Просмотр исходного кода

发布 v0.3.0:将角色与固定成员群聊迁入 Web

LSamien 2 месяцев назад
Родитель
Сommit
5ca7879b0a
100 измененных файлов с 4302 добавлено и 36216 удалено
  1. 0 5
      Dockerfile
  2. 31 377
      README.md
  3. 2 5
      bin/hermes-yaoyao-updater.mjs
  4. 21 270
      docs/agent-install.md
  5. 19 0
      docs/releases/v0.3.0.md
  6. 33 0
      docs/workspace-acceptance.md
  7. 38 0
      docs/workspace-chat.md
  8. 0 62
      hermes-plugins/yaoyao/dashboard/data_paths.py
  9. 0 1075
      hermes-plugins/yaoyao/dashboard/dist/index.js
  10. 0 934
      hermes-plugins/yaoyao/dashboard/dist/index.v1.1.0.js
  11. 0 934
      hermes-plugins/yaoyao/dashboard/dist/index.v1.2.0.js
  12. 0 934
      hermes-plugins/yaoyao/dashboard/dist/index.v1.3.0.js
  13. 0 934
      hermes-plugins/yaoyao/dashboard/dist/index.v1.4.0.js
  14. 0 433
      hermes-plugins/yaoyao/dashboard/dist/style.css
  15. 0 433
      hermes-plugins/yaoyao/dashboard/dist/style.v1.1.0.css
  16. 0 433
      hermes-plugins/yaoyao/dashboard/dist/style.v1.2.0.css
  17. 0 433
      hermes-plugins/yaoyao/dashboard/dist/style.v1.3.0.css
  18. 0 433
      hermes-plugins/yaoyao/dashboard/dist/style.v1.4.0.css
  19. 0 2050
      hermes-plugins/yaoyao/dashboard/group_gateway.py
  20. 0 290
      hermes-plugins/yaoyao/dashboard/group_node_registry.py
  21. 0 341
      hermes-plugins/yaoyao/dashboard/group_node_worker.py
  22. 0 3776
      hermes-plugins/yaoyao/dashboard/group_orchestrator.py
  23. 0 1769
      hermes-plugins/yaoyao/dashboard/group_plugin_api.py
  24. 0 601
      hermes-plugins/yaoyao/dashboard/group_protocol.py
  25. 0 488
      hermes-plugins/yaoyao/dashboard/group_remote_gateway.py
  26. 0 7432
      hermes-plugins/yaoyao/dashboard/group_store.py
  27. 0 413
      hermes-plugins/yaoyao/dashboard/group_stream.py
  28. 0 11
      hermes-plugins/yaoyao/dashboard/manifest.json
  29. 0 858
      hermes-plugins/yaoyao/dashboard/plugin_api.py
  30. 0 510
      hermes-plugins/yaoyao/dashboard/poller.py
  31. 0 1166
      hermes-plugins/yaoyao/dashboard/store.py
  32. 0 84
      hermes-plugins/yaoyao/dashboard/tests/test_data_paths.py
  33. 0 229
      hermes-plugins/yaoyao/dashboard/tests/test_file_library_contract.py
  34. 0 27
      hermes-plugins/yaoyao/dashboard/tests/test_frontend_contract.py
  35. 0 1014
      hermes-plugins/yaoyao/dashboard/tests/test_group_host_contract.py
  36. 0 285
      hermes-plugins/yaoyao/dashboard/tests/test_group_merge_contract.py
  37. 0 2384
      hermes-plugins/yaoyao/dashboard/tests/test_group_settings_contract.py
  38. 0 1965
      hermes-plugins/yaoyao/dashboard/tests/test_group_topics_contract.py
  39. 0 104
      hermes-plugins/yaoyao/dashboard/tests/test_poller_contract.py
  40. 0 48
      hermes-plugins/yaoyao/dashboard/tests/test_voice_settings_contract.py
  41. 0 487
      hermes-plugins/yaoyao/dashboard/voice_store.py
  42. 0 4
      hermes-plugins/yaoyao/plugin.yaml
  43. 2 2
      package-lock.json
  44. 3 2
      package.json
  45. 1 0
      playwright.config.ts
  46. 22 0
      playwright.workspace.config.ts
  47. 3 4
      release.json
  48. 1 6
      scripts/verify-release.mjs
  49. 2 6
      src/client/App.vue
  50. 3 3
      src/client/api/sessions.ts
  51. 0 16
      src/client/api/systemUpdate.ts
  52. 4 2
      src/client/components/app/SettingsCenterDialog.vue
  53. 0 4
      src/client/components/app/SystemUpdateDialog.vue
  54. 0 4
      src/client/components/app/SystemUpdatePanel.vue
  55. 20 19
      src/client/components/app/WorkspaceShell.vue
  56. 1 0
      src/client/components/library/types.ts
  57. 1 2
      src/client/components/messages/MarkdownContent.vue
  58. 114 0
      src/client/components/workspace/ConversationList.vue
  59. 127 0
      src/client/components/workspace/WorkspaceNodesPanel.vue
  60. 167 0
      src/client/components/workspace/WorkspaceVoiceProviders.vue
  61. 2 1
      src/client/components/workspace/viewModels.ts
  62. 2 2
      src/client/router/index.ts
  63. 11 2
      src/client/stores/files.ts
  64. 1 0
      src/client/utils/normalize.ts
  65. 991 0
      src/client/views/ConversationsView.vue
  66. 5 0
      src/client/views/FilesView.vue
  67. 61 16
      src/server/app.ts
  68. 0 20
      src/server/config.ts
  69. 18 302
      src/server/pushEventAdapter.ts
  70. 0 263
      src/server/pushEvents.ts
  71. 2 2
      src/server/realtimeApi.ts
  72. 25 28
      src/server/realtimeBroker.ts
  73. 1 3
      src/server/releases.ts
  74. 31 710
      src/server/routes.ts
  75. 4 8
      src/server/updateManager.ts
  76. 0 1
      src/server/upstream.ts
  77. 2 15
      src/server/upstreamReadCache.ts
  78. 173 0
      src/server/workspaceAssets.ts
  79. 254 0
      src/server/workspaceGateway.ts
  80. 549 0
      src/server/workspaceRoutes.ts
  81. 693 0
      src/server/workspaceRuntime.ts
  82. 369 0
      src/server/workspaceStore.ts
  83. 1 0
      src/shared/types.ts
  84. 92 0
      src/shared/workspace.ts
  85. 3 3
      tests/client/remoteNodeFiles.test.ts
  86. 0 3
      tests/client/systemUpdate.test.ts
  87. 1 1
      tests/client/systemUpdatePanel.test.ts
  88. 83 0
      tests/e2e/workspace-chat.spec.ts
  89. 232 0
      tests/fixtures/workspace-server.ts
  90. 1 3
      tests/server/agentManagementRoutes.test.ts
  91. 6 317
      tests/server/app.test.ts
  92. 2 63
      tests/server/localAuthRoutes.test.ts
  93. 1 1
      tests/server/offlineSystemUpdate.test.ts
  94. 2 7
      tests/server/pairing.test.ts
  95. 61 158
      tests/server/pushEventAdapter.test.ts
  96. 0 53
      tests/server/pushEvents.test.ts
  97. 3 83
      tests/server/pushRoutes.test.ts
  98. 2 39
      tests/server/pushRuntime.test.ts
  99. 1 9
      tests/server/security.test.ts
  100. 2 2
      tests/server/systemUpdateRoutes.test.ts

+ 0 - 5
Dockerfile

@@ -13,7 +13,6 @@ COPY index.html ./
 COPY public ./public
 COPY scripts ./scripts
 COPY src ./src
-COPY hermes-plugins/yaoyao ./hermes-plugins/yaoyao
 
 RUN npm run build \
   && npm prune --omit=dev
@@ -34,10 +33,6 @@ COPY --chown=node:node package.json package-lock.json release.json ./
 COPY --chown=node:node --from=builder /app/node_modules ./node_modules
 COPY --chown=node:node --from=builder /app/dist ./dist
 COPY --chown=node:node --from=builder /app/dist-server ./dist-server
-# Keep the Dashboard plugin in the offline image as an installation payload.
-# Hermes itself owns plugin discovery, configuration, and restart, so this is
-# deliberately not copied into the Web container's runtime data directory.
-COPY --chown=node:node hermes-plugins/yaoyao /opt/hermes-yaoyao-plugin
 
 USER node
 

+ 31 - 377
README.md

@@ -1,403 +1,57 @@
 # 夭夭 Web
 
-夭夭 Web 是一个独立的本地 Web 工作台,通过端口 `8800` 连接 Hermes Dashboard/Gateway `9119`,提供普通聊天、群聊、文件库和产物浏览。通过本项目安装的 LaunchAgent 会持续监督本机 `9119`:缺失时在 `127.0.0.1` 启动它,不自动写入账号密码,也不重启或重绑定已有服务。
+当前发布版本:**v0.3.0**,配套 iOS **1.3(164)**。详见 [发布说明](docs/releases/v0.3.0.md)。
 
-## 8800 用户与 iOS
+夭夭 Web 为网页和 iOS 提供统一的 Agent、群聊、文件库及语音配置服务。Hermes 通过标准 9119 HTTP/WebSocket 接口执行任务;无需安装 Yaoyao 插件。
 
-8800 拥有独立于 9119 的用户机制。首次安装会创建管理员 `admin/admin`,首次登录
-必须修改凭据。管理员可在“系统管理”中创建、禁用、删除普通用户和重置临时密码。
-所有 8800 用户共享本机 9119 的 Bots、历史、团队和文件;普通用户不能管理用户、
-节点、插件或系统升级。
+## 聊天与 Agent
 
-iOS/Web 连接 `http://主机:8800` 并使用 8800 用户登录,客户端实时接口仅支持 HTTP+SSE。
-从 v0.2.27 起,旧客户端 WebSocket、票据和租约接口已移除;iOS 必须同步更新到 HTTP+SSE 版本。
-9119 和 8800 都可管理由 8800 签发配对码的直接子节点,节点不会递归暴露孙节点。
-已登录 Web 用户还可在“手机登录与节点”中生成两分钟有效的一次性登录二维码;iOS
-登录页扫描后会把 8800 保存为普通服务器账号。`yaoyao://login` 登录码与
-`yaoyao://pair` 子节点码相互独立,不会把手机误登记为子节点。
+- 在已有 Hermes Profile 基础上创建角色,填写名称、头像、提示词和规则。创建不会复制或修改基础 Profile。
+- 每个角色只有一条连续单聊;角色可加入多个群聊。单聊与各群聊分别使用独立会话。
+- 聊天列表混排角色单聊与群聊,不含默认 Profile 对话,没有独立话题列表。
+- 群成员创建后固定。可修改群规则、管理员、协作方式和自动回复轮数;默认管理员协调、3 轮。
+- 角色规则在下一次执行生效。归档角色隐藏单聊并禁止加入新群,但不改变已有群成员。
+- 原生对话保留独立入口,由 Web 转发给 Hermes。
+- 新聊天、事件及文件按登录用户隔离;基础 Profile 的工具、技能和既有记忆能力继续由 Hermes 管理。
 
-8800 直连 `127.0.0.1`(或 `::1`),且 9119 明确声明 `auth_required=false` 时,
-使用 Hermes 签发的本机临时会话令牌,无需配置 9119 用户名密码。令牌仅保存在服务端内存,
-不返回客户端;REST 和上游 WebSocket 均携带该凭据。远程或已开启账号鉴权的 9119
-仍使用独立服务账号,可在“系统管理”中配置,或设置
-`HERMES_YAOYAO_UPSTREAM_USERNAME` 和 `HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE`。
-`localhost`、Docker 宿主机别名和转发头不作为本机授权依据;详见 [本机授权边界](docs/loopback-authorization.md)。
+## 运行
 
-### iOS 后台消息推送
+需要 Node.js 24 和可通过标准 API 访问的 Hermes 9119 服务。
 
-iOS 在线时使用 8800 的 SSE 实时接收消息;App 被挂起或未运行时,8800
-可作为 APNs Provider 发送系统通知。推送设备与当前 8800 用户绑定,普通聊天只提醒
-该用户经 8800 发起的任务;团队在用户首次发言后自动订阅,也可在团队页关闭。
-
-在 Apple Developer 中为 `cn.samien.yaoyao.hermes` 开启 Push Notifications 并创建
-Token Key,把下载的 `.p8` 保存在仓库外、权限设为 `0600`,然后为 8800 配置:
-
-```bash
-export HERMES_YAOYAO_APNS_KEY_FILE=/absolute/path/to/AuthKey_XXXXXXXXXX.p8
-export HERMES_YAOYAO_APNS_KEY_ID=XXXXXXXXXX
-export HERMES_YAOYAO_APNS_TEAM_ID=GMU6W5FKQ6
-export HERMES_YAOYAO_APNS_TOPIC=cn.samien.yaoyao.hermes
-```
-
-前三项必须同时存在;缺失或无效时聊天服务仍会启动,iOS 自动保留原有本地通知降级。
-管理员可在“系统管理 → iOS 消息推送”查看配置、注册设备和待发送数量,页面与日志均
-不会显示 `.p8` 内容或 device token。Docker 部署需要把 `.p8` 只读挂载到容器,并让
-`HERMES_YAOYAO_APNS_KEY_FILE` 指向容器内绝对路径。APNs 只要求 8800 能主动访问
-Apple,不需要把 8800 暴露到公网;手机访问 8800 仍应优先使用 HTTPS 或 Tailscale。
-
-未设置任何 `HERMES_YAOYAO_APNS_*` 环境变量时,管理员也可以在“系统管理 → iOS
-消息推送”填写 **8800 所在机器上的 `.p8` 绝对路径**、Key ID、Team ID、Topic 及启用
-环境,然后点击“验证并启用”。私钥内容不会经过浏览器;8800 会本地读取 P-256 密钥、
-探测所选 APNs 环境,再把路径和元数据原子保存到
-`$HERMES_YAOYAO_HOME/push/apns-config.json`(权限 `0600`)并立即热加载。密钥文件权限
-宽于 `0600` 只显示安全建议,不会阻止启用。任一 APNs 环境变量存在时仍以环境变量为准,
-Web 界面只读,避免两个配置源互相覆盖。
-
-### Android 后台消息推送
-
-Android 使用 FCM HTTP v1 的高优先级 data-only 消息;通知标题、摘要、去重 `eventId`
-和更新用 `collapseId` 由 App 统一处理。FCM 与 APNs 是两个独立 provider:任一方配置或
-发送失败都不会停用另一方,团队订阅、事件去重和后台任务恢复继续共用同一份持久状态。
-
-在 Firebase 项目中注册包名 `cn.samien.yaoyao.hermes`,为专用服务账号授予发送 FCM
-消息所需的最小权限。把服务账号 JSON 保存在仓库外、权限设为 `0600`,然后配置:
-
-```bash
-export HERMES_YAOYAO_FCM_SERVICE_ACCOUNT_FILE=/absolute/path/to/firebase-service-account.json
-export HERMES_YAOYAO_FCM_PROJECT_ID=your-firebase-project-id
-export HERMES_YAOYAO_FCM_PACKAGE_NAME=cn.samien.yaoyao.hermes
-```
-
-也可以在“系统管理 → Android 消息推送”填写 8800 所在机器上的 JSON 绝对路径、Project
-ID 和包名。浏览器只提交路径和公开元数据;8800 本地校验 RSA 凭据,并通过
-`validate_only` 发送探测确认该账号对目标项目具有消息权限,然后把路径和元数据原子保存到
-`$HERMES_YAOYAO_HOME/push/fcm-config.json`。配置文件不会复制 JSON 私钥或设备 FID。
-任一 `HERMES_YAOYAO_FCM_*` 环境变量存在时,Web 界面保持只读。Docker 部署时需把服务
-账号文件只读挂载到容器,并允许 8800 主动访问 Google OAuth 与 FCM HTTP v1 端点。
-
-仓库同时归档了夭夭的 Hermes Dashboard 插件,位于
-[`hermes-plugins/yaoyao/dashboard`](hermes-plugins/yaoyao/dashboard)。Web 工作台和该插件是两个独立部署单元:前者运行在 `8800`,后者由已运行的 Hermes Dashboard 在 `9119` 加载。
-
-插件根目录同时提供 Hermes 标准 `plugin.yaml`,可通过 Dashboard 的 Git
-插件安装接口安装。默认源为
-`https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao`。
-
-当前发布版本:**Git `v0.2.31` / 夭夭 Web `0.2.31` / Hermes Dashboard 插件 `1.7.3`**。版本组合由仓库根目录的 `release.json` 唯一声明,并由 `npm run release:verify` 校验。
-
-本版支持 Web 独立检查更新、升级和回滚,9119 离线、超时或认证失败不再阻塞升级。8800 仍保留管理员登录及安全校验,并兼容 9119 的本机 Session Token、密码认证和旧版本机直连模式;9119 可保持仅本机监听,8800 继续面向局域网提供服务。
-
-普通聊天和团队事件继续使用 [HTTP+SSE 接口](docs/http-sse-realtime.md),不兼容旧客户端 WebSocket。8800 到 9119 的上游接口及 Python 插件保持不变。
-
-需要由自动化 Agent 部署或升级时,请直接使用 [Agent 安装手册](docs/agent-install.md)。其中包含固定版本校验、备份、同步、单一 Dashboard 重载与验证步骤。
-
-## 安装 Hermes Dashboard 插件
-
-前提是目标机器已安装并可运行 Hermes。插件目录会被 Hermes 以路径加载,因此请保留下面的目录层级,不要只复制其中的 Python 文件或 `dist/`。
-
-```text
-<Hermes 数据目录>/plugins/yaoyao/dashboard/
-├── manifest.json
-├── plugin_api.py
-├── group_plugin_api.py
-└── dist/
-```
-
-默认 Hermes 数据目录是 `~/.hermes`。从本仓库根目录执行下列命令即可安装或更新插件;首次覆盖已有版本时会先创建带时间戳的备份:
-
-```bash
-HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
-PLUGIN_DIR="$HERMES_HOME/plugins/yaoyao/dashboard"
-
-if [ -d "$PLUGIN_DIR" ]; then
-  cp -a "$PLUGIN_DIR" "${PLUGIN_DIR}.backup-$(date +%Y%m%d%H%M%S)"
-fi
-
-mkdir -p "$PLUGIN_DIR"
-rsync -a --delete \
-  --exclude '__pycache__/' \
-  --exclude '*.py[cod]' \
-  --exclude '.pytest_cache/' \
-  hermes-plugins/yaoyao/dashboard/ "$PLUGIN_DIR/"
-```
-
-`rsync --delete` 只会删除目标 `dashboard/` 目录中仓库未提供的旧插件文件,不会触及其他 Hermes 插件或数据;如需保留本机额外文件,请先移出该目录或不要使用 `--delete`。
-
-安装后需显式启用夭夭插件。Dashboard 对用户目录下的插件采用默认拒绝策略:文件已复制不代表前端资源或 API 已加载。
-
-先查看当前启用列表:
-
-```bash
-hermes config get plugins.enabled
-```
-
-若输出为 `[]`,可直接启用夭夭:
-
-```bash
-hermes config set plugins.enabled '["yaoyao"]'
-```
-
-若已有其他条目,请在保留原有插件名的前提下,将 `yaoyao` 加入同一 JSON 列表后再写回。不要只依赖 `hermes plugins list` 判断夭夭是否加载:夭夭是 Dashboard 扩展,最终应以 Dashboard 的插件清单和启动日志为准。
-
-然后停止 Dashboard,使运行中的 `9119` 进程重新加载插件。已安装的夭夭 Web LaunchAgent 会在下一轮检查中自动按其配置重启它:
-
-```bash
-hermes dashboard --stop
-```
-
-通过状态命令、插件清单和日志确认 Dashboard 已恢复且已加载夭夭:
-
-```bash
-hermes dashboard --status
-curl --noproxy '*' --fail --silent http://127.0.0.1:9119/api/dashboard/plugins
-tail -n 100 ~/.hermes/logs/gui.log
-```
-
-验收时,插件清单应包含 `"name":"yaoyao"`,日志应包含 `Mounted plugin API routes: /api/plugins/yaoyao/`。夭夭 API 需要 Dashboard 登录会话,匿名请求返回 `401`、插件静态资源跳转到登录页均属预期。
-
-若 Hermes 由 LaunchAgent、服务管理器或其他外部监督器启动,请使用该监督器重启 Dashboard;不要在 `hermes dashboard --stop` 后同时手动执行 `hermes dashboard --no-open`,以免产生重复监听进程。
-
-插件的归档数据与运行状态仍位于 Hermes 数据目录中,不在此仓库的 `hermes-plugins/` 中;升级插件前的备份也不应提交到 Git。
-
-### 通过 8800 安全编排 9119 安装
-
-登录夭夭 Web 后,可以调用受登录、Origin 和 CSRF 保护的接口:
-
-```http
-POST /api/app/plugins/yaoyao/install
-Content-Type: application/json
-
-{"force":false}
-```
-
-全新安装使用 `force:false`;已安装版本升级必须明确使用 `force:true`。8800
-只会把服务端配置的固定 Git 源交给 9119,不接受浏览器传入任意仓库地址。
-可通过 `HERMES_YAOYAO_PLUGIN_SOURCE` 覆盖默认源,且配置中禁止嵌入用户名或
-密码。
-
-插件数据会从旧的 `<profile-home>/plugins/yaoyao/data` 一次性迁移到
-`<profile-home>/plugin-data/yaoyao`。如果旧、新目录同时包含数据,安装接口会
-返回 `409 yaoyao_storage_conflict`,不会覆盖任一目录;运行时仍以
-`plugin-data/yaoyao` 为唯一权威目录,不会回退读取旧数据。旧版插件没有迁移检查
-接口时,也会返回 `409 yaoyao_storage_migration_required`;此时先按上面的
-`dashboard/` 局部同步方式安装一次当前兼容版本并重启,之后才能使用一键升级。
-
-安装、覆盖、启用和加载均由 9119 自身处理;8800 不重启 9119,也不读写 Hermes
-插件目录。登录 Web 后还会比较发布清单与 9119 的实际插件版本,落后时自动通过
-同一接口更新。
-
-### Web 独立升级
-
-macOS 受管服务可在左下角 Agent 菜单中打开“系统更新”。Git 发布标签负责 Web
-版本,`release.json` 同时声明兼容的插件版本;插件本身始终通过 9119 独立同步。
-
-独立升级能力从 `v0.2.30` 生效。旧版首次升级仍使用旧更新器:请在 9119 可用时升级一次,或按固定标签手动部署新版;升级后不再要求 9119 在线。
-
-升级接口固定读取 `HERMES_YAOYAO_RELEASE_SOURCE`,只接受发布源中最新的
-`vX.Y.Z` 标签,并在下载后核对标签解析出的 Git 提交和发布清单。浏览器不能传入
-仓库地址或任意提交。所有更新接口都要求 8800 本地管理员登录,写接口仍受 Origin 和 CSRF 保护;默认还要求
-请求来自本机,可通过 `HERMES_YAOYAO_ALLOW_REMOTE_UPDATE=1` 明确允许远程管理。
-
-首次成功升级会把运行文件迁入:
-
-```text
-~/.local/share/hermes-yaoyao/
-├── releases/<版本>-<提交>/
-└── current -> releases/<版本>-<提交>
-```
-
-检查、执行、查询任务和回滚 Web 都不连接 9119,也不会先检测或更新插件。
-9119 离线、响应超时、认证失败或插件版本落后均不阻止 Web 升级;Git 发布源仍需可访问。
-登录初始化最多等待上游 3 秒,超时后仍可进入设置管理和更新 Web。
-独立 updater 只下载、构建和切换 Web 的 `current`,不会停止 9119、调用 `hermes config` 或读写
-`HERMES_HOME`。升级和回滚只用 `/healthz` 验证 Web 自身;`/readyz` 保留上游连通性诊断,
-不参与升级成败判定。Web 验证失败时只回滚 Web;插件由 9119 恢复后独立同步。
-用户数据始终留在 `~/.hermes-yaoyao` 和
-`~/.hermes/plugin-data/yaoyao`,不进入版本目录。
-
-相关接口:
-
-```text
-GET  /api/app/system/update/status
-POST /api/app/system/update/check
-POST /api/app/system/update/apply
-GET  /api/app/system/update/jobs/:jobID
-POST /api/app/system/update/rollback
-```
-
-容器和非 macOS 环境只显示版本状态,不执行服务内升级;应通过替换镜像更新。
-
-## 开发
-
-```bash
-npm install
-cp .env.example .env
-npm run dev
-```
-
-## 手机扫码与跨节点 Agent
-
-插件 `1.7.3` 与当前 Web 服务共同提供 Hermes 节点配对。每台参与设备都需要安装相同版本的夭夭插件并运行 Web 服务:
-
-1. 在目标 Hermes 的夭夭 Web 左下角打开“手机登录与节点”。
-2. 生成两分钟有效、只能使用一次的“子节点配对二维码”。
-3. 在夭夭 iOS 的“设置 → 远程节点”中扫描;节点的 Agent 名称、头像和文件访问权限会随配对一起注册到当前父服务器。
-4. 扫描后,该节点的 Bots、普通聊天历史和 Agent Profile 会按节点身份加入手机;同名 Profile 使用 `nodeId + profile` 区分。
-
-二维码不包含账号密码、长期 Token 或 Dashboard Cookie。Web 服务会签发可撤销的设备 Token,并把代理所需的 Dashboard Cookie 加密保存在 `HERMES_YAOYAO_HOME`。iOS Token 按服务器账号保存在系统 Keychain。忘记 iOS 中的节点或在 Web 中撤销设备都会终止后续访问。
-
-当前免密扫码签发要求 Hermes 启用 `basic` 密码 provider,以便为每台手机建立彼此独立、可单独刷新的上游会话;不会复制浏览器正在轮换的 refresh Cookie。仅启用 OAuth/SSO 的安装仍可在 iOS 中使用手动“添加服务器账号”,等待 Hermes 提供适合移动回调的原生授权方式。
-
-原生群聊由房主 Hermes 保存权威房间、话题和消息。扫码时,iOS 会把远端节点以加密凭据注册到房主插件;房主通过远端 `nodeWorker` 执行 Session,并转发流式事件、审批、澄清、中断和受限群聊附件。房主工作目录不会作为远端绝对路径使用,远端 Agent 默认采用自己的工作区。
-
-免密配对和跨节点执行应使用 HTTPS 或 Tailscale。受管安装会显式设置 `HERMES_YAOYAO_ALLOW_INSECURE_LAN=1`,因此默认 HTTP 监听只适合可信局域网;不要把二维码或配对凭据发送给不受信任的人。
-
-## 网络暴露:9119 与 8800 分别控制
-
-通过 `service install` 安装的受管服务默认只开放夭夭 Web `8800` 到可信局域网;新启动的 Hermes Dashboard `9119` 仅监听回环。手动 `npm start` 与 Docker 部署仍保留各自的绑定默认值。
-
-| 端口 | 服务 | 默认 | 单独开启局域网 |
-| --- | --- | --- | --- |
-| `9119` | Hermes Dashboard | `127.0.0.1` | 不自动开放;已有服务保持原配置,远程服务必须启用鉴权 |
-| `8800` | 夭夭 Web | `0.0.0.0` | LaunchAgent 显式启用可信局域网 HTTP |
-
-夭夭 Web 默认上游仍是 `http://127.0.0.1:9119`;客户端只连接 8800。监督器仅管理此本机 HTTP 端口,不替外部上游启动本机 Dashboard。
-
-受管 `service install` 会覆盖 8800 遗留的 loopback 环境并保持 8800 局域网监听。若 8800 也必须仅本机访问,请使用手动 `npm start` 或 Docker 的回环绑定,不要使用受管 LaunchAgent。
-
-默认局域网 HTTP 只适合可信网络。跨不受信网络使用时必须配置 `HERMES_YAOYAO_TLS_CERT` 和 `HERMES_YAOYAO_TLS_KEY`,并限制防火墙或反向代理访问范围。
-
-受管服务不创建或修改 `dashboard.basic_auth`。已有密码配置不会被删除;若 9119
-仍要求账号鉴权,需在 8800 配置服务账号,不会自动降级成免账号模式。
-8800 本地管理员 `admin/admin` 首次登录强制修改。具体步骤见
-[Agent 安装手册](docs/agent-install.md#受管-9119-的默认认证与持续监督)。
-Dashboard 的 `--insecure` 参数不会关闭认证;不要并行安装其他 Dashboard 监督器。
-
-## 构建与运行
-
-```bash
+```sh
+npm ci
 npm run build
 npm start
 ```
 
-服务管理命令:
-
-```bash
-node bin/hermes-yaoyao.mjs service install
-node bin/hermes-yaoyao.mjs service start
-node bin/hermes-yaoyao.mjs service status
-node bin/hermes-yaoyao.mjs service stop
-node bin/hermes-yaoyao.mjs service uninstall
-```
-
-执行 `npm link` 后也可以直接使用 `hermes-yaoyao` 命令。
-
-运行数据默认位于 `~/.hermes-yaoyao`。卸载 LaunchAgent 不会删除运行数据。
-
-## Docker 部署(仅夭夭 Web 8800)
-
-Docker 镜像运行时只启动本项目的夭夭 Web,不监督或重启 Hermes Dashboard。
-`9119` 必须已经由项目外部的 Hermes 实例提供;Compose 会强制关闭
-`HERMES_YAOYAO_SUPERVISE_DASHBOARD`。用户登录 Web 后,8800 会通过 9119 的
-插件安装接口自动补齐落后的夭夭插件,不会直接操作 Hermes 容器或数据卷。为支持
-离线部署,镜像仍携带 `/opt/hermes-yaoyao-plugin/dashboard` 作为手动安装材料。
-
-复制 Docker 环境示例并启动:
-
-```bash
-cp docker.env.example docker.env
-docker compose --env-file docker.env up -d --build
-```
-
-默认行为:
-
-- 只把容器的 `8800` 发布到宿主机 `127.0.0.1:8800`;
-- 通过 `http://host.docker.internal:9119` 连接宿主机已有的 Dashboard;
-- 将 CSRF 密钥、设备配对信息和上传索引保存在命名卷 `hermes-yaoyao_yaoyao-data`;
-- 以非 root 用户和只读根文件系统运行容器。
-
-若本机 `8800` 已被占用,只需在 `docker.env` 中将
-`HERMES_YAOYAO_PUBLISHED_PORT` 改为未占用端口(例如 `8801`),再重新执行
-`docker compose --env-file docker.env up -d`。容器内服务和默认发布端口仍为
-`8800`,并且 Compose 已允许通过 `localhost` 和 `127.0.0.1` 使用这个替代端口。
-
-查看状态与日志:
-
-```bash
-docker compose --env-file docker.env ps
-docker compose --env-file docker.env logs -f web
-curl --fail --silent http://127.0.0.1:8800/healthz
-curl --fail --silent http://127.0.0.1:8800/readyz
-```
-
-`/healthz` 只检查 8800 自身,`/readyz` 还会检查配置的 9119 是否可达。若 Dashboard 在另一台机器或另一个容器中,请在 `docker.env` 中把 `HERMES_YAOYAO_UPSTREAM` 改为容器可访问的 `http://主机:9119`;不要把账号密码写进该 URL。
-
-Docker Desktop 会把 `host.docker.internal` 转发到宿主机。Linux 上的 `host-gateway` 只负责解析宿主机地址:如果外部 9119 仍只监听宿主机 `127.0.0.1`,桥接网络中的容器无法连接它。此时应让现有 Dashboard 在有认证和防火墙保护的前提下监听容器可达的宿主机地址,或由部署方改用经过评估的 host 网络方案;Compose 本身不会更改 9119 的监听配置。
-
-如需经可信局域网或反向代理访问,可将 `HERMES_YAOYAO_BIND_ADDRESS` 改为 `0.0.0.0`。首次使用外网域名或公网 IP 前,可先从 `localhost:8800` 进入“设置中心 → Hermes 连接 → 外网访问地址”添加;也可继续通过 `HERMES_YAOYAO_ALLOWED_HOSTS` 配置,环境变量地址会与 Web 设置合并。Compose 内部的 8800 使用 HTTP;对非可信网络发布时,应在容器前配置 HTTPS 反向代理,不要直接把 8800 暴露到公网。
-
-停止或升级不会删除运行数据:
+默认 Web 地址为 `http://127.0.0.1:8800`,上游为 `http://127.0.0.1:9119`。首次使用 `admin/admin` 登录并修改密码。远端 Hermes 的凭据可在系统设置中配置。
 
-```bash
-docker compose --env-file docker.env down
-docker compose --env-file docker.env up -d --build
+```sh
+HERMES_YAOYAO_UPSTREAM=http://服务器:9119 npm start
 ```
 
-只有显式执行 `docker compose down --volumes` 才会删除夭夭 Web 的命名卷。在线
-环境会在登录后通过 9119 自动更新插件;下方手动步骤仅用于离线安装或旧插件缺少
-安全迁移接口的兼容处理。
+Web 数据默认保存在 `~/.hermes-yaoyao`,可用 `HERMES_YAOYAO_HOME` 指定。备份应包含整个数据目录及加密密钥。Docker 使用 `/var/lib/hermes-yaoyao` 持久化卷,不需要 Python、Hermes 文件系统挂载或插件安装载荷。
 
-### Docker Hermes 容器的插件安装
+## iOS
 
-`Plugin 'yaoyao' is not installed or bundled.` 表示报错的 **Hermes 容器** 的持久化目录中没有插件;重启或重建夭夭 Web 容器不会修复它。先确认 Hermes 容器把数据目录持久化到 `/root/.hermes`(或该镜像实际使用的 Hermes 数据目录)。没有持久化挂载时,`docker cp` 的内容会在 Hermes 重建后丢失。
+iOS 统一连接 Web 地址,通过设置中的手机登录二维码或账号密码登录。不能再直接填写 9119 地址。原有直连账号需要重新配置为 Web 地址;不会自动改端口或删除旧缓存。
 
-离线镜像已加载后,用它携带的插件材料复制到 Hermes 容器。将下面的 `hermes` 替换为实际 Hermes 容器名,并按实际数据目录替换 `/root/.hermes`:
-
-```bash
-WEB_IMAGE=hermes-yaoyao:local
-HERMES_CONTAINER=hermes
-HERMES_HOME=/root/.hermes
-SOURCE_CONTAINER=$(docker create "$WEB_IMAGE")
-
-docker exec "$HERMES_CONTAINER" mkdir -p "$HERMES_HOME/plugins/yaoyao/dashboard"
-docker cp "$SOURCE_CONTAINER":/opt/hermes-yaoyao-plugin/dashboard/. \
-  "$HERMES_CONTAINER":"$HERMES_HOME/plugins/yaoyao/dashboard/"
-docker rm "$SOURCE_CONTAINER"
-```
+## 数据与升级
 
-随后保留现有启用列表并加入 `yaoyao`,再重启 **Hermes 容器** 使其重新发现插件。若当前没有其他用户插件,命令为:
+新体系从空数据开始,不导入旧插件的团队、话题、文件或配置。旧 Hermes 数据及已安装插件原地留存,Web 不再访问、升级或卸载它们。发布清单只记录 Web 版本,Web 自身升级功能保留。首次切换请整体替换 Web 部署并配套更新 iOS。
 
-```bash
-docker exec "$HERMES_CONTAINER" hermes config set plugins.enabled '["yaoyao"]'
-docker restart "$HERMES_CONTAINER"
-```
+Kanban 仍是可选的独立功能,其插件不在本次迁移范围内。
 
-若 `hermes config get plugins.enabled` 已有其他插件名,请把 `yaoyao` 合并进同一个 JSON 列表后再设置,不能用上面的示例覆盖它们。最后从 Hermes 容器或能访问其 `9119` 的位置确认插件清单包含 `"name":"yaoyao"`:
+## 开发验证
 
-```bash
-docker exec "$HERMES_CONTAINER" hermes config get plugins.enabled
-curl --fail --silent http://127.0.0.1:9119/api/dashboard/plugins
+```sh
+npm run typecheck
+npm test
+npm run build
 ```
 
-注意:当前安全边界要求群聊上传和宿主机绝对路径媒体只用于回环地址的 Hermes 上游。默认桥接网络中的 `host.docker.internal` 不属于容器回环地址,因此这两类本地文件功能会返回明确的不可用错误;普通聊天、群聊消息、文件库 API 和产物代理不受此限制。不要通过关闭该检查来让不同机器共享本地文件路径。
-
-## 受管服务操作与验收
-
-`service install` 会写入并启动 `com.samien.hermes-yaoyao` LaunchAgent;8800 默认监听局域网,新启动的受监督 9119 仅监听回环。已安装服务的环境变量写入 plist,因此改变监听地址、TLS 或监督开关后需要再次执行 `service install`,仅执行 `service start` 不会刷新这些配置。
+新体系契约见 [聊天接口与运行模型](docs/workspace-chat.md),安装步骤见 [部署说明](docs/agent-install.md)。
 
-| 目标 | 命令 | 预期结果 |
-| --- | --- | --- |
-| 查看服务 | `node bin/hermes-yaoyao.mjs service status` | `com.samien.hermes-yaoyao` 为 running |
-| 查看 Web | `curl --noproxy '*' --fail --silent http://127.0.0.1:8800/` | 返回夭夭 Web 页面 |
-| 查看 Dashboard | `curl --noproxy '*' --fail --silent http://127.0.0.1:9119/api/status` | 查看 `auth_required`;`false` 表示本机令牌模式 |
-| 查看监听器 | `lsof -nP -iTCP:8800 -sTCP:LISTEN` 与 `lsof -nP -iTCP:9119 -sTCP:LISTEN` | 每个端口恰好一个监听进程 |
-| 查看受管日志 | `tail -f ~/Library/Logs/hermes-yaoyao.log` | 记录 Web 监听和 Dashboard 监督事件 |
-
-在部分 macOS 环境中,`service install` 内部的 `launchctl bootstrap` 可能返回 `Bootstrap failed: 5: Input/output error`。先验证 plist 再使用等效兼容回退,不要重复创建服务:
-
-```bash
-plutil -lint ~/Library/LaunchAgents/com.samien.hermes-yaoyao.plist
-launchctl load -w ~/Library/LaunchAgents/com.samien.hermes-yaoyao.plist
-node bin/hermes-yaoyao.mjs service status
-```
+## 许可证
 
-手动以 `npm start` 运行时,`HERMES_YAOYAO_SUPERVISE_DASHBOARD` 默认关闭;如需让该进程监督 Dashboard,请显式设置为 `1`。生产环境优先使用上述 LaunchAgent,避免两个进程同时管理 `9119`。
+BSL-1.1,详见仓库 LICENSE。

+ 2 - 5
bin/hermes-yaoyao-updater.mjs

@@ -31,7 +31,7 @@ function writeJSON(path, value) {
 
 export function validateManifest(value) {
   if (!value || typeof value !== 'object' || value.schemaVersion !== 1) fail('release.json 格式无效')
-  for (const key of ['releaseVersion', 'webVersion', 'pluginVersion']) {
+  for (const key of ['releaseVersion', 'webVersion']) {
     if (typeof value[key] !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value[key])) {
       fail(`release.json ${key} 无效`)
     }
@@ -231,7 +231,7 @@ function stageRelease(job, jobPath) {
   updateJob(jobPath, { state: 'downloading', message: `正在下载 ${target.gitTag}` })
   run('git', ['clone', '--quiet', '--depth', '1', '--single-branch', '--branch', target.gitTag, plan.source, staging], { timeout: 600_000 })
   const manifest = validateManifest(readJSON(join(staging, 'release.json')))
-  for (const field of ['schemaVersion', 'releaseVersion', 'webVersion', 'pluginVersion', 'gitTag']) {
+  for (const field of ['schemaVersion', 'releaseVersion', 'webVersion', 'gitTag']) {
     if (manifest[field] !== target[field]) fail('下载的发布清单与检查结果不一致')
   }
   const commit = run('git', ['rev-parse', 'HEAD'], { cwd: staging }).trim()
@@ -253,9 +253,6 @@ async function runUpdate(jobPath, job) {
   const { plan, target, id } = job
   if (!target) fail('升级任务缺少目标发布清单')
   const { finalRoot, commit } = stageRelease(job, jobPath)
-  const pluginSource = join(finalRoot, 'hermes-plugins', 'yaoyao')
-  const pluginManifest = readJSON(join(pluginSource, 'dashboard', 'manifest.json'))
-  if (pluginManifest.version !== target.pluginVersion) fail('构建产物中的插件版本与发布清单不一致')
 
   const previousCurrentTarget = currentTarget(plan.releaseRoot)
   let transitioned = false

+ 21 - 270
docs/agent-install.md

@@ -1,284 +1,35 @@
-# 夭夭 Agent 安装手册
+# 部署夭夭 Web
 
-适用于需要部署或升级夭夭 Web 与 Hermes Dashboard 插件的自动化 Agent。
+## 前提
 
-## 发布版本
+- Node.js 24。
+- 可访问的 Hermes Dashboard/Gateway(通常为 9119),支持会话创建、恢复、提示词提交、附件及审批 RPC。
+- 不需要 Yaoyao 插件,不会修改外部 Hermes 的插件目录或重启外部 Hermes。
 
-| 项目 | 版本 | 校验位置 |
-| --- | --- | --- |
-| Git 发布标签 | `v0.2.31` | `release.json` 的 `gitTag` 与 `git describe --tags --exact-match HEAD` |
-| 夭夭 Web | `0.2.31` | `release.json` 与 `package.json` 的 `version` |
-| Hermes Dashboard 插件 | `1.7.3` | `hermes-plugins/yaoyao/dashboard/manifest.json` 的 `version` |
+## 源码安装
 
-以下步骤以仓库根目录为工作目录。不要使用浮动分支替代发布标签。
+在仓库执行 `npm ci`、`npm run build`,然后执行 `npm start`。Web 默认监听 `127.0.0.1:8800`。
 
-本版客户端只支持 HTTP+SSE,旧 WebSocket、票据和租约入口返回 410。升级服务端时必须同步更新 iOS 客户端;Web 静态资源随本版发布。上游 9119 与 Python 插件未迁移,插件版本仍为 1.7.3。
+上游地址由 `HERMES_YAOYAO_UPSTREAM` 配置。远端凭据在 Web 系统设置中保存。需要环境配置时使用 `HERMES_YAOYAO_UPSTREAM_USERNAME` 和 `HERMES_YAOYAO_UPSTREAM_PASSWORD`,不要把凭据嵌入 URL。
 
-v0.2.28 增加服务端热点读取缓存与 30 秒上游登录状态检查复用;实际请求仍携带凭据,客户端权限仍逐次校验。已有 HTTP+SSE 版 iOS 无需因本次缓存优化重新打包。缓存边界见 [读取缓存说明](read-cache.md)。
+首次登录使用 `admin/admin`,随后必须修改密码。iOS 使用 Web 的账号或手机登录二维码。
 
-## 网络默认值与局域网策略
+## 局域网与容器
 
-通过 `service install` 安装的受管服务默认只将 8800 开放到可信局域网:
+局域网部署可设置 `HERMES_YAOYAO_HOST=0.0.0.0` 和 `HERMES_YAOYAO_ALLOW_INSECURE_LAN=1`,并在 `HERMES_YAOYAO_ALLOWED_HOSTS` 中列入访问地址。公网部署配置 TLS。
 
-| 端口 | 服务 | 默认监听地址 | 开启局域网的责任边界 |
-| --- | --- | --- | --- |
-| `9119` | Hermes Dashboard | `127.0.0.1` | 缺失时在回环启动,不生成密码,不改动已有服务 |
-| `8800` | 夭夭 Web | `0.0.0.0` | LaunchAgent 显式写入可信局域网 HTTP 开关 |
+容器保持 `HERMES_YAOYAO_SUPERVISE_DASHBOARD=0`,使用外部 Hermes 上游。数据目录 `/var/lib/hermes-yaoyao` 必须持久化;无需挂载 Hermes 文件系统或 Docker socket。
 
-新启动的受管 9119 不跟随 8800 暴露到局域网。已有 9119 的绑定和认证保持原状;手动 `npm start` 和 Docker 部署仍使用各自的绑定配置。
+## 验收
 
-受管 `service install` 会覆盖 8800 遗留的 loopback 环境并保持 8800 局域网监听。若 8800 也必须仅本机访问,请使用手动 `npm start` 或 Docker 的回环绑定,不要使用受管 LaunchAgent。
+- `/healthz` 检查 Web 自身;`/readyz` 检查 Hermes 上游。
+- 登录后 `/api/app/capabilities` 声明新聊天功能。
+- 创建角色、发送消息、上传并下载附件、创建固定成员群聊。
+- 用同一账号在 iOS 和 Web 查看相同历史;另一账号看不到这些聊天。
+- 全过程不应访问 `/api/plugins/yaoyao/`、插件安装或插件升级接口。
 
-默认局域网模式会显式设置 `HERMES_YAOYAO_ALLOW_INSECURE_LAN=1`,只适合受信网络。跨不受信网络部署时必须设置 `HERMES_YAOYAO_TLS_CERT` 和 `HERMES_YAOYAO_TLS_KEY`,并使用防火墙或反向代理限制访问;`hermes dashboard --insecure` 不会关闭认证,不能将它当成局域网开关。
+## 数据和发布
 
-## 受管 9119 的默认认证与持续监督
+备份整个 `HERMES_YAOYAO_HOME`,包含 SQLite、上传与归档文件、用户凭据和密钥。正常的数据库持久化不依赖旧插件存储维护工具。
 
-夭夭 Web LaunchAgent 默认启用 `HERMES_YAOYAO_SUPERVISE_DASHBOARD=1`。仅当上游为 `http://127.0.0.1:9119` 时,每 5 秒检查该端口;未监听时执行 `hermes dashboard --host 127.0.0.1 --no-open`。不再自动生成 9119 服务账号、密码或签名密钥;不会因安装检查而停止或重绑定已有 Dashboard。
-
-直连回环且 Hermes 声明 `auth_required=false` 时,8800 自动取得并验证 Hermes 原生会话令牌;REST 和 WebSocket 都使用该令牌,不是跳过鉴权。令牌只驻留服务端内存,重启失效后自动重新取得。详见 [本机授权边界](loopback-authorization.md)。
-
-8800 自己的默认管理员仍为 `admin/admin`,首次登录必须修改。已有或外部 9119 若仍声明 `auth_required=true`,必须在 8800“系统管理”中配置服务账号;已有账号和密码不会被删除,`--insecure` 也不会绕过该认证。
-
-以下仅用于需要账号鉴权的部署,不是本机安装的必做步骤。可用下列命令以 scrypt 哈希方式配置账号;不要将密码放入命令历史、Git 或日志。
-
-```bash
-HERMES_AGENT_HOME="${HERMES_AGENT_HOME:-$HOME/.hermes/hermes-agent}"
-read -r -p 'Dashboard username: ' DASHBOARD_USERNAME
-read -r -s -p 'Dashboard password: ' DASHBOARD_PASSWORD
-printf '\n'
-
-DASHBOARD_PASSWORD_HASH="$(
-  DASHBOARD_PASSWORD="$DASHBOARD_PASSWORD" \
-    "$HERMES_AGENT_HOME/venv/bin/python" -c \
-    'import os; from plugins.dashboard_auth.basic import hash_password; print(hash_password(os.environ["DASHBOARD_PASSWORD"]))'
-)"
-DASHBOARD_SECRET="$("$HERMES_AGENT_HOME/venv/bin/python" -c 'import secrets; print(secrets.token_urlsafe(32))')"
-
-hermes config set dashboard.basic_auth.username "$DASHBOARD_USERNAME"
-hermes config set dashboard.basic_auth.password_hash "$DASHBOARD_PASSWORD_HASH"
-hermes config set dashboard.basic_auth.secret "$DASHBOARD_SECRET"
-
-unset DASHBOARD_PASSWORD DASHBOARD_PASSWORD_HASH DASHBOARD_SECRET
-```
-
-`password_hash` 优先于明文 `password`。`secret` 使认证会话可跨 Dashboard 重启继续有效。若 Dashboard 由 LaunchAgent 或其他监督器运行,配置变更后必须通过**同一个监督器**重启它,确保新认证提供方被加载。
-
-受管服务负责启动和重启 9119,不能再同时安装独立的 Dashboard LaunchAgent 或手动长期运行 `hermes dashboard`。认证加载可在本机无密码回显地检查:
-
-```bash
-hermes config get dashboard.basic_auth.username
-curl --fail --silent --show-error http://127.0.0.1:9119/api/auth/providers
-```
-
-第二条命令应能返回包含用户名密码登录提供方的 JSON。不要在自动化日志、命令行、环境变量转储或 Git 配置中记录替换后的明文密码。
-
-## 1. 获取并校验指定发布版本
-
-```bash
-RELEASE_VERSION=v0.2.31
-git fetch --tags
-git checkout "$RELEASE_VERSION"
-
-test "$(git describe --tags --exact-match HEAD)" = "$RELEASE_VERSION"
-test "$(node -p \"require('./package.json').version\")" = "0.2.31"
-test "$(node -e \"console.log(require('./hermes-plugins/yaoyao/dashboard/manifest.json').version)\")" = "1.7.3"
-npm run release:verify
-```
-
-这会进入 detached HEAD 状态,属于部署发布版本的预期行为。若 Agent 负责修改代码,应另行创建工作分支,不要在此发布检出上修改。
-
-## 2. 安装或升级 Hermes Dashboard 插件
-
-前提:目标机器已安装 Hermes,且 `hermes dashboard --status` 可执行。插件必须完整放在 `<Hermes 数据目录>/plugins/yaoyao/dashboard/`,不能只复制 Python 文件或前端 `dist/` 目录。
-
-```bash
-HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
-PLUGIN_DIR="$HERMES_HOME/plugins/yaoyao/dashboard"
-BACKUP_DIR="${PLUGIN_DIR}.backup-$(date +%Y%m%d%H%M%S)"
-
-if [ -d "$PLUGIN_DIR" ]; then
-  cp -a "$PLUGIN_DIR" "$BACKUP_DIR"
-fi
-
-mkdir -p "$PLUGIN_DIR"
-rsync -a --delete \
-  --exclude '__pycache__/' \
-  --exclude '*.py[cod]' \
-  --exclude '.pytest_cache/' \
-  hermes-plugins/yaoyao/dashboard/ "$PLUGIN_DIR/"
-
-test -f "$PLUGIN_DIR/manifest.json"
-test -f "$PLUGIN_DIR/plugin_api.py"
-test -f "$PLUGIN_DIR/group_plugin_api.py"
-test -f "$PLUGIN_DIR/dist/index.js"
-test "$(node -e \"console.log(require(process.argv[1]).version)\" "$PLUGIN_DIR/manifest.json")" = "1.7.3"
-```
-
-`rsync --delete` 的范围严格限于 `$PLUGIN_DIR`,不会删除其他 Hermes 插件或用户数据。若目标目录已有额外的本机定制文件,应先将其移出目录或改用不带 `--delete` 的同步命令。
-
-不要提交、复制或恢复 `data/`、`__pycache__/`、`.pytest_cache/` 等运行时内容。归档数据库和本机状态不属于插件发布物。
-
-当前兼容版本首次启动时,会把每个 Profile 的旧目录
-`<profile-home>/plugins/yaoyao/data` 原子迁移到
-`<profile-home>/plugin-data/yaoyao`。后者独立于插件安装树,后续通过 Hermes
-插件接口替换 `plugins/yaoyao` 时不会丢失运行数据。若两个目录同时包含数据,
-插件不会自动合并,运行时仍只读取 `plugin-data/yaoyao`;应人工核对后移出旧目录,
-最终只保留这一权威数据目录。
-
-完成这次兼容版本启动后,后续可在已登录的 8800 会话中调用:
-
-```http
-POST /api/app/plugins/yaoyao/install
-Content-Type: application/json
-
-{"force":true}
-```
-
-默认安装源是
-`https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao`,可由服务端
-环境变量 `HERMES_YAOYAO_PLUGIN_SOURCE` 覆盖。接口不接受请求体覆盖仓库地址,
-并会在调用 9119 的通用安装接口前检查持久数据迁移状态。
-
-## 3. 由 8800 服务担任唯一 Dashboard 监督者
-
-插件文件只有在 Dashboard 重载后才会生效。安装本项目的受管服务后,8800 服务是 Dashboard 的唯一持续监督者;不要保留其他 Dashboard LaunchAgent 或手动常驻进程。
-
-| Dashboard 情况 | 正确做法 | 禁止做法 |
-| --- | --- | --- |
-| 需要让新插件生效 | 执行 `hermes dashboard --stop`,等待 8800 监督器在 5 秒内自动启动 | 另起常驻 `hermes dashboard` 进程 |
-| 9119 未监听 | 等待 8800 监督器自动启动;检查其日志 | 手动重复启动多个 Dashboard |
-
-## 4. 显式启用夭夭 Dashboard 插件
-
-夭夭位于用户插件目录,Dashboard 会先发现其 `manifest.json`,但不会自动执行用户提供的 JavaScript 或 Python 代码。只有插件名同时满足 `plugins.enabled` 包含 `yaoyao` 且未出现在 `plugins.disabled` 中时,Dashboard 才会展示夭夭标签、提供静态资源并挂载 `/api/plugins/yaoyao/`。
-
-先读取当前列表:
-
-```bash
-hermes config get plugins.enabled
-```
-
-当列表为空时,设置唯一的启用项:
-
-```bash
-hermes config set plugins.enabled '["yaoyao"]'
-```
-
-如果列表已有其他插件名,必须保留它们并在同一 JSON 列表中加入 `yaoyao`;不要以该示例覆盖已有启用项。随后执行:
-
-```bash
-hermes dashboard --stop
-```
-
-8800 监督器会在下一轮检查中自动重新启动 9119。不要补充 `hermes dashboard --no-open`,否则可能与监督器竞争端口。
-
-验证时使用 Dashboard 专用清单,而不是通用 `hermes plugins list`:
-
-```bash
-curl --noproxy '*' --fail --silent http://127.0.0.1:9119/api/dashboard/plugins
-tail -n 100 ~/.hermes/logs/gui.log
-```
-
-验收条件:清单包含 `"name":"yaoyao"`,日志包含 `Mounted plugin API routes: /api/plugins/yaoyao/`。匿名请求 `/api/plugins/yaoyao/...` 返回 `401` 是认证生效的信号,不表示插件加载失败。
-
-## 5. 验证插件和 Dashboard
-
-```bash
-hermes dashboard --status
-lsof -nP -iTCP:9119 -sTCP:LISTEN
-```
-
-验收条件:Dashboard 状态正常,且只有一个 `9119` TCP 监听器。插件路由位于 `/api/plugins/yaoyao/`,该 API 需要 Hermes 登录会话或原生本机令牌;不要为了探测路由而关闭认证。新启动的受管 Dashboard 默认只监听 `127.0.0.1`。
-
-## 6. 可选:部署夭夭 Web
-
-夭夭 Web 默认使用端口 `8800` 并连接 Dashboard `9119`。通过 LaunchAgent 安装后,8800 默认监听 `0.0.0.0`,新启动的 9119 只监听 `127.0.0.1`;8800 停止或卸载时不会主动停止正在运行的 Dashboard。
-
-```bash
-npm ci
-npm run build
-node bin/hermes-yaoyao.mjs service install
-node bin/hermes-yaoyao.mjs service status
-```
-
-若需要显式指定 Dashboard 上游,只在安装服务前设置 `HERMES_YAOYAO_UPSTREAM`。默认值为 `http://127.0.0.1:9119`,因为 8800 仍通过本机回环访问受监督的 9119。受管升级会迁移旧版 `127.0.0.1/0` 环境并继续使用局域网监听。
-
-受管服务的配置被写入 `~/Library/LaunchAgents/com.samien.hermes-yaoyao.plist`。任何监听、TLS、上游或监督配置变更后,都要再次执行 `service install`,随后确认状态、两个监听器和日志:
-
-```bash
-node bin/hermes-yaoyao.mjs service status
-lsof -nP -iTCP:8800 -sTCP:LISTEN
-lsof -nP -iTCP:9119 -sTCP:LISTEN
-tail -n 100 ~/Library/Logs/hermes-yaoyao.log
-```
-
-若 `launchctl bootstrap` 报 `Bootstrap failed: 5: Input/output error`,先验证 plist,再使用已验证的兼容回退加载同一份文件:
-
-```bash
-plutil -lint ~/Library/LaunchAgents/com.samien.hermes-yaoyao.plist
-launchctl load -w ~/Library/LaunchAgents/com.samien.hermes-yaoyao.plist
-```
-
-### 推送状态 v2 与 Android FCM
-
-Web `0.2.16` 及后续版本会在首次写入时把 `$HERMES_YAOYAO_HOME/push/state.json` 从 schema 1
-迁移为 schema 2;已有 APNs 安装、待发送队列、团队订阅、事件去重、游标和聊天恢复
-任务都会保留。旧版 Web 不能直接读取 schema 2,因此升级前必须备份整个 `push/`
-目录;若回滚 Web,也要同步恢复这份升级前备份,不能只切换 `current` 符号链接。
-
-Android FCM 的服务账号 JSON 必须位于发布目录和 Git 仓库之外,权限建议为 `0600`。
-可在 8800“系统管理 → Android 消息推送”填写其绝对路径、Firebase Project ID 和
-固定包名 `cn.samien.yaoyao.hermes`。使用环境变量管理时配置以下三项并重新执行
-`service install`;任一项出现时三项都必须有效,Web 界面只读:
-
-```bash
-HERMES_YAOYAO_FCM_SERVICE_ACCOUNT_FILE=/absolute/path/to/firebase-service-account.json \
-HERMES_YAOYAO_FCM_PROJECT_ID=your-firebase-project-id \
-HERMES_YAOYAO_FCM_PACKAGE_NAME=cn.samien.yaoyao.hermes \
-node bin/hermes-yaoyao.mjs service install
-```
-
-服务账号文件、OAuth Token、FID 和 Android 的 `google-services.json` 都不得进入
-Git、发布目录、命令输出或日志。配置后检查系统管理中的 APNs/FCM 独立状态;一方
-未配置或失败不能使另一方停止。
-
-## 7. 通过受管服务独立升级 Web
-
-首次按第 6 步安装 Web `0.2.31` 后,可在左下角 Agent 菜单打开“系统更新”。
-旧版首次升级仍受旧更新器的上游检查限制,需要在 9119 可用时升级一次,或按第 1、6 步手动部署新版。独立升级能力在运行 `v0.2.30` 后生效。
-检查更新只读取固定的 `HERMES_YAOYAO_RELEASE_SOURCE`,并锁定最新 `vX.Y.Z`
-标签解析到的 Git 提交。更新状态、检查、执行、任务查询和回滚仅要求 8800 本地管理员登录;
-写请求仍验证 Origin、CSRF 和本机访问策略,不要求 9119 可用或通过上游认证。
-不会检查插件持久目录或强制先升级插件。9119 离线时,登录初始化最多等待 3 秒后仍可进入更新页。
-
-升级任务由 8800 外部的独立 updater 执行。运行文件会安装到
-`~/.local/share/hermes-yaoyao/releases/`,LaunchAgent 改为指向稳定的
-`current` 符号链接。切换期间 8800 会短暂不可用,不因 Web 升级重启 9119;任务状态保存在
-`~/.hermes-yaoyao/updates/`,新服务启动后可继续读取。
-
-默认只能从目标 Mac 本机触发“升级”和“回滚”;仅当用户明确允许远程系统管理
-时,才在重新安装 LaunchAgent 前设置 `HERMES_YAOYAO_ALLOW_REMOTE_UPDATE=1`。
-Docker 和其他非 macOS 部署必须替换镜像,不能调用服务内升级接口。
-
-Web 升级成功必须通过自身健康检查,并确认发布目录:
-
-```bash
-curl --noproxy '*' --fail --silent http://127.0.0.1:8800/healthz
-readlink ~/.local/share/hermes-yaoyao/current
-```
-
-下列是独立的上游诊断。9119 离线时可失败,不应因此判定 Web 升级失败或回滚:
-
-```bash
-curl --noproxy '*' --fail --silent http://127.0.0.1:8800/readyz
-curl --noproxy '*' --fail --silent http://127.0.0.1:9119/api/dashboard/plugins
-```
-
-## 8. 失败处理
-
-1. 记录失败的命令、退出码、Dashboard 状态和 `9119` 监听信息。
-2. 若插件重载失败,使用第 2 步生成的 `$BACKUP_DIR` 恢复到 `$PLUGIN_DIR`,执行 `hermes dashboard --stop`,再由 8800 监督器重启 Dashboard。
-3. 若插件文件存在但未显示,先检查 `plugins.enabled` 是否包含 `yaoyao`,再检查 `/api/dashboard/plugins` 和 `gui.log`;不要通过重复复制目录或禁用认证来“尝试修复”。
-4. 不要通过多次执行 `hermes dashboard --no-open`、重复安装 LaunchAgent 或停止无关 Gateway 来“尝试修复”。这些操作会掩盖真正错误,或产生重复监听进程。
-
-版本不匹配、没有可用备份或无法确认 Dashboard 所有者时,停止自动化流程并报告,而不是猜测或覆盖现有安装。
+本次升级不迁移旧数据。旧插件及数据文件保留在原处,不自动卸载或删除。首次切换整体部署新 Web 和 iOS;此后只升级 Web 自身版本。

+ 19 - 0
docs/releases/v0.3.0.md

@@ -0,0 +1,19 @@
+# v0.3.0 — Web 原生角色与固定成员聊天
+
+团队、角色和聊天记录现在由 Web 服务直接保存和运行。基于已有 Hermes Profile 创建角色并设置提示词,角色单聊与群聊显示在同一列表;群成员创建后固定,不再提供独立话题列表。
+
+文件归档、语音配置、上下文快照、节点管理与团队推送迁入 Web。移除 Yaoyao 插件及其安装、版本检查和升级流程。原生 Hermes 对话保留独立入口。
+
+## 配套客户端
+
+请同时更新至 iOS 1.3(164)。iOS 统一连接 Web 地址,角色会话按登录账号隔离;Hermes 暂时不可用时仍可登录 Web 查看已有聊天。
+
+## 升级方式
+
+这是不兼容旧接口的版本。首次切换请整体替换 Web 部署,不通过旧版插件升级流程更新。新体系从空数据库开始,旧团队、话题和插件配置不自动导入,旧文件原地保留。
+
+Web 上游仍为标准 Hermes 9119 服务。无需安装 Yaoyao 插件;Kanban 仍是独立可选功能。
+
+## 验证
+
+发布前执行 Web 全量单元测试、类型检查、生产构建和新聊天浏览器端到端测试。iOS 使用当前提交执行设备归档、开发签名导出和包完整性检查。该 IPA 供签名配置中已注册的设备使用。

+ 33 - 0
docs/workspace-acceptance.md

@@ -0,0 +1,33 @@
+# Web 聊天迁移验收
+
+验收日期:2026-09-03。涉及 `hermes-yaoyao` 与 `hermes-mobile`,旧插件数据未导入或删除。
+
+## 自动验证
+
+- `npm run typecheck`:通过。
+- `npm test`:84 个测试文件、451 项测试通过。
+- `npm run test:e2e:workspace`:生产构建通过,完整浏览器流程通过。
+- iOS 模拟器签名构建通过;`WorkspaceChatTests` 的 5 项新协议测试通过。
+- 两个仓库的 `git diff --check` 均通过。
+
+服务端回归覆盖用户隔离、固定成员、规则更新、执行中改名、管理员调度、轮数限制、审批、澄清、重复提交、断线不确定状态、按历史恢复且不重发、失效节点的可见失败、附件归档、安全预览、语音密钥和上下文快照。
+
+浏览器用例覆盖创建两个角色、创建群聊、三项混合列表、不可编辑成员、角色单聊隔离、群聊发送、第二页面同步、归档恢复、文件来源返回新聊天,以及全过程不访问 Yaoyao 插件接口。
+
+iOS 新协议用例覆盖应用写入的 Origin/CSRF、跨账号令牌刷新、拒绝直连 9119、新聊天通知路由、归档文件呈现、语音时间戳,以及上游无 Profile 时仍可登录 Web。
+
+## 界面联调
+
+使用独立 Web 数据目录和未提供插件接口的标准 Gateway 测试节点;未使用用户当前服务的数据。
+
+已在浏览器和独立的 `Yaoyao Workspace QA` 模拟器中核对:同一账号显示相同的两个角色及一个群聊;iOS 发出的群聊消息、回复及历史在 Web 中可见。浏览器确认已建群的成员选择框禁用,服务端也拒绝成员变更。
+
+这些结果验证应用协议与界面联动,不代表真实模型、真实远端节点或 APNs/FCM 推送供应商的生产验收。此轮没有发布版本、更新现有 Web 服务或安装到真机。
+
+## 重现
+
+Web:运行上述三个 npm 命令。浏览器用例会自动启动隔离测试服务。
+
+iOS:使用 `YaoYaoAI` scheme 和可用模拟器,运行 `-only-testing:YaoYaoAITests/WorkspaceChatTests`。需要允许模拟器签名以验证钥匙串登录;禁用签名的安装包不能作为登录验收依据。
+
+实现和接口说明见 [聊天契约](workspace-chat.md),部署步骤见 [部署说明](agent-install.md)。

+ 38 - 0
docs/workspace-chat.md

@@ -0,0 +1,38 @@
+# Web 聊天契约
+
+## 身份和数据
+
+`WorkspaceAgent` 引用不可变的 `(nodeId, profile)`,保存名称、头像及角色规则。`WorkspaceConversation` 为 `direct` 或 `group`;每个角色只有一个 direct,group 的成员集合不可变,协议不包含 topicId。角色名在用户内唯一,以便精确 @。
+
+应用数据保存在 Web 数据目录的 `workspace.sqlite3`。每一条实体、命令和事件包含服务端用户归属。隐藏上游会话只由 WorkspaceRuntime 驱动,原生历史及 RPC 不允许直接访问。基础 Hermes Profile 的记忆和工具权限没有被复制为新的隔离运行环境。
+
+## API
+
+- `GET /api/app/capabilities`:协议 1 和能力。
+- `GET/POST /api/app/agents`、`PATCH /api/app/agents/:id`:角色;`GET /api/app/agents/sources`:基础来源。
+- `GET/POST /api/app/conversations`、`GET/PATCH /api/app/conversations/:id`:混合列表和聊天详情。创建接口仅创建群聊;创建角色自动创建单聊。
+- `GET/POST /api/app/conversations/:id/messages`:历史和发送。发送需 UUID `requestId`、`content`、`mentionIds`、`fileIds`。重复编号与内容返回同一运行,内容冲突返回 409。
+- `PUT /api/app/conversations/:id/read`:单调递增的已读序号。
+- `POST /api/app/runs/:id/stop`、`/reconcile`:停止和核对不确定状态。
+- `POST /api/app/interactions/:id/respond`:审批或澄清。
+- `GET /api/app/events?after=N`:按序号读取持久化事件,最多 250 条,重连从最后序号继续。
+- `POST /api/app/uploads`:multipart 上传;`GET /api/app/files` 与文件下载、预览接口:Web 归档库。
+- `/api/app/nodes`:用户自己的远端节点。密码加密保存,只返回公开字段。
+- `/api/app/voice/*`、`/api/app/tts/settings/*`、`/api/app/stt/settings/*`:语音设置及运行配置。
+- `/api/app/session-context/:id?profile=...`:原生会话上下文快照,按观测时间拒绝倒退。
+
+网页与 iOS 均使用相同本地账号认证。应用写入接口校验 Origin 和 CSRF;客户端先从 bootstrap 获取令牌。
+
+## 执行
+
+用户消息先持久化,再创建运行。每聊天一次只能有一个运行;群内按已记录的队列逐个执行。每个群成员有独立上游会话,聊天之间不复用会话。
+
+明确 @ 优先;否则管理员模式由管理员开始,自由模式按自动回复成员开始,无人启用则由管理员响应。管理员委派后由成员执行并返回管理员;自由模式按成员 @ 接力。默认最多 3 轮,范围 1~100,达到上限即结束自动接力。引用和代码中的 @ 不触发协作。
+
+每次成员执行前读取最新角色及群规则,附加到本次输入,不修改基础 Profile。网页和手机只展示用户原始消息,不展示执行提示词。
+
+断开客户端不取消运行。提交丢失确认、连接中断或服务重启时,不自动重发可能已执行的请求。核对上游会话及带运行标识的历史后继续;无法核对时显示不确定状态并要求显式停止或核对。
+
+## 退出旧插件
+
+旧 Yaoyao API 返回 410;没有安装、reconcile、版本要求或升级流程。新数据不导入旧插件目录。旧插件数据原地保留。原生对话和可选 Kanban 继续使用各自的独立接口。

+ 0 - 62
hermes-plugins/yaoyao/dashboard/data_paths.py

@@ -1,62 +0,0 @@
-"""Durable storage paths and one-time migration for the YaoYao plugin.
-
-Plugin installers replace ``<profile_home>/plugins/yaoyao`` atomically. Runtime
-state therefore lives under ``<profile_home>/plugin-data/yaoyao`` so installs,
-updates, and removals cannot delete user data.
-"""
-
-from __future__ import annotations
-
-import os
-from dataclasses import dataclass
-from pathlib import Path
-
-
-DURABLE_DATA_SUBPATH = Path("plugin-data") / "yaoyao"
-LEGACY_DATA_SUBPATH = Path("plugins") / "yaoyao" / "data"
-
-
-@dataclass(frozen=True)
-class DataPathStatus:
-    data_root: Path
-    ready: bool
-    migrated: bool
-    legacy_present: bool
-    conflict: bool
-
-
-def _has_entries(path: Path) -> bool:
-    try:
-        return next(path.iterdir(), None) is not None
-    except FileNotFoundError:
-        return False
-
-
-def ensure_durable_data_root(profile_home: Path) -> DataPathStatus:
-    """Move the legacy data directory once, without merging ambiguous trees.
-
-    The durable tree is always the runtime authority once it exists. When both
-    locations contain data, keep both untouched and report a conflict so the
-    install coordinator can refuse a full plugin replace without making the
-    application silently fall back to stale legacy state.
-    """
-
-    home = Path(profile_home).expanduser().resolve()
-    durable = home / DURABLE_DATA_SUBPATH
-    legacy = home / LEGACY_DATA_SUBPATH
-
-    legacy_present = legacy.exists()
-    if not legacy_present:
-        return DataPathStatus(durable, True, False, False, False)
-
-    if legacy.is_symlink() or durable.is_symlink():
-        return DataPathStatus(durable, False, False, True, True)
-
-    if durable.exists():
-        if _has_entries(legacy):
-            return DataPathStatus(durable, False, False, True, True)
-        return DataPathStatus(durable, True, False, True, False)
-
-    durable.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
-    os.replace(legacy, durable)
-    return DataPathStatus(durable, True, True, False, False)

+ 0 - 1075
hermes-plugins/yaoyao/dashboard/dist/index.js

@@ -1,1075 +0,0 @@
-/**
- * Yaoyao - dashboard plugin frontend.
- *
- * Plain IIFE, no build step. Uses window.__HERMES_PLUGIN_SDK__ for React +
- * shadcn-ui primitives + fetchJSON / authedFetch. Backend routes live under
- * /api/plugins/yaoyao/ (auto-mounted by the dashboard plugin loader).
- */
-(function () {
-  "use strict";
-
-  const SDK = window.__HERMES_PLUGIN_SDK__;
-  if (!SDK) return;
-  const { React } = SDK;
-  const h = React.createElement;
-  const { useState, useEffect, useCallback, useRef, useMemo } = SDK.hooks;
-  const {
-    Card,
-    CardContent,
-    Badge,
-    Button,
-    Input,
-    Label,
-    Select,
-    SelectOption,
-  } = SDK.components;
-  const { cn, timeAgo } = SDK.utils;
-  const fetchJSON = SDK.fetchJSON;
-  const authedFetch = SDK.authedFetch;
-
-  const API = "/api/plugins/yaoyao";
-
-  // ---------------------------------------------------------------------
-  // Helpers
-  // ---------------------------------------------------------------------
-
-  function inferKind(name, mimeType) {
-    const ext = (name.split(".").pop() || "").toLowerCase();
-    if ((mimeType || "").startsWith("image/") ||
-        ["png","jpg","jpeg","gif","webp","bmp","svg","tiff","tif"].includes(ext))
-      return "image";
-    if ((mimeType || "").startsWith("video/") ||
-        ["mp4","mov","avi","mkv","webm","m4v","wmv","flv"].includes(ext))
-      return "video";
-    if ((mimeType || "").startsWith("text/") ||
-        ["txt","md","json","yaml","yml","csv","log","py","js","ts","html","xml","rst"].includes(ext))
-      return "text";
-    return "file";
-  }
-
-  function formatBytes(n) {
-    if (!n || n <= 0) return "0 B";
-    const units = ["B", "KB", "MB", "GB"];
-    let i = 0, v = n;
-    while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
-    return v >= 100 ? v.toFixed(0) + " " + units[i]
-         : v >= 10  ? v.toFixed(1) + " " + units[i]
-                    : v.toFixed(2) + " " + units[i];
-  }
-
-  function senderLabel(s) {
-    return s === "user" ? "用户" : s === "agent" ? "Agent" : s;
-  }
-
-  function kindIcon(kind) {
-    switch (kind) {
-      case "image": return "🖼";
-      case "video": return "🎬";
-      case "text": return "📄";
-      default: return "📦";
-    }
-  }
-
-  // ---------------------------------------------------------------------
-  // Thumbnail image: fetch as blob via authedFetch (img tags can't set
-  // Authorization headers), then create an object URL.
-  // ---------------------------------------------------------------------
-
-  function Thumbnail({ item, profile }) {
-    const [url, setUrl] = useState(null);
-    const [err, setErr] = useState(false);
-    const kind = inferKind(item.name, item.mimeType);
-
-    useEffect(() => {
-      if (kind !== "image") return;
-      let revoke = null;
-      let cancelled = false;
-      const dlUrl = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-      authedFetch(dlUrl)
-        .then((res) => res.blob())
-        .then((blob) => {
-          if (cancelled) return;
-          const u = URL.createObjectURL(blob);
-          revoke = u;
-          setUrl(u);
-        })
-        .catch(() => { if (!cancelled) setErr(true); });
-      return () => {
-        cancelled = true;
-        if (revoke) URL.revokeObjectURL(revoke);
-      };
-    }, [item.id, profile]);
-
-    if (kind !== "image") {
-      return h("div", {
-        className: "yaoyao-thumb yaoyao-thumb-icon",
-      }, kindIcon(kind));
-    }
-    if (err) return h("div", { className: "yaoyao-thumb yaoyao-thumb-icon" }, "🖼");
-    if (!url) return h("div", { className: "yaoyao-thumb yaoyao-thumb-loading" }, "…");
-    return h("img", {
-      src: url,
-      alt: item.name,
-      className: "yaoyao-thumb yaoyao-thumb-img",
-      loading: "lazy",
-    });
-  }
-
-  // ---------------------------------------------------------------------
-  // File card
-  // ---------------------------------------------------------------------
-
-  function FileCard({ item, onDownload, profile }) {
-    const kind = inferKind(item.name, item.mimeType);
-    return h(Card, { className: "yaoyao-card" },
-      h(CardContent, { className: "yaoyao-card-content" },
-        h("div", { className: "yaoyao-card-preview" },
-          h(Thumbnail, { item: item, profile: profile })
-        ),
-        h("div", { className: "yaoyao-card-info" },
-          h("div", { className: "yaoyao-card-name", title: item.name }, item.name),
-          h("div", { className: "yaoyao-card-meta" },
-            h(Badge, { variant: "secondary" }, senderLabel(item.origins && item.origins[0] ? item.origins[0].authorKind : "agent")),
-            h("span", { className: "yaoyao-card-size" }, formatBytes(item.size)),
-            item.messageTimestamp
-              ? h("span", { className: "yaoyao-card-time" }, timeAgo(item.messageTimestamp * 1000))
-              : null
-          ),
-          h("div", { className: "yaoyao-card-actions" },
-            h(Button, {
-              variant: "outline",
-              size: "sm",
-              onClick: () => onDownload(item),
-            }, "下载")
-          )
-        )
-      )
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Main page
-  // ---------------------------------------------------------------------
-
-  function YaoyaoFilesPage() {
-    const [items, setItems] = useState([]);
-    const [loading, setLoading] = useState(true);
-    const [loadingMore, setLoadingMore] = useState(false);
-    const [error, setError] = useState(null);
-    const [cursor, setCursor] = useState(null);
-    const [hasMore, setHasMore] = useState(false);
-    const [stats, setStats] = useState(null);
-    const [profiles, setProfiles] = useState([]);
-    // Initial profile from the URL (?profile=gril) so deep links / shared
-    // links land on the right agent's library; fall back to "default".
-    const [profile, setProfile] = useState(() => {
-      try {
-        const u = new URL(window.location.href);
-        const p = u.searchParams.get("profile");
-        return p || "default";
-      } catch (e) {
-        return "default";
-      }
-    });
-    const [filter, setFilter] = useState({ sender: "", kind: "" });
-    const [search, setSearch] = useState("");
-    const [searchInput, setSearchInput] = useState("");
-    const sentinelRef = useRef(null);
-
-    // Keep the URL ?profile= in sync with the dropdown selection so the
-    // address bar reflects what's shown (and is shareable / refreshable).
-    useEffect(() => {
-      try {
-        const u = new URL(window.location.href);
-        if (profile && profile !== "default") {
-          u.searchParams.set("profile", profile);
-        } else {
-          u.searchParams.delete("profile");
-        }
-        window.history.replaceState(null, "", u.toString());
-      } catch (e) { /* ignore */ }
-    }, [profile]);
-
-    // Also react to back/forward navigation so the dropdown follows the URL.
-    useEffect(() => {
-      const onPop = () => {
-        try {
-          const u = new URL(window.location.href);
-          const p = u.searchParams.get("profile") || "default";
-          setProfile(p);
-        } catch (e) { /* ignore */ }
-      };
-      window.addEventListener("popstate", onPop);
-      return () => window.removeEventListener("popstate", onPop);
-    }, []);
-
-    // Profiles dropdown: which agents have libraries. default always present.
-    useEffect(() => {
-      fetchJSON(`${API}/profiles`)
-        .then((res) => {
-          const list = (res.profiles || []);
-          setProfiles(list);
-          // If the current selection vanished (profile deleted), fall back.
-          if (list.length && !list.some((p) => p.name === profile)) {
-            setProfile("default");
-          }
-        })
-        .catch(() => {});
-    }, []); // eslint-disable-line
-
-    // Fetch first page whenever filter / search / profile changes.
-    const loadFirst = useCallback(async () => {
-      setLoading(true);
-      setError(null);
-      try {
-        const params = { limit: 50 };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems(res.items || []);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }, [filter, search, profile]);
-
-    useEffect(() => { loadFirst(); }, [loadFirst]);
-
-    // Stats (re-fetch when profile changes)
-    useEffect(() => {
-      const params = {};
-      if (profile) params.profile = profile;
-      const qs = new URLSearchParams(params).toString();
-      fetchJSON(`${API}/stats?${qs}`).then(setStats).catch(() => {});
-    }, [profile]);
-
-    // Load more
-    const loadMore = useCallback(async () => {
-      if (!cursor || loadingMore) return;
-      setLoadingMore(true);
-      try {
-        const params = { limit: 50, cursor };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems((prev) => [...prev, ...(res.items || [])]);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoadingMore(false);
-      }
-    }, [cursor, filter, search, profile, loadingMore]);
-
-    // Infinite scroll via IntersectionObserver
-    useEffect(() => {
-      const el = sentinelRef.current;
-      if (!el || !hasMore) return;
-      const obs = new IntersectionObserver((entries) => {
-        if (entries[0].isIntersecting) loadMore();
-      }, { rootMargin: "200px" });
-      obs.observe(el);
-      return () => obs.disconnect();
-    }, [hasMore, loadMore]);
-
-    const onDownload = useCallback(async (item) => {
-      try {
-        const url = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-        const res = await authedFetch(url);
-        const blob = await res.blob();
-        const urlObj = URL.createObjectURL(blob);
-        const a = document.createElement("a");
-        a.href = urlObj;
-        a.download = item.name;
-        document.body.appendChild(a);
-        a.click();
-        document.body.removeChild(a);
-        setTimeout(() => URL.revokeObjectURL(urlObj), 10000);
-      } catch (e) {
-        alert("下载失败: " + (e.message || e));
-      }
-    }, [profile]);
-
-    const onSearchSubmit = useCallback((e) => {
-      e.preventDefault();
-      setSearch(searchInput.trim());
-    }, [searchInput]);
-
-    return h("div", { className: "yaoyao-page" },
-      // Header + stats
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "夭夭文件库"),
-        stats ? h("div", { className: "yaoyao-stats" },
-          profile && profile !== "default"
-            ? h(Badge, { variant: "secondary" }, `Agent: ${profile}`)
-            : null,
-          h(Badge, { variant: "secondary" }, `共 ${stats.totalAttachments} 个文件`),
-          h(Badge, { variant: "secondary" }, `${formatBytes(stats.totalBytes)}`),
-          stats.bySender && stats.bySender.agent
-            ? h(Badge, { variant: "outline" }, `Agent ${stats.bySender.agent}`)
-            : null,
-          stats.bySender && stats.bySender.user
-            ? h(Badge, { variant: "outline" }, `用户 ${stats.bySender.user}`)
-            : null,
-        ) : null
-      ),
-
-      // Filters
-      h("div", { className: "yaoyao-filters" },
-        h(Label, null, "Agent"),
-        h(Select, {
-          value: profile,
-          onValueChange: setProfile,
-          disabled: profiles.length === 0,
-        },
-          profiles.length === 0
-            ? h(SelectOption, { value: "default" }, "默认")
-            : profiles.map((p) =>
-                h(SelectOption, { key: p.name, value: p.name }, p.label)
-              )
-        ),
-        h(Label, null, "来源"),
-        h(Select, {
-          value: filter.sender,
-          onValueChange: (value) => setFilter((f) => ({ ...f, sender: value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "agent" }, "Agent"),
-          h(SelectOption, { value: "user" }, "用户")
-        ),
-        h(Label, null, "类型"),
-        h(Select, {
-          value: filter.kind,
-          onValueChange: (value) => setFilter((f) => ({ ...f, kind: value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "image" }, "图片"),
-          h(SelectOption, { value: "video" }, "视频"),
-          h(SelectOption, { value: "text" }, "文本"),
-          h(SelectOption, { value: "file" }, "文档")
-        ),
-        h("form", { onSubmit: onSearchSubmit, className: "yaoyao-search" },
-          h(Input, {
-            type: "text",
-            placeholder: "搜索文件名…",
-            value: searchInput,
-            onChange: (e) => setSearchInput(e.target.value),
-          }),
-          h(Button, { type: "submit", size: "sm" }, "搜索")
-        )
-      ),
-
-      // Error
-      error ? h("div", { className: "yaoyao-error" }, "错误: " + error) : null,
-
-      // Loading
-      loading ? h("div", { className: "yaoyao-loading" }, "加载中…") :
-      // Grid
-      items.length === 0
-        ? h("div", { className: "yaoyao-empty" }, "暂无文件")
-        : h("div", { className: "yaoyao-grid" },
-            items.map((item) =>
-              h(FileCard, { key: item.id, item: item, onDownload: onDownload, profile: profile })
-            )
-          ),
-
-      // Infinite scroll sentinel
-      hasMore ? h("div", {
-        ref: sentinelRef,
-        className: "yaoyao-sentinel"
-      }, loadingMore ? "加载更多…" : "") : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Agent display-name settings page
-  // ---------------------------------------------------------------------
-
-  function AgentSettingsPage() {
-    const [profiles, setProfiles] = useState([]);
-    const [profile, setProfile] = useState("default");
-    const [settings, setSettings] = useState(null);
-    const [draftName, setDraftName] = useState("");
-    const [loading, setLoading] = useState(true);
-    const [saving, setSaving] = useState(false);
-    const [error, setError] = useState(null);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    useEffect(() => {
-      fetchJSON(`${API}/profiles`)
-        .then((response) => setProfiles(response.profiles || []))
-        .catch((requestError) => setError(String(requestError.message || requestError)));
-    }, []);
-
-    useEffect(() => {
-      let cancelled = false;
-      setLoading(true);
-      setError(null);
-      fetchJSON(`${API}/agent/settings?profile=${encodeURIComponent(profile)}`)
-        .then((response) => {
-          if (cancelled) return;
-          setSettings(response);
-          setDraftName(response.agentName || "");
-        })
-        .catch((requestError) => {
-          if (!cancelled) setError(String(requestError.message || requestError));
-        })
-        .finally(() => {
-          if (!cancelled) setLoading(false);
-        });
-      return () => { cancelled = true; };
-    }, [profile]);
-
-    async function saveAgentName() {
-      setSaving(true);
-      setError(null);
-      try {
-        const response = await fetchJSON(
-          `${API}/agent/settings?profile=${encodeURIComponent(profile)}`,
-          {
-            method: "PUT",
-            headers: { "Content-Type": "application/json" },
-            body: JSON.stringify({ agentName: draftName.trim() }),
-          },
-        );
-        setSettings(response);
-        setDraftName(response.agentName || "");
-        setProfiles((current) => current.map((item) =>
-          item.name === profile
-            ? {
-                ...item,
-                agentName: response.agentName,
-                label: response.agentName || (profile === "default" ? "默认" : profile),
-              }
-            : item
-        ));
-        setSavedMsg("已保存");
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (requestError) {
-        setError(String(requestError.message || requestError));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    const effectiveName = settings?.agentName || (profile === "default" ? "default" : profile);
-    const readApi = `${API}/agent/settings?profile=${encodeURIComponent(profile)}`;
-
-    return h("div", { className: "yaoyao-page" },
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "Agent 设置"),
-        savedMsg ? h(Badge, { variant: "secondary" }, savedMsg) : null
-      ),
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "agent-profile" }, "Hermes Profile"),
-            h(Select, {
-              id: "agent-profile",
-              value: profile,
-              onValueChange: setProfile,
-              disabled: profiles.length === 0,
-            },
-              profiles.map((item) =>
-                h(SelectOption, { key: item.name, value: item.name },
-                  item.label === item.name ? item.name : `${item.label} (${item.name})`
-                )
-              )
-            )
-          ),
-          loading
-            ? h("div", { className: "yaoyao-loading" }, "加载中…")
-            : h(React.Fragment, null,
-                h("div", { className: "yaoyao-voice-row" },
-                  h(Label, { htmlFor: "agent-name" }, "Agent 名称"),
-                  h(Input, {
-                    id: "agent-name",
-                    type: "text",
-                    maxLength: 100,
-                    value: draftName,
-                    placeholder: `留空时使用 ${profile}`,
-                    onChange: (event) => setDraftName(event.target.value),
-                  })
-                ),
-                h("div", { className: "yaoyao-duplex-meta" },
-                  h("div", null,
-                    h("span", { className: "yaoyao-meta-label" }, "当前显示名称"),
-                    h("span", null, effectiveName)
-                  ),
-                  h("div", null,
-                    h("span", { className: "yaoyao-meta-label" }, "读取 API"),
-                    h("code", null, readApi)
-                  )
-                ),
-                h("p", { className: "yaoyao-hint" },
-                  "名称只用于展示,Profile ID 仍作为稳定的路由与数据隔离标识。留空保存可恢复默认名称。"
-                ),
-                h("div", { className: "yaoyao-voice-actions" },
-                  h(Button, {
-                    onClick: saveAgentName,
-                    disabled: saving,
-                  }, saving ? "保存中…" : "保存")
-                )
-              )
-        )
-      ),
-      error ? h("div", { className: "yaoyao-error" }, error) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Voice settings page
-  // ---------------------------------------------------------------------
-
-  // ---------------------------------------------------------------------
-  // Duplex voice settings page
-  // Mirrors yaoyao-webui's IosDuplexVoiceSettings.vue contract:
-  // {hasApiKey, voices:[{id,name}], currentVoiceId, updatedAt}
-  // ---------------------------------------------------------------------
-
-  function VoiceSettingsPage() {
-    const [settings, setSettings] = useState(null);
-    const [loading, setLoading] = useState(true);
-    const [saving, setSaving] = useState(false);
-    const [switching, setSwitching] = useState(false);
-    const [error, setError] = useState(null);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    // Draft state for the editor
-    const [draftApiKey, setDraftApiKey] = useState("");
-    const [draftVoices, setDraftVoices] = useState([]);
-    const [draftCurrent, setDraftCurrent] = useState("");
-    const [editing, setEditing] = useState(false);
-
-    useEffect(() => {
-      load();
-    }, []);
-
-    async function load() {
-      setLoading(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/settings`);
-        setSettings(s);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }
-
-    const voiceOptions = useMemo(() => {
-      if (!settings) return [];
-      return settings.voices
-        .filter((v) => v.id.trim() && v.name.trim())
-        .map((v) => ({ label: v.name, value: v.id }));
-    }, [settings]);
-
-    const isConfigured = settings
-      && settings.hasApiKey
-      && voiceOptions.length > 0
-      && voiceOptions.some((o) => o.value === settings.currentVoiceId);
-
-    function openEditor() {
-      setDraftApiKey("");
-      setDraftVoices((settings?.voices || []).map((v) => ({ ...v })));
-      setDraftCurrent(settings?.currentVoiceId || "");
-      setEditing(true);
-    }
-
-    function addVoice() {
-      setDraftVoices((prev) => [...prev, { id: "", name: "" }]);
-    }
-
-    function removeVoice(idx) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        const removed = next[idx];
-        next.splice(idx, 1);
-        if (removed?.id === draftCurrent) {
-          setDraftCurrent(next[0]?.id || "");
-        }
-        return next;
-      });
-    }
-
-    function updateVoice(idx, field, value) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        next[idx] = { ...next[idx], [field]: value };
-        return next;
-      });
-    }
-
-    async function saveSettings() {
-      setSaving(true);
-      setError(null);
-      try {
-        const body = {
-          voices: draftVoices.map((v) => ({ id: v.id.trim(), name: v.name.trim() })),
-          currentVoiceId: draftCurrent,
-        };
-        if (draftApiKey.trim()) body.apiKey = draftApiKey.trim();
-        const s = await fetchJSON(`${API}/voice/settings`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify(body),
-        });
-        setSettings(s);
-        setEditing(false);
-        setSavedMsg("已保存");
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function switchVoice(voiceId) {
-      if (switching || voiceId === settings.currentVoiceId) return;
-      setSwitching(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/current-voice`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify({ currentVoiceId: voiceId }),
-        });
-        setSettings((prev) => ({ ...prev, ...s }));
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSwitching(false);
-      }
-    }
-
-    if (loading) return h("div", { className: "yaoyao-loading" }, "加载中…");
-    if (!settings) return h("div", { className: "yaoyao-error" }, "加载失败: " + error);
-
-    const currentVoiceName = voiceOptions.find((o) => o.value === settings.currentVoiceId)?.label
-      || settings.currentVoiceId
-      || "未选择";
-
-    return h("div", { className: "yaoyao-page" },
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "App 双流直连配置"),
-        savedMsg ? h(Badge, { variant: "secondary" }, savedMsg) : null
-      ),
-
-      // Status card
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-duplex-status" },
-            h("div", { className: "yaoyao-duplex-icon" }, "D"),
-            h("div", { className: "yaoyao-duplex-info" },
-              h("div", { className: "yaoyao-duplex-title-row" },
-                h("h5", null, "火山引擎 / 豆包 TTS"),
-                h(Badge, {
-                  variant: isConfigured ? "default" : "secondary",
-                }, isConfigured ? "已配置" : "未配置")
-              ),
-              h("p", { className: "yaoyao-hint" },
-                "iOS App 直连 TTS 引擎进行双流语音对话。API Key 和声音列表在此配置后,App 从 /voice/runtime 拉取。")
-            )
-          ),
-          h("div", { className: "yaoyao-duplex-meta" },
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "当前声音"), h("span", null, currentVoiceName)),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "API Key"), h("span", null, settings.hasApiKey ? "已存储" : "未设置")),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "声音数量"), h("span", null, String(settings.voices.length))),
-          )
-        )
-      ),
-
-      // Current voice quick switch
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-current" }, "当前声音"),
-            h("div", { className: "yaoyao-voice-switch" },
-              h(Select, {
-                id: "duplex-current",
-                value: settings.currentVoiceId,
-                onValueChange: switchVoice,
-                disabled: switching || voiceOptions.length === 0,
-              },
-                voiceOptions.map((o) =>
-                  h(SelectOption, { key: o.value, value: o.value }, o.label)
-                )
-              ),
-              h(Button, {
-                variant: "outline",
-                size: "sm",
-                onClick: openEditor,
-              }, "编辑配置")
-            )
-          )
-        )
-      ),
-
-      error ? h("div", { className: "yaoyao-error" }, error) : null,
-
-      // Editor (inline form)
-      editing ? h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("h3", { className: "yaoyao-section-title" }, "编辑双流配置"),
-
-          // API Key
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-key" }, "API Key"),
-            h(Input, {
-              id: "duplex-key",
-              type: "password",
-              value: draftApiKey,
-              placeholder: settings.hasApiKey ? "已存储 (留空保持不变)" : "输入 API Key",
-              onChange: (e) => setDraftApiKey(e.target.value),
-            })
-          ),
-
-          // Current voice in draft
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-draft-current" }, "当前声音"),
-            h(Select, {
-              id: "duplex-draft-current",
-              value: draftCurrent,
-              onValueChange: setDraftCurrent,
-            },
-              draftVoices
-                .filter((v) => v.id.trim())
-                .map((v) =>
-                  h(SelectOption, { key: v.id, value: v.id }, v.name || v.id)
-                )
-            )
-          ),
-
-          // Voice list editor
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, null, "声音列表"),
-            h("div", { className: "yaoyao-voice-editor" },
-              draftVoices.map((voice, idx) =>
-                h("div", { key: idx, className: "yaoyao-voice-editor-row" },
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音名称 (如 小何 2.0)",
-                    value: voice.name,
-                    onChange: (e) => updateVoice(idx, "name", e.target.value),
-                  }),
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音 ID (如 zh_female_xiaohe_uranus_bigtts)",
-                    value: voice.id,
-                    onChange: (e) => updateVoice(idx, "id", e.target.value),
-                  }),
-                  h(Button, {
-                    variant: "ghost",
-                    size: "sm",
-                    disabled: draftVoices.length <= 1,
-                    onClick: () => removeVoice(idx),
-                  }, "×")
-                )
-              ),
-              h(Button, { variant: "outline", size: "sm", onClick: addVoice }, "+ 添加声音")
-            )
-          ),
-
-          h("div", { className: "yaoyao-voice-actions" },
-            h(Button, { variant: "ghost", onClick: () => setEditing(false) }, "取消"),
-            h(Button, { onClick: saveSettings, disabled: saving }, saving ? "保存中…" : "保存")
-          )
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // TTS / STT provider settings page
-  // Mirrors yaoyao-webui's VoiceSettings.vue + VoiceApiConfigurator.vue.
-  // ---------------------------------------------------------------------
-
-  function VoiceProvidersPage() {
-    const [ttsData, setTtsData] = useState(null);
-    const [sttData, setSttData] = useState(null);
-    const [providersInfo, setProvidersInfo] = useState(null);
-    const [error, setError] = useState(null);
-    const [saving, setSaving] = useState(false);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    useEffect(() => {
-      Promise.all([
-        fetchJSON(`${API}/tts/settings`),
-        fetchJSON(`${API}/stt/settings`),
-        fetchJSON(`${API}/voice/providers-info`),
-      ]).then(([t, s, p]) => {
-        setTtsData(t);
-        setSttData(s);
-        setProvidersInfo(p);
-      }).catch((e) => setError(String(e.message || e)));
-    }, []);
-
-    async function setTtsActive(provider) {
-      try {
-        await fetchJSON(`${API}/tts/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setTtsData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function setSttActive(provider) {
-      try {
-        await fetchJSON(`${API}/stt/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setSttData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function saveProvider(kind, provider, settings, secrets) {
-      setSaving(true);
-      setError(null);
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        const res = await fetchJSON(endpoint, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({settings, secrets}),
-        });
-        // Refresh
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-        setSavedMsg(`${provider} 已保存`);
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function deleteProvider(kind, provider) {
-      if (!confirm(`确定删除 ${provider} 配置?`)) return;
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        await fetchJSON(endpoint, {method: "DELETE"});
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    if (!ttsData || !sttData || !providersInfo) {
-      return h("div", {className: "yaoyao-loading"}, "加载中…");
-    }
-
-    const ttsProviders = providersInfo.tts.providers;
-    const sttProviders = providersInfo.stt.providers;
-
-    function renderProviderCard(kind, info, data) {
-      const settings = (data.settings || []).find(s => s.provider === info.id);
-      const isActive = data.activeProvider === info.id;
-      const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-      const isConfigured = info.id === "edge" || info.id === "browser" || hasKey;
-
-      return h(Card, {key: info.id, className: cn("yaoyao-provider-card", isActive && "yaoyao-provider-active")},
-        h(CardContent, {className: "yaoyao-voice-card"},
-          h("div", {className: "yaoyao-provider-header"},
-            h("div", {className: "yaoyao-provider-title-row"},
-              h("h5", null, info.label),
-              h(Badge, {variant: isActive ? "default" : "secondary"},
-                isActive ? "当前" : (isConfigured ? "已配置" : "未配置"))
-            ),
-            h("p", {className: "yaoyao-hint"},
-              info.needsKey ? "需要 API Key" : "免费 / 内置")
-          ),
-          h(ProviderEditor, {
-            kind, info, settings: settings || null, saving,
-            onSave: (s, sec) => saveProvider(kind, info.id, s, sec),
-            onDelete: info.id !== "edge" && info.id !== "browser"
-              ? () => deleteProvider(kind, info.id) : null,
-            onActivate: () => kind === "tts" ? setTtsActive(info.id) : setSttActive(info.id),
-          })
-        )
-      );
-    }
-
-    return h("div", {className: "yaoyao-page"},
-      h("div", {className: "yaoyao-header"},
-        h("h2", null, "语音引擎配置"),
-        savedMsg ? h(Badge, {variant: "secondary"}, savedMsg) : null
-      ),
-      error ? h("div", {className: "yaoyao-error"}, error) : null,
-
-      h("h3", {className: "yaoyao-section-title"}, "TTS (文字转语音)"),
-      h("div", {className: "yaoyao-provider-list"},
-        ttsProviders.map(info => renderProviderCard("tts", info, ttsData))
-      ),
-
-      h("h3", {className: "yaoyao-section-title"}, "STT (语音转文字)"),
-      h("div", {className: "yaoyao-provider-list"},
-        sttProviders.map(info => renderProviderCard("stt", info, sttData))
-      )
-    );
-  }
-
-  // Inline provider editor (expandable)
-  function ProviderEditor({kind, info, settings, saving, onSave, onDelete, onActivate}) {
-    const [expanded, setExpanded] = useState(false);
-    const [draft, setDraft] = useState({});
-
-    useEffect(() => {
-      if (settings) {
-        setDraft({
-          baseUrl: settings.settings?.baseUrl || info.defaults?.baseUrl || "",
-          model: settings.settings?.model || info.defaults?.model || "",
-          voice: settings.settings?.voice || info.defaults?.voice || "",
-          language: settings.settings?.language || info.defaults?.language || "",
-          rate: settings.settings?.rate || "",
-          pitch: settings.settings?.pitch || "",
-          stylePrompt: settings.settings?.stylePrompt || "",
-          apiKey: "",
-        });
-      } else {
-        setDraft({
-          baseUrl: info.defaults?.baseUrl || "",
-          model: info.defaults?.model || "",
-          voice: info.defaults?.voice || "",
-          language: info.defaults?.language || "",
-          apiKey: "",
-        });
-      }
-    }, [info.id, settings]);
-
-    function update(field, value) {
-      setDraft(d => ({...d, [field]: value}));
-    }
-
-    function handleSave() {
-      const s = {};
-      const sec = {};
-      if (draft.baseUrl) s.baseUrl = draft.baseUrl;
-      if (draft.model) s.model = draft.model;
-      if (draft.voice) s.voice = draft.voice;
-      if (draft.language) s.language = draft.language;
-      if (draft.rate) s.rate = draft.rate;
-      if (draft.pitch) s.pitch = draft.pitch;
-      if (draft.stylePrompt) s.stylePrompt = draft.stylePrompt;
-      if (draft.apiKey) sec.apiKey = draft.apiKey;
-      onSave(s, sec);
-    }
-
-    const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-    const showFields = info.settingsKeys || [];
-
-    return h("div", {className: "yaoyao-provider-editor"},
-      h("div", {className: "yaoyao-provider-actions"},
-        h(Button, {variant: "outline", size: "sm", onClick: () => setExpanded(e => !e)},
-          expanded ? "收起" : "展开"),
-        onActivate ? h(Button, {variant: "ghost", size: "sm", onClick: onActivate}, "设为当前") : null,
-      ),
-      expanded ? h("div", {className: "yaoyao-provider-fields"},
-        showFields.includes("baseUrl") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "Base URL"),
-          h(Input, {type: "text", value: draft.baseUrl, onChange: e => update("baseUrl", e.target.value),
-            placeholder: "https://..."})
-        ) : null,
-        showFields.includes("model") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "模型"),
-          h(Input, {type: "text", value: draft.model, onChange: e => update("model", e.target.value),
-            placeholder: "model id"})
-        ) : null,
-        showFields.includes("voice") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "声音"),
-          h(Input, {type: "text", value: draft.voice, onChange: e => update("voice", e.target.value),
-            placeholder: "voice id"})
-        ) : null,
-        showFields.includes("language") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语言"),
-          h(Input, {type: "text", value: draft.language, onChange: e => update("language", e.target.value),
-            placeholder: "zh / en / ..."})
-        ) : null,
-        showFields.includes("rate") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语速"),
-          h(Input, {type: "text", value: draft.rate, onChange: e => update("rate", e.target.value),
-            placeholder: "+0%"})
-        ) : null,
-        showFields.includes("pitch") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "音调"),
-          h(Input, {type: "text", value: draft.pitch, onChange: e => update("pitch", e.target.value),
-            placeholder: "+0Hz"})
-        ) : null,
-        showFields.includes("stylePrompt") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "风格提示"),
-          h(Input, {type: "text", value: draft.stylePrompt, onChange: e => update("stylePrompt", e.target.value),
-            placeholder: "style prompt"})
-        ) : null,
-        info.needsKey ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "API Key"),
-          h(Input, {type: "password", value: draft.apiKey,
-            onChange: e => update("apiKey", e.target.value),
-            placeholder: hasKey ? "已存储 (留空保持不变)" : "输入 API Key"})
-        ) : null,
-        h("div", {className: "yaoyao-voice-actions"},
-          h(Button, {size: "sm", onClick: handleSave, disabled: saving},
-            saving ? "保存中…" : "保存"),
-          onDelete ? h(Button, {variant: "ghost", size: "sm", onClick: onDelete}, "删除") : null,
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Top-level page with internal tab switcher
-  // ---------------------------------------------------------------------
-
-  function YaoyaoPage() {
-    const [tab, setTab] = useState("files");
-    return h("div", { className: "yaoyao-root" },
-      h("div", { className: "yaoyao-tabs" },
-        h("button", {
-          className: cn("yaoyao-tab", tab === "files" && "yaoyao-tab-active"),
-          onClick: () => setTab("files"),
-        }, "文件库"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "agent" && "yaoyao-tab-active"),
-          onClick: () => setTab("agent"),
-        }, "Agent设置"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "duplex" && "yaoyao-tab-active"),
-          onClick: () => setTab("duplex"),
-        }, "App双流直连"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "engines" && "yaoyao-tab-active"),
-          onClick: () => setTab("engines"),
-        }, "语音引擎")
-      ),
-      tab === "files" ? h(YaoyaoFilesPage)
-      : tab === "agent" ? h(AgentSettingsPage)
-      : tab === "duplex" ? h(VoiceSettingsPage)
-      : h(VoiceProvidersPage)
-    );
-  }
-
-  // Register the plugin page. The name MUST match manifest.json "name".
-  if (window.__HERMES_PLUGINS__ &&
-      typeof window.__HERMES_PLUGINS__.register === "function") {
-    window.__HERMES_PLUGINS__.register("yaoyao", YaoyaoPage);
-  }
-})();

+ 0 - 934
hermes-plugins/yaoyao/dashboard/dist/index.v1.1.0.js

@@ -1,934 +0,0 @@
-/**
- * Yaoyao File Library - dashboard plugin frontend.
- *
- * Plain IIFE, no build step. Uses window.__HERMES_PLUGIN_SDK__ for React +
- * shadcn-ui primitives + fetchJSON / authedFetch. Backend routes live under
- * /api/plugins/yaoyao/ (auto-mounted by the dashboard plugin loader).
- */
-(function () {
-  "use strict";
-
-  const SDK = window.__HERMES_PLUGIN_SDK__;
-  if (!SDK) return;
-  const { React } = SDK;
-  const h = React.createElement;
-  const { useState, useEffect, useCallback, useRef, useMemo } = SDK.hooks;
-  const {
-    Card,
-    CardContent,
-    Badge,
-    Button,
-    Input,
-    Label,
-    Select,
-    SelectOption,
-  } = SDK.components;
-  const { cn, timeAgo } = SDK.utils;
-  const fetchJSON = SDK.fetchJSON;
-  const authedFetch = SDK.authedFetch;
-
-  const API = "/api/plugins/yaoyao";
-
-  // ---------------------------------------------------------------------
-  // Helpers
-  // ---------------------------------------------------------------------
-
-  function inferKind(name, mimeType) {
-    const ext = (name.split(".").pop() || "").toLowerCase();
-    if ((mimeType || "").startsWith("image/") ||
-        ["png","jpg","jpeg","gif","webp","bmp","svg","tiff","tif"].includes(ext))
-      return "image";
-    if ((mimeType || "").startsWith("video/") ||
-        ["mp4","mov","avi","mkv","webm","m4v","wmv","flv"].includes(ext))
-      return "video";
-    if ((mimeType || "").startsWith("text/") ||
-        ["txt","md","json","yaml","yml","csv","log","py","js","ts","html","xml","rst"].includes(ext))
-      return "text";
-    return "file";
-  }
-
-  function formatBytes(n) {
-    if (!n || n <= 0) return "0 B";
-    const units = ["B", "KB", "MB", "GB"];
-    let i = 0, v = n;
-    while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
-    return v >= 100 ? v.toFixed(0) + " " + units[i]
-         : v >= 10  ? v.toFixed(1) + " " + units[i]
-                    : v.toFixed(2) + " " + units[i];
-  }
-
-  function senderLabel(s) {
-    return s === "user" ? "用户" : s === "agent" ? "Agent" : s;
-  }
-
-  function kindIcon(kind) {
-    switch (kind) {
-      case "image": return "🖼";
-      case "video": return "🎬";
-      case "text": return "📄";
-      default: return "📦";
-    }
-  }
-
-  // ---------------------------------------------------------------------
-  // Thumbnail image: fetch as blob via authedFetch (img tags can't set
-  // Authorization headers), then create an object URL.
-  // ---------------------------------------------------------------------
-
-  function Thumbnail({ item, profile }) {
-    const [url, setUrl] = useState(null);
-    const [err, setErr] = useState(false);
-    const kind = inferKind(item.name, item.mimeType);
-
-    useEffect(() => {
-      if (kind !== "image") return;
-      let revoke = null;
-      let cancelled = false;
-      const dlUrl = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-      authedFetch(dlUrl)
-        .then((res) => res.blob())
-        .then((blob) => {
-          if (cancelled) return;
-          const u = URL.createObjectURL(blob);
-          revoke = u;
-          setUrl(u);
-        })
-        .catch(() => { if (!cancelled) setErr(true); });
-      return () => {
-        cancelled = true;
-        if (revoke) URL.revokeObjectURL(revoke);
-      };
-    }, [item.id, profile]);
-
-    if (kind !== "image") {
-      return h("div", {
-        className: "yaoyao-thumb yaoyao-thumb-icon",
-      }, kindIcon(kind));
-    }
-    if (err) return h("div", { className: "yaoyao-thumb yaoyao-thumb-icon" }, "🖼");
-    if (!url) return h("div", { className: "yaoyao-thumb yaoyao-thumb-loading" }, "…");
-    return h("img", {
-      src: url,
-      alt: item.name,
-      className: "yaoyao-thumb yaoyao-thumb-img",
-      loading: "lazy",
-    });
-  }
-
-  // ---------------------------------------------------------------------
-  // File card
-  // ---------------------------------------------------------------------
-
-  function FileCard({ item, onDownload, profile }) {
-    const kind = inferKind(item.name, item.mimeType);
-    return h(Card, { className: "yaoyao-card" },
-      h(CardContent, { className: "yaoyao-card-content" },
-        h("div", { className: "yaoyao-card-preview" },
-          h(Thumbnail, { item: item, profile: profile })
-        ),
-        h("div", { className: "yaoyao-card-info" },
-          h("div", { className: "yaoyao-card-name", title: item.name }, item.name),
-          h("div", { className: "yaoyao-card-meta" },
-            h(Badge, { variant: "secondary" }, senderLabel(item.origins && item.origins[0] ? item.origins[0].authorKind : "agent")),
-            h("span", { className: "yaoyao-card-size" }, formatBytes(item.size)),
-            item.messageTimestamp
-              ? h("span", { className: "yaoyao-card-time" }, timeAgo(item.messageTimestamp * 1000))
-              : null
-          ),
-          h("div", { className: "yaoyao-card-actions" },
-            h(Button, {
-              variant: "outline",
-              size: "sm",
-              onClick: () => onDownload(item),
-            }, "下载")
-          )
-        )
-      )
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Main page
-  // ---------------------------------------------------------------------
-
-  function YaoyaoFilesPage() {
-    const [items, setItems] = useState([]);
-    const [loading, setLoading] = useState(true);
-    const [loadingMore, setLoadingMore] = useState(false);
-    const [error, setError] = useState(null);
-    const [cursor, setCursor] = useState(null);
-    const [hasMore, setHasMore] = useState(false);
-    const [stats, setStats] = useState(null);
-    const [profiles, setProfiles] = useState([]);
-    // Initial profile from the URL (?profile=gril) so deep links / shared
-    // links land on the right agent's library; fall back to "default".
-    const [profile, setProfile] = useState(() => {
-      try {
-        const u = new URL(window.location.href);
-        const p = u.searchParams.get("profile");
-        return p || "default";
-      } catch (e) {
-        return "default";
-      }
-    });
-    const [filter, setFilter] = useState({ sender: "", kind: "" });
-    const [search, setSearch] = useState("");
-    const [searchInput, setSearchInput] = useState("");
-    const sentinelRef = useRef(null);
-
-    // Keep the URL ?profile= in sync with the dropdown selection so the
-    // address bar reflects what's shown (and is shareable / refreshable).
-    useEffect(() => {
-      try {
-        const u = new URL(window.location.href);
-        if (profile && profile !== "default") {
-          u.searchParams.set("profile", profile);
-        } else {
-          u.searchParams.delete("profile");
-        }
-        window.history.replaceState(null, "", u.toString());
-      } catch (e) { /* ignore */ }
-    }, [profile]);
-
-    // Also react to back/forward navigation so the dropdown follows the URL.
-    useEffect(() => {
-      const onPop = () => {
-        try {
-          const u = new URL(window.location.href);
-          const p = u.searchParams.get("profile") || "default";
-          setProfile(p);
-        } catch (e) { /* ignore */ }
-      };
-      window.addEventListener("popstate", onPop);
-      return () => window.removeEventListener("popstate", onPop);
-    }, []);
-
-    // Profiles dropdown: which agents have libraries. default always present.
-    useEffect(() => {
-      fetchJSON(`${API}/profiles`)
-        .then((res) => {
-          const list = (res.profiles || []);
-          setProfiles(list);
-          // If the current selection vanished (profile deleted), fall back.
-          if (list.length && !list.some((p) => p.name === profile)) {
-            setProfile("default");
-          }
-        })
-        .catch(() => {});
-    }, []); // eslint-disable-line
-
-    // Fetch first page whenever filter / search / profile changes.
-    const loadFirst = useCallback(async () => {
-      setLoading(true);
-      setError(null);
-      try {
-        const params = { limit: 50 };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems(res.items || []);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }, [filter, search, profile]);
-
-    useEffect(() => { loadFirst(); }, [loadFirst]);
-
-    // Stats (re-fetch when profile changes)
-    useEffect(() => {
-      const params = {};
-      if (profile) params.profile = profile;
-      const qs = new URLSearchParams(params).toString();
-      fetchJSON(`${API}/stats?${qs}`).then(setStats).catch(() => {});
-    }, [profile]);
-
-    // Load more
-    const loadMore = useCallback(async () => {
-      if (!cursor || loadingMore) return;
-      setLoadingMore(true);
-      try {
-        const params = { limit: 50, cursor };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems((prev) => [...prev, ...(res.items || [])]);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoadingMore(false);
-      }
-    }, [cursor, filter, search, profile, loadingMore]);
-
-    // Infinite scroll via IntersectionObserver
-    useEffect(() => {
-      const el = sentinelRef.current;
-      if (!el || !hasMore) return;
-      const obs = new IntersectionObserver((entries) => {
-        if (entries[0].isIntersecting) loadMore();
-      }, { rootMargin: "200px" });
-      obs.observe(el);
-      return () => obs.disconnect();
-    }, [hasMore, loadMore]);
-
-    const onDownload = useCallback(async (item) => {
-      try {
-        const url = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-        const res = await authedFetch(url);
-        const blob = await res.blob();
-        const urlObj = URL.createObjectURL(blob);
-        const a = document.createElement("a");
-        a.href = urlObj;
-        a.download = item.name;
-        document.body.appendChild(a);
-        a.click();
-        document.body.removeChild(a);
-        setTimeout(() => URL.revokeObjectURL(urlObj), 10000);
-      } catch (e) {
-        alert("下载失败: " + (e.message || e));
-      }
-    }, [profile]);
-
-    const onSearchSubmit = useCallback((e) => {
-      e.preventDefault();
-      setSearch(searchInput.trim());
-    }, [searchInput]);
-
-    return h("div", { className: "yaoyao-page" },
-      // Header + stats
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "夭夭文件库"),
-        stats ? h("div", { className: "yaoyao-stats" },
-          profile && profile !== "default"
-            ? h(Badge, { variant: "secondary" }, `Agent: ${profile}`)
-            : null,
-          h(Badge, { variant: "secondary" }, `共 ${stats.totalAttachments} 个文件`),
-          h(Badge, { variant: "secondary" }, `${formatBytes(stats.totalBytes)}`),
-          stats.bySender && stats.bySender.agent
-            ? h(Badge, { variant: "outline" }, `Agent ${stats.bySender.agent}`)
-            : null,
-          stats.bySender && stats.bySender.user
-            ? h(Badge, { variant: "outline" }, `用户 ${stats.bySender.user}`)
-            : null,
-        ) : null
-      ),
-
-      // Filters
-      h("div", { className: "yaoyao-filters" },
-        h(Label, null, "Agent"),
-        h(Select, {
-          value: profile,
-          onChange: (e) => setProfile(e.target.value),
-          disabled: profiles.length === 0,
-        },
-          profiles.length === 0
-            ? h(SelectOption, { value: "default" }, "默认")
-            : profiles.map((p) =>
-                h(SelectOption, { key: p.name, value: p.name }, p.label)
-              )
-        ),
-        h(Label, null, "来源"),
-        h(Select, {
-          value: filter.sender,
-          onChange: (e) => setFilter((f) => ({ ...f, sender: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "agent" }, "Agent"),
-          h(SelectOption, { value: "user" }, "用户")
-        ),
-        h(Label, null, "类型"),
-        h(Select, {
-          value: filter.kind,
-          onChange: (e) => setFilter((f) => ({ ...f, kind: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "image" }, "图片"),
-          h(SelectOption, { value: "video" }, "视频"),
-          h(SelectOption, { value: "text" }, "文本"),
-          h(SelectOption, { value: "file" }, "文档")
-        ),
-        h("form", { onSubmit: onSearchSubmit, className: "yaoyao-search" },
-          h(Input, {
-            type: "text",
-            placeholder: "搜索文件名…",
-            value: searchInput,
-            onChange: (e) => setSearchInput(e.target.value),
-          }),
-          h(Button, { type: "submit", size: "sm" }, "搜索")
-        )
-      ),
-
-      // Error
-      error ? h("div", { className: "yaoyao-error" }, "错误: " + error) : null,
-
-      // Loading
-      loading ? h("div", { className: "yaoyao-loading" }, "加载中…") :
-      // Grid
-      items.length === 0
-        ? h("div", { className: "yaoyao-empty" }, "暂无文件")
-        : h("div", { className: "yaoyao-grid" },
-            items.map((item) =>
-              h(FileCard, { key: item.id, item: item, onDownload: onDownload, profile: profile })
-            )
-          ),
-
-      // Infinite scroll sentinel
-      hasMore ? h("div", {
-        ref: sentinelRef,
-        className: "yaoyao-sentinel"
-      }, loadingMore ? "加载更多…" : "") : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Voice settings page
-  // ---------------------------------------------------------------------
-
-  // ---------------------------------------------------------------------
-  // Duplex voice settings page
-  // Mirrors yaoyao-webui's IosDuplexVoiceSettings.vue contract:
-  // {hasApiKey, voices:[{id,name}], currentVoiceId, updatedAt}
-  // ---------------------------------------------------------------------
-
-  function VoiceSettingsPage() {
-    const [settings, setSettings] = useState(null);
-    const [loading, setLoading] = useState(true);
-    const [saving, setSaving] = useState(false);
-    const [switching, setSwitching] = useState(false);
-    const [error, setError] = useState(null);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    // Draft state for the editor
-    const [draftApiKey, setDraftApiKey] = useState("");
-    const [draftVoices, setDraftVoices] = useState([]);
-    const [draftCurrent, setDraftCurrent] = useState("");
-    const [editing, setEditing] = useState(false);
-
-    useEffect(() => {
-      load();
-    }, []);
-
-    async function load() {
-      setLoading(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/settings`);
-        setSettings(s);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }
-
-    const voiceOptions = useMemo(() => {
-      if (!settings) return [];
-      return settings.voices
-        .filter((v) => v.id.trim() && v.name.trim())
-        .map((v) => ({ label: v.name, value: v.id }));
-    }, [settings]);
-
-    const isConfigured = settings
-      && settings.hasApiKey
-      && voiceOptions.length > 0
-      && voiceOptions.some((o) => o.value === settings.currentVoiceId);
-
-    function openEditor() {
-      setDraftApiKey("");
-      setDraftVoices((settings?.voices || []).map((v) => ({ ...v })));
-      setDraftCurrent(settings?.currentVoiceId || "");
-      setEditing(true);
-    }
-
-    function addVoice() {
-      setDraftVoices((prev) => [...prev, { id: "", name: "" }]);
-    }
-
-    function removeVoice(idx) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        const removed = next[idx];
-        next.splice(idx, 1);
-        if (removed?.id === draftCurrent) {
-          setDraftCurrent(next[0]?.id || "");
-        }
-        return next;
-      });
-    }
-
-    function updateVoice(idx, field, value) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        next[idx] = { ...next[idx], [field]: value };
-        return next;
-      });
-    }
-
-    async function saveSettings() {
-      setSaving(true);
-      setError(null);
-      try {
-        const body = {
-          voices: draftVoices.map((v) => ({ id: v.id.trim(), name: v.name.trim() })),
-          currentVoiceId: draftCurrent,
-        };
-        if (draftApiKey.trim()) body.apiKey = draftApiKey.trim();
-        const s = await fetchJSON(`${API}/voice/settings`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify(body),
-        });
-        setSettings(s);
-        setEditing(false);
-        setSavedMsg("已保存");
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function switchVoice(voiceId) {
-      if (switching || voiceId === settings.currentVoiceId) return;
-      setSwitching(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/current-voice`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify({ currentVoiceId: voiceId }),
-        });
-        setSettings((prev) => ({ ...prev, ...s }));
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSwitching(false);
-      }
-    }
-
-    if (loading) return h("div", { className: "yaoyao-loading" }, "加载中…");
-    if (!settings) return h("div", { className: "yaoyao-error" }, "加载失败: " + error);
-
-    const currentVoiceName = voiceOptions.find((o) => o.value === settings.currentVoiceId)?.label
-      || settings.currentVoiceId
-      || "未选择";
-
-    return h("div", { className: "yaoyao-page" },
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "App 双流直连配置"),
-        savedMsg ? h(Badge, { variant: "secondary" }, savedMsg) : null
-      ),
-
-      // Status card
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-duplex-status" },
-            h("div", { className: "yaoyao-duplex-icon" }, "D"),
-            h("div", { className: "yaoyao-duplex-info" },
-              h("div", { className: "yaoyao-duplex-title-row" },
-                h("h5", null, "火山引擎 / 豆包 TTS"),
-                h(Badge, {
-                  variant: isConfigured ? "default" : "secondary",
-                }, isConfigured ? "已配置" : "未配置")
-              ),
-              h("p", { className: "yaoyao-hint" },
-                "iOS App 直连 TTS 引擎进行双流语音对话。API Key 和声音列表在此配置后,App 从 /voice/runtime 拉取。")
-            )
-          ),
-          h("div", { className: "yaoyao-duplex-meta" },
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "当前声音"), h("span", null, currentVoiceName)),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "API Key"), h("span", null, settings.hasApiKey ? "已存储" : "未设置")),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "声音数量"), h("span", null, String(settings.voices.length))),
-          )
-        )
-      ),
-
-      // Current voice quick switch
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-current" }, "当前声音"),
-            h("div", { className: "yaoyao-voice-switch" },
-              h(Select, {
-                id: "duplex-current",
-                value: settings.currentVoiceId,
-                onChange: (e) => switchVoice(e.target.value),
-                disabled: switching || voiceOptions.length === 0,
-              },
-                voiceOptions.map((o) =>
-                  h(SelectOption, { key: o.value, value: o.value }, o.label)
-                )
-              ),
-              h(Button, {
-                variant: "outline",
-                size: "sm",
-                onClick: openEditor,
-              }, "编辑配置")
-            )
-          )
-        )
-      ),
-
-      error ? h("div", { className: "yaoyao-error" }, error) : null,
-
-      // Editor (inline form)
-      editing ? h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("h3", { className: "yaoyao-section-title" }, "编辑双流配置"),
-
-          // API Key
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-key" }, "API Key"),
-            h(Input, {
-              id: "duplex-key",
-              type: "password",
-              value: draftApiKey,
-              placeholder: settings.hasApiKey ? "已存储 (留空保持不变)" : "输入 API Key",
-              onChange: (e) => setDraftApiKey(e.target.value),
-            })
-          ),
-
-          // Current voice in draft
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-draft-current" }, "当前声音"),
-            h(Select, {
-              id: "duplex-draft-current",
-              value: draftCurrent,
-              onChange: (e) => setDraftCurrent(e.target.value),
-            },
-              draftVoices
-                .filter((v) => v.id.trim())
-                .map((v) =>
-                  h(SelectOption, { key: v.id, value: v.id }, v.name || v.id)
-                )
-            )
-          ),
-
-          // Voice list editor
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, null, "声音列表"),
-            h("div", { className: "yaoyao-voice-editor" },
-              draftVoices.map((voice, idx) =>
-                h("div", { key: idx, className: "yaoyao-voice-editor-row" },
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音名称 (如 小何 2.0)",
-                    value: voice.name,
-                    onChange: (e) => updateVoice(idx, "name", e.target.value),
-                  }),
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音 ID (如 zh_female_xiaohe_uranus_bigtts)",
-                    value: voice.id,
-                    onChange: (e) => updateVoice(idx, "id", e.target.value),
-                  }),
-                  h(Button, {
-                    variant: "ghost",
-                    size: "sm",
-                    disabled: draftVoices.length <= 1,
-                    onClick: () => removeVoice(idx),
-                  }, "×")
-                )
-              ),
-              h(Button, { variant: "outline", size: "sm", onClick: addVoice }, "+ 添加声音")
-            )
-          ),
-
-          h("div", { className: "yaoyao-voice-actions" },
-            h(Button, { variant: "ghost", onClick: () => setEditing(false) }, "取消"),
-            h(Button, { onClick: saveSettings, disabled: saving }, saving ? "保存中…" : "保存")
-          )
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // TTS / STT provider settings page
-  // Mirrors yaoyao-webui's VoiceSettings.vue + VoiceApiConfigurator.vue.
-  // ---------------------------------------------------------------------
-
-  function VoiceProvidersPage() {
-    const [ttsData, setTtsData] = useState(null);
-    const [sttData, setSttData] = useState(null);
-    const [providersInfo, setProvidersInfo] = useState(null);
-    const [error, setError] = useState(null);
-    const [saving, setSaving] = useState(false);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    useEffect(() => {
-      Promise.all([
-        fetchJSON(`${API}/tts/settings`),
-        fetchJSON(`${API}/stt/settings`),
-        fetchJSON(`${API}/voice/providers-info`),
-      ]).then(([t, s, p]) => {
-        setTtsData(t);
-        setSttData(s);
-        setProvidersInfo(p);
-      }).catch((e) => setError(String(e.message || e)));
-    }, []);
-
-    async function setTtsActive(provider) {
-      try {
-        await fetchJSON(`${API}/tts/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setTtsData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function setSttActive(provider) {
-      try {
-        await fetchJSON(`${API}/stt/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setSttData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function saveProvider(kind, provider, settings, secrets) {
-      setSaving(true);
-      setError(null);
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        const res = await fetchJSON(endpoint, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({settings, secrets}),
-        });
-        // Refresh
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-        setSavedMsg(`${provider} 已保存`);
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function deleteProvider(kind, provider) {
-      if (!confirm(`确定删除 ${provider} 配置?`)) return;
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        await fetchJSON(endpoint, {method: "DELETE"});
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    if (!ttsData || !sttData || !providersInfo) {
-      return h("div", {className: "yaoyao-loading"}, "加载中…");
-    }
-
-    const ttsProviders = providersInfo.tts.providers;
-    const sttProviders = providersInfo.stt.providers;
-
-    function renderProviderCard(kind, info, data) {
-      const settings = (data.settings || []).find(s => s.provider === info.id);
-      const isActive = data.activeProvider === info.id;
-      const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-      const isConfigured = info.id === "edge" || info.id === "browser" || hasKey;
-
-      return h(Card, {key: info.id, className: cn("yaoyao-provider-card", isActive && "yaoyao-provider-active")},
-        h(CardContent, {className: "yaoyao-voice-card"},
-          h("div", {className: "yaoyao-provider-header"},
-            h("div", {className: "yaoyao-provider-title-row"},
-              h("h5", null, info.label),
-              h(Badge, {variant: isActive ? "default" : "secondary"},
-                isActive ? "当前" : (isConfigured ? "已配置" : "未配置"))
-            ),
-            h("p", {className: "yaoyao-hint"},
-              info.needsKey ? "需要 API Key" : "免费 / 内置")
-          ),
-          h(ProviderEditor, {
-            kind, info, settings: settings || null, saving,
-            onSave: (s, sec) => saveProvider(kind, info.id, s, sec),
-            onDelete: info.id !== "edge" && info.id !== "browser"
-              ? () => deleteProvider(kind, info.id) : null,
-            onActivate: () => kind === "tts" ? setTtsActive(info.id) : setSttActive(info.id),
-          })
-        )
-      );
-    }
-
-    return h("div", {className: "yaoyao-page"},
-      h("div", {className: "yaoyao-header"},
-        h("h2", null, "语音引擎配置"),
-        savedMsg ? h(Badge, {variant: "secondary"}, savedMsg) : null
-      ),
-      error ? h("div", {className: "yaoyao-error"}, error) : null,
-
-      h("h3", {className: "yaoyao-section-title"}, "TTS (文字转语音)"),
-      h("div", {className: "yaoyao-provider-list"},
-        ttsProviders.map(info => renderProviderCard("tts", info, ttsData))
-      ),
-
-      h("h3", {className: "yaoyao-section-title"}, "STT (语音转文字)"),
-      h("div", {className: "yaoyao-provider-list"},
-        sttProviders.map(info => renderProviderCard("stt", info, sttData))
-      )
-    );
-  }
-
-  // Inline provider editor (expandable)
-  function ProviderEditor({kind, info, settings, saving, onSave, onDelete, onActivate}) {
-    const [expanded, setExpanded] = useState(false);
-    const [draft, setDraft] = useState({});
-
-    useEffect(() => {
-      if (settings) {
-        setDraft({
-          baseUrl: settings.settings?.baseUrl || info.defaults?.baseUrl || "",
-          model: settings.settings?.model || info.defaults?.model || "",
-          voice: settings.settings?.voice || info.defaults?.voice || "",
-          language: settings.settings?.language || info.defaults?.language || "",
-          rate: settings.settings?.rate || "",
-          pitch: settings.settings?.pitch || "",
-          stylePrompt: settings.settings?.stylePrompt || "",
-          apiKey: "",
-        });
-      } else {
-        setDraft({
-          baseUrl: info.defaults?.baseUrl || "",
-          model: info.defaults?.model || "",
-          voice: info.defaults?.voice || "",
-          language: info.defaults?.language || "",
-          apiKey: "",
-        });
-      }
-    }, [info.id, settings]);
-
-    function update(field, value) {
-      setDraft(d => ({...d, [field]: value}));
-    }
-
-    function handleSave() {
-      const s = {};
-      const sec = {};
-      if (draft.baseUrl) s.baseUrl = draft.baseUrl;
-      if (draft.model) s.model = draft.model;
-      if (draft.voice) s.voice = draft.voice;
-      if (draft.language) s.language = draft.language;
-      if (draft.rate) s.rate = draft.rate;
-      if (draft.pitch) s.pitch = draft.pitch;
-      if (draft.stylePrompt) s.stylePrompt = draft.stylePrompt;
-      if (draft.apiKey) sec.apiKey = draft.apiKey;
-      onSave(s, sec);
-    }
-
-    const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-    const showFields = info.settingsKeys || [];
-
-    return h("div", {className: "yaoyao-provider-editor"},
-      h("div", {className: "yaoyao-provider-actions"},
-        h(Button, {variant: "outline", size: "sm", onClick: () => setExpanded(e => !e)},
-          expanded ? "收起" : "展开"),
-        onActivate ? h(Button, {variant: "ghost", size: "sm", onClick: onActivate}, "设为当前") : null,
-      ),
-      expanded ? h("div", {className: "yaoyao-provider-fields"},
-        showFields.includes("baseUrl") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "Base URL"),
-          h(Input, {type: "text", value: draft.baseUrl, onChange: e => update("baseUrl", e.target.value),
-            placeholder: "https://..."})
-        ) : null,
-        showFields.includes("model") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "模型"),
-          h(Input, {type: "text", value: draft.model, onChange: e => update("model", e.target.value),
-            placeholder: "model id"})
-        ) : null,
-        showFields.includes("voice") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "声音"),
-          h(Input, {type: "text", value: draft.voice, onChange: e => update("voice", e.target.value),
-            placeholder: "voice id"})
-        ) : null,
-        showFields.includes("language") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语言"),
-          h(Input, {type: "text", value: draft.language, onChange: e => update("language", e.target.value),
-            placeholder: "zh / en / ..."})
-        ) : null,
-        showFields.includes("rate") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语速"),
-          h(Input, {type: "text", value: draft.rate, onChange: e => update("rate", e.target.value),
-            placeholder: "+0%"})
-        ) : null,
-        showFields.includes("pitch") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "音调"),
-          h(Input, {type: "text", value: draft.pitch, onChange: e => update("pitch", e.target.value),
-            placeholder: "+0Hz"})
-        ) : null,
-        showFields.includes("stylePrompt") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "风格提示"),
-          h(Input, {type: "text", value: draft.stylePrompt, onChange: e => update("stylePrompt", e.target.value),
-            placeholder: "style prompt"})
-        ) : null,
-        info.needsKey ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "API Key"),
-          h(Input, {type: "password", value: draft.apiKey,
-            onChange: e => update("apiKey", e.target.value),
-            placeholder: hasKey ? "已存储 (留空保持不变)" : "输入 API Key"})
-        ) : null,
-        h("div", {className: "yaoyao-voice-actions"},
-          h(Button, {size: "sm", onClick: handleSave, disabled: saving},
-            saving ? "保存中…" : "保存"),
-          onDelete ? h(Button, {variant: "ghost", size: "sm", onClick: onDelete}, "删除") : null,
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Top-level page with internal tab switcher (Files / Duplex / Engines)
-  // ---------------------------------------------------------------------
-
-  function YaoyaoPage() {
-    const [tab, setTab] = useState("files");
-    return h("div", { className: "yaoyao-root" },
-      h("div", { className: "yaoyao-tabs" },
-        h("button", {
-          className: cn("yaoyao-tab", tab === "files" && "yaoyao-tab-active"),
-          onClick: () => setTab("files"),
-        }, "文件库"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "duplex" && "yaoyao-tab-active"),
-          onClick: () => setTab("duplex"),
-        }, "App双流直连"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "engines" && "yaoyao-tab-active"),
-          onClick: () => setTab("engines"),
-        }, "语音引擎")
-      ),
-      tab === "files" ? h(YaoyaoFilesPage)
-      : tab === "duplex" ? h(VoiceSettingsPage)
-      : h(VoiceProvidersPage)
-    );
-  }
-
-  // Register the plugin page. The name MUST match manifest.json "name".
-  if (window.__HERMES_PLUGINS__ &&
-      typeof window.__HERMES_PLUGINS__.register === "function") {
-    window.__HERMES_PLUGINS__.register("yaoyao", YaoyaoPage);
-  }
-})();

+ 0 - 934
hermes-plugins/yaoyao/dashboard/dist/index.v1.2.0.js

@@ -1,934 +0,0 @@
-/**
- * Yaoyao File Library - dashboard plugin frontend.
- *
- * Plain IIFE, no build step. Uses window.__HERMES_PLUGIN_SDK__ for React +
- * shadcn-ui primitives + fetchJSON / authedFetch. Backend routes live under
- * /api/plugins/yaoyao/ (auto-mounted by the dashboard plugin loader).
- */
-(function () {
-  "use strict";
-
-  const SDK = window.__HERMES_PLUGIN_SDK__;
-  if (!SDK) return;
-  const { React } = SDK;
-  const h = React.createElement;
-  const { useState, useEffect, useCallback, useRef, useMemo } = SDK.hooks;
-  const {
-    Card,
-    CardContent,
-    Badge,
-    Button,
-    Input,
-    Label,
-    Select,
-    SelectOption,
-  } = SDK.components;
-  const { cn, timeAgo } = SDK.utils;
-  const fetchJSON = SDK.fetchJSON;
-  const authedFetch = SDK.authedFetch;
-
-  const API = "/api/plugins/yaoyao";
-
-  // ---------------------------------------------------------------------
-  // Helpers
-  // ---------------------------------------------------------------------
-
-  function inferKind(name, mimeType) {
-    const ext = (name.split(".").pop() || "").toLowerCase();
-    if ((mimeType || "").startsWith("image/") ||
-        ["png","jpg","jpeg","gif","webp","bmp","svg","tiff","tif"].includes(ext))
-      return "image";
-    if ((mimeType || "").startsWith("video/") ||
-        ["mp4","mov","avi","mkv","webm","m4v","wmv","flv"].includes(ext))
-      return "video";
-    if ((mimeType || "").startsWith("text/") ||
-        ["txt","md","json","yaml","yml","csv","log","py","js","ts","html","xml","rst"].includes(ext))
-      return "text";
-    return "file";
-  }
-
-  function formatBytes(n) {
-    if (!n || n <= 0) return "0 B";
-    const units = ["B", "KB", "MB", "GB"];
-    let i = 0, v = n;
-    while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
-    return v >= 100 ? v.toFixed(0) + " " + units[i]
-         : v >= 10  ? v.toFixed(1) + " " + units[i]
-                    : v.toFixed(2) + " " + units[i];
-  }
-
-  function senderLabel(s) {
-    return s === "user" ? "用户" : s === "agent" ? "Agent" : s;
-  }
-
-  function kindIcon(kind) {
-    switch (kind) {
-      case "image": return "🖼";
-      case "video": return "🎬";
-      case "text": return "📄";
-      default: return "📦";
-    }
-  }
-
-  // ---------------------------------------------------------------------
-  // Thumbnail image: fetch as blob via authedFetch (img tags can't set
-  // Authorization headers), then create an object URL.
-  // ---------------------------------------------------------------------
-
-  function Thumbnail({ item, profile }) {
-    const [url, setUrl] = useState(null);
-    const [err, setErr] = useState(false);
-    const kind = inferKind(item.name, item.mimeType);
-
-    useEffect(() => {
-      if (kind !== "image") return;
-      let revoke = null;
-      let cancelled = false;
-      const dlUrl = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-      authedFetch(dlUrl)
-        .then((res) => res.blob())
-        .then((blob) => {
-          if (cancelled) return;
-          const u = URL.createObjectURL(blob);
-          revoke = u;
-          setUrl(u);
-        })
-        .catch(() => { if (!cancelled) setErr(true); });
-      return () => {
-        cancelled = true;
-        if (revoke) URL.revokeObjectURL(revoke);
-      };
-    }, [item.id, profile]);
-
-    if (kind !== "image") {
-      return h("div", {
-        className: "yaoyao-thumb yaoyao-thumb-icon",
-      }, kindIcon(kind));
-    }
-    if (err) return h("div", { className: "yaoyao-thumb yaoyao-thumb-icon" }, "🖼");
-    if (!url) return h("div", { className: "yaoyao-thumb yaoyao-thumb-loading" }, "…");
-    return h("img", {
-      src: url,
-      alt: item.name,
-      className: "yaoyao-thumb yaoyao-thumb-img",
-      loading: "lazy",
-    });
-  }
-
-  // ---------------------------------------------------------------------
-  // File card
-  // ---------------------------------------------------------------------
-
-  function FileCard({ item, onDownload, profile }) {
-    const kind = inferKind(item.name, item.mimeType);
-    return h(Card, { className: "yaoyao-card" },
-      h(CardContent, { className: "yaoyao-card-content" },
-        h("div", { className: "yaoyao-card-preview" },
-          h(Thumbnail, { item: item, profile: profile })
-        ),
-        h("div", { className: "yaoyao-card-info" },
-          h("div", { className: "yaoyao-card-name", title: item.name }, item.name),
-          h("div", { className: "yaoyao-card-meta" },
-            h(Badge, { variant: "secondary" }, senderLabel(item.origins && item.origins[0] ? item.origins[0].authorKind : "agent")),
-            h("span", { className: "yaoyao-card-size" }, formatBytes(item.size)),
-            item.messageTimestamp
-              ? h("span", { className: "yaoyao-card-time" }, timeAgo(item.messageTimestamp * 1000))
-              : null
-          ),
-          h("div", { className: "yaoyao-card-actions" },
-            h(Button, {
-              variant: "outline",
-              size: "sm",
-              onClick: () => onDownload(item),
-            }, "下载")
-          )
-        )
-      )
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Main page
-  // ---------------------------------------------------------------------
-
-  function YaoyaoFilesPage() {
-    const [items, setItems] = useState([]);
-    const [loading, setLoading] = useState(true);
-    const [loadingMore, setLoadingMore] = useState(false);
-    const [error, setError] = useState(null);
-    const [cursor, setCursor] = useState(null);
-    const [hasMore, setHasMore] = useState(false);
-    const [stats, setStats] = useState(null);
-    const [profiles, setProfiles] = useState([]);
-    // Initial profile from the URL (?profile=gril) so deep links / shared
-    // links land on the right agent's library; fall back to "default".
-    const [profile, setProfile] = useState(() => {
-      try {
-        const u = new URL(window.location.href);
-        const p = u.searchParams.get("profile");
-        return p || "default";
-      } catch (e) {
-        return "default";
-      }
-    });
-    const [filter, setFilter] = useState({ sender: "", kind: "" });
-    const [search, setSearch] = useState("");
-    const [searchInput, setSearchInput] = useState("");
-    const sentinelRef = useRef(null);
-
-    // Keep the URL ?profile= in sync with the dropdown selection so the
-    // address bar reflects what's shown (and is shareable / refreshable).
-    useEffect(() => {
-      try {
-        const u = new URL(window.location.href);
-        if (profile && profile !== "default") {
-          u.searchParams.set("profile", profile);
-        } else {
-          u.searchParams.delete("profile");
-        }
-        window.history.replaceState(null, "", u.toString());
-      } catch (e) { /* ignore */ }
-    }, [profile]);
-
-    // Also react to back/forward navigation so the dropdown follows the URL.
-    useEffect(() => {
-      const onPop = () => {
-        try {
-          const u = new URL(window.location.href);
-          const p = u.searchParams.get("profile") || "default";
-          setProfile(p);
-        } catch (e) { /* ignore */ }
-      };
-      window.addEventListener("popstate", onPop);
-      return () => window.removeEventListener("popstate", onPop);
-    }, []);
-
-    // Profiles dropdown: which agents have libraries. default always present.
-    useEffect(() => {
-      fetchJSON(`${API}/profiles`)
-        .then((res) => {
-          const list = (res.profiles || []);
-          setProfiles(list);
-          // If the current selection vanished (profile deleted), fall back.
-          if (list.length && !list.some((p) => p.name === profile)) {
-            setProfile("default");
-          }
-        })
-        .catch(() => {});
-    }, []); // eslint-disable-line
-
-    // Fetch first page whenever filter / search / profile changes.
-    const loadFirst = useCallback(async () => {
-      setLoading(true);
-      setError(null);
-      try {
-        const params = { limit: 50 };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems(res.items || []);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }, [filter, search, profile]);
-
-    useEffect(() => { loadFirst(); }, [loadFirst]);
-
-    // Stats (re-fetch when profile changes)
-    useEffect(() => {
-      const params = {};
-      if (profile) params.profile = profile;
-      const qs = new URLSearchParams(params).toString();
-      fetchJSON(`${API}/stats?${qs}`).then(setStats).catch(() => {});
-    }, [profile]);
-
-    // Load more
-    const loadMore = useCallback(async () => {
-      if (!cursor || loadingMore) return;
-      setLoadingMore(true);
-      try {
-        const params = { limit: 50, cursor };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems((prev) => [...prev, ...(res.items || [])]);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoadingMore(false);
-      }
-    }, [cursor, filter, search, profile, loadingMore]);
-
-    // Infinite scroll via IntersectionObserver
-    useEffect(() => {
-      const el = sentinelRef.current;
-      if (!el || !hasMore) return;
-      const obs = new IntersectionObserver((entries) => {
-        if (entries[0].isIntersecting) loadMore();
-      }, { rootMargin: "200px" });
-      obs.observe(el);
-      return () => obs.disconnect();
-    }, [hasMore, loadMore]);
-
-    const onDownload = useCallback(async (item) => {
-      try {
-        const url = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-        const res = await authedFetch(url);
-        const blob = await res.blob();
-        const urlObj = URL.createObjectURL(blob);
-        const a = document.createElement("a");
-        a.href = urlObj;
-        a.download = item.name;
-        document.body.appendChild(a);
-        a.click();
-        document.body.removeChild(a);
-        setTimeout(() => URL.revokeObjectURL(urlObj), 10000);
-      } catch (e) {
-        alert("下载失败: " + (e.message || e));
-      }
-    }, [profile]);
-
-    const onSearchSubmit = useCallback((e) => {
-      e.preventDefault();
-      setSearch(searchInput.trim());
-    }, [searchInput]);
-
-    return h("div", { className: "yaoyao-page" },
-      // Header + stats
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "夭夭文件库"),
-        stats ? h("div", { className: "yaoyao-stats" },
-          profile && profile !== "default"
-            ? h(Badge, { variant: "secondary" }, `Agent: ${profile}`)
-            : null,
-          h(Badge, { variant: "secondary" }, `共 ${stats.totalAttachments} 个文件`),
-          h(Badge, { variant: "secondary" }, `${formatBytes(stats.totalBytes)}`),
-          stats.bySender && stats.bySender.agent
-            ? h(Badge, { variant: "outline" }, `Agent ${stats.bySender.agent}`)
-            : null,
-          stats.bySender && stats.bySender.user
-            ? h(Badge, { variant: "outline" }, `用户 ${stats.bySender.user}`)
-            : null,
-        ) : null
-      ),
-
-      // Filters
-      h("div", { className: "yaoyao-filters" },
-        h(Label, null, "Agent"),
-        h(Select, {
-          value: profile,
-          onChange: (e) => setProfile(e.target.value),
-          disabled: profiles.length === 0,
-        },
-          profiles.length === 0
-            ? h(SelectOption, { value: "default" }, "默认")
-            : profiles.map((p) =>
-                h(SelectOption, { key: p.name, value: p.name }, p.label)
-              )
-        ),
-        h(Label, null, "来源"),
-        h(Select, {
-          value: filter.sender,
-          onChange: (e) => setFilter((f) => ({ ...f, sender: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "agent" }, "Agent"),
-          h(SelectOption, { value: "user" }, "用户")
-        ),
-        h(Label, null, "类型"),
-        h(Select, {
-          value: filter.kind,
-          onChange: (e) => setFilter((f) => ({ ...f, kind: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "image" }, "图片"),
-          h(SelectOption, { value: "video" }, "视频"),
-          h(SelectOption, { value: "text" }, "文本"),
-          h(SelectOption, { value: "file" }, "文档")
-        ),
-        h("form", { onSubmit: onSearchSubmit, className: "yaoyao-search" },
-          h(Input, {
-            type: "text",
-            placeholder: "搜索文件名…",
-            value: searchInput,
-            onChange: (e) => setSearchInput(e.target.value),
-          }),
-          h(Button, { type: "submit", size: "sm" }, "搜索")
-        )
-      ),
-
-      // Error
-      error ? h("div", { className: "yaoyao-error" }, "错误: " + error) : null,
-
-      // Loading
-      loading ? h("div", { className: "yaoyao-loading" }, "加载中…") :
-      // Grid
-      items.length === 0
-        ? h("div", { className: "yaoyao-empty" }, "暂无文件")
-        : h("div", { className: "yaoyao-grid" },
-            items.map((item) =>
-              h(FileCard, { key: item.id, item: item, onDownload: onDownload, profile: profile })
-            )
-          ),
-
-      // Infinite scroll sentinel
-      hasMore ? h("div", {
-        ref: sentinelRef,
-        className: "yaoyao-sentinel"
-      }, loadingMore ? "加载更多…" : "") : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Voice settings page
-  // ---------------------------------------------------------------------
-
-  // ---------------------------------------------------------------------
-  // Duplex voice settings page
-  // Mirrors yaoyao-webui's IosDuplexVoiceSettings.vue contract:
-  // {hasApiKey, voices:[{id,name}], currentVoiceId, updatedAt}
-  // ---------------------------------------------------------------------
-
-  function VoiceSettingsPage() {
-    const [settings, setSettings] = useState(null);
-    const [loading, setLoading] = useState(true);
-    const [saving, setSaving] = useState(false);
-    const [switching, setSwitching] = useState(false);
-    const [error, setError] = useState(null);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    // Draft state for the editor
-    const [draftApiKey, setDraftApiKey] = useState("");
-    const [draftVoices, setDraftVoices] = useState([]);
-    const [draftCurrent, setDraftCurrent] = useState("");
-    const [editing, setEditing] = useState(false);
-
-    useEffect(() => {
-      load();
-    }, []);
-
-    async function load() {
-      setLoading(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/settings`);
-        setSettings(s);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }
-
-    const voiceOptions = useMemo(() => {
-      if (!settings) return [];
-      return settings.voices
-        .filter((v) => v.id.trim() && v.name.trim())
-        .map((v) => ({ label: v.name, value: v.id }));
-    }, [settings]);
-
-    const isConfigured = settings
-      && settings.hasApiKey
-      && voiceOptions.length > 0
-      && voiceOptions.some((o) => o.value === settings.currentVoiceId);
-
-    function openEditor() {
-      setDraftApiKey("");
-      setDraftVoices((settings?.voices || []).map((v) => ({ ...v })));
-      setDraftCurrent(settings?.currentVoiceId || "");
-      setEditing(true);
-    }
-
-    function addVoice() {
-      setDraftVoices((prev) => [...prev, { id: "", name: "" }]);
-    }
-
-    function removeVoice(idx) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        const removed = next[idx];
-        next.splice(idx, 1);
-        if (removed?.id === draftCurrent) {
-          setDraftCurrent(next[0]?.id || "");
-        }
-        return next;
-      });
-    }
-
-    function updateVoice(idx, field, value) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        next[idx] = { ...next[idx], [field]: value };
-        return next;
-      });
-    }
-
-    async function saveSettings() {
-      setSaving(true);
-      setError(null);
-      try {
-        const body = {
-          voices: draftVoices.map((v) => ({ id: v.id.trim(), name: v.name.trim() })),
-          currentVoiceId: draftCurrent,
-        };
-        if (draftApiKey.trim()) body.apiKey = draftApiKey.trim();
-        const s = await fetchJSON(`${API}/voice/settings`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify(body),
-        });
-        setSettings(s);
-        setEditing(false);
-        setSavedMsg("已保存");
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function switchVoice(voiceId) {
-      if (switching || voiceId === settings.currentVoiceId) return;
-      setSwitching(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/current-voice`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify({ currentVoiceId: voiceId }),
-        });
-        setSettings((prev) => ({ ...prev, ...s }));
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSwitching(false);
-      }
-    }
-
-    if (loading) return h("div", { className: "yaoyao-loading" }, "加载中…");
-    if (!settings) return h("div", { className: "yaoyao-error" }, "加载失败: " + error);
-
-    const currentVoiceName = voiceOptions.find((o) => o.value === settings.currentVoiceId)?.label
-      || settings.currentVoiceId
-      || "未选择";
-
-    return h("div", { className: "yaoyao-page" },
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "App 双流直连配置"),
-        savedMsg ? h(Badge, { variant: "secondary" }, savedMsg) : null
-      ),
-
-      // Status card
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-duplex-status" },
-            h("div", { className: "yaoyao-duplex-icon" }, "D"),
-            h("div", { className: "yaoyao-duplex-info" },
-              h("div", { className: "yaoyao-duplex-title-row" },
-                h("h5", null, "火山引擎 / 豆包 TTS"),
-                h(Badge, {
-                  variant: isConfigured ? "default" : "secondary",
-                }, isConfigured ? "已配置" : "未配置")
-              ),
-              h("p", { className: "yaoyao-hint" },
-                "iOS App 直连 TTS 引擎进行双流语音对话。API Key 和声音列表在此配置后,App 从 /voice/runtime 拉取。")
-            )
-          ),
-          h("div", { className: "yaoyao-duplex-meta" },
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "当前声音"), h("span", null, currentVoiceName)),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "API Key"), h("span", null, settings.hasApiKey ? "已存储" : "未设置")),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "声音数量"), h("span", null, String(settings.voices.length))),
-          )
-        )
-      ),
-
-      // Current voice quick switch
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-current" }, "当前声音"),
-            h("div", { className: "yaoyao-voice-switch" },
-              h(Select, {
-                id: "duplex-current",
-                value: settings.currentVoiceId,
-                onChange: (e) => switchVoice(e.target.value),
-                disabled: switching || voiceOptions.length === 0,
-              },
-                voiceOptions.map((o) =>
-                  h(SelectOption, { key: o.value, value: o.value }, o.label)
-                )
-              ),
-              h(Button, {
-                variant: "outline",
-                size: "sm",
-                onClick: openEditor,
-              }, "编辑配置")
-            )
-          )
-        )
-      ),
-
-      error ? h("div", { className: "yaoyao-error" }, error) : null,
-
-      // Editor (inline form)
-      editing ? h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("h3", { className: "yaoyao-section-title" }, "编辑双流配置"),
-
-          // API Key
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-key" }, "API Key"),
-            h(Input, {
-              id: "duplex-key",
-              type: "password",
-              value: draftApiKey,
-              placeholder: settings.hasApiKey ? "已存储 (留空保持不变)" : "输入 API Key",
-              onChange: (e) => setDraftApiKey(e.target.value),
-            })
-          ),
-
-          // Current voice in draft
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-draft-current" }, "当前声音"),
-            h(Select, {
-              id: "duplex-draft-current",
-              value: draftCurrent,
-              onChange: (e) => setDraftCurrent(e.target.value),
-            },
-              draftVoices
-                .filter((v) => v.id.trim())
-                .map((v) =>
-                  h(SelectOption, { key: v.id, value: v.id }, v.name || v.id)
-                )
-            )
-          ),
-
-          // Voice list editor
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, null, "声音列表"),
-            h("div", { className: "yaoyao-voice-editor" },
-              draftVoices.map((voice, idx) =>
-                h("div", { key: idx, className: "yaoyao-voice-editor-row" },
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音名称 (如 小何 2.0)",
-                    value: voice.name,
-                    onChange: (e) => updateVoice(idx, "name", e.target.value),
-                  }),
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音 ID (如 zh_female_xiaohe_uranus_bigtts)",
-                    value: voice.id,
-                    onChange: (e) => updateVoice(idx, "id", e.target.value),
-                  }),
-                  h(Button, {
-                    variant: "ghost",
-                    size: "sm",
-                    disabled: draftVoices.length <= 1,
-                    onClick: () => removeVoice(idx),
-                  }, "×")
-                )
-              ),
-              h(Button, { variant: "outline", size: "sm", onClick: addVoice }, "+ 添加声音")
-            )
-          ),
-
-          h("div", { className: "yaoyao-voice-actions" },
-            h(Button, { variant: "ghost", onClick: () => setEditing(false) }, "取消"),
-            h(Button, { onClick: saveSettings, disabled: saving }, saving ? "保存中…" : "保存")
-          )
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // TTS / STT provider settings page
-  // Mirrors yaoyao-webui's VoiceSettings.vue + VoiceApiConfigurator.vue.
-  // ---------------------------------------------------------------------
-
-  function VoiceProvidersPage() {
-    const [ttsData, setTtsData] = useState(null);
-    const [sttData, setSttData] = useState(null);
-    const [providersInfo, setProvidersInfo] = useState(null);
-    const [error, setError] = useState(null);
-    const [saving, setSaving] = useState(false);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    useEffect(() => {
-      Promise.all([
-        fetchJSON(`${API}/tts/settings`),
-        fetchJSON(`${API}/stt/settings`),
-        fetchJSON(`${API}/voice/providers-info`),
-      ]).then(([t, s, p]) => {
-        setTtsData(t);
-        setSttData(s);
-        setProvidersInfo(p);
-      }).catch((e) => setError(String(e.message || e)));
-    }, []);
-
-    async function setTtsActive(provider) {
-      try {
-        await fetchJSON(`${API}/tts/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setTtsData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function setSttActive(provider) {
-      try {
-        await fetchJSON(`${API}/stt/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setSttData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function saveProvider(kind, provider, settings, secrets) {
-      setSaving(true);
-      setError(null);
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        const res = await fetchJSON(endpoint, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({settings, secrets}),
-        });
-        // Refresh
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-        setSavedMsg(`${provider} 已保存`);
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function deleteProvider(kind, provider) {
-      if (!confirm(`确定删除 ${provider} 配置?`)) return;
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        await fetchJSON(endpoint, {method: "DELETE"});
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    if (!ttsData || !sttData || !providersInfo) {
-      return h("div", {className: "yaoyao-loading"}, "加载中…");
-    }
-
-    const ttsProviders = providersInfo.tts.providers;
-    const sttProviders = providersInfo.stt.providers;
-
-    function renderProviderCard(kind, info, data) {
-      const settings = (data.settings || []).find(s => s.provider === info.id);
-      const isActive = data.activeProvider === info.id;
-      const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-      const isConfigured = info.id === "edge" || info.id === "browser" || hasKey;
-
-      return h(Card, {key: info.id, className: cn("yaoyao-provider-card", isActive && "yaoyao-provider-active")},
-        h(CardContent, {className: "yaoyao-voice-card"},
-          h("div", {className: "yaoyao-provider-header"},
-            h("div", {className: "yaoyao-provider-title-row"},
-              h("h5", null, info.label),
-              h(Badge, {variant: isActive ? "default" : "secondary"},
-                isActive ? "当前" : (isConfigured ? "已配置" : "未配置"))
-            ),
-            h("p", {className: "yaoyao-hint"},
-              info.needsKey ? "需要 API Key" : "免费 / 内置")
-          ),
-          h(ProviderEditor, {
-            kind, info, settings: settings || null, saving,
-            onSave: (s, sec) => saveProvider(kind, info.id, s, sec),
-            onDelete: info.id !== "edge" && info.id !== "browser"
-              ? () => deleteProvider(kind, info.id) : null,
-            onActivate: () => kind === "tts" ? setTtsActive(info.id) : setSttActive(info.id),
-          })
-        )
-      );
-    }
-
-    return h("div", {className: "yaoyao-page"},
-      h("div", {className: "yaoyao-header"},
-        h("h2", null, "语音引擎配置"),
-        savedMsg ? h(Badge, {variant: "secondary"}, savedMsg) : null
-      ),
-      error ? h("div", {className: "yaoyao-error"}, error) : null,
-
-      h("h3", {className: "yaoyao-section-title"}, "TTS (文字转语音)"),
-      h("div", {className: "yaoyao-provider-list"},
-        ttsProviders.map(info => renderProviderCard("tts", info, ttsData))
-      ),
-
-      h("h3", {className: "yaoyao-section-title"}, "STT (语音转文字)"),
-      h("div", {className: "yaoyao-provider-list"},
-        sttProviders.map(info => renderProviderCard("stt", info, sttData))
-      )
-    );
-  }
-
-  // Inline provider editor (expandable)
-  function ProviderEditor({kind, info, settings, saving, onSave, onDelete, onActivate}) {
-    const [expanded, setExpanded] = useState(false);
-    const [draft, setDraft] = useState({});
-
-    useEffect(() => {
-      if (settings) {
-        setDraft({
-          baseUrl: settings.settings?.baseUrl || info.defaults?.baseUrl || "",
-          model: settings.settings?.model || info.defaults?.model || "",
-          voice: settings.settings?.voice || info.defaults?.voice || "",
-          language: settings.settings?.language || info.defaults?.language || "",
-          rate: settings.settings?.rate || "",
-          pitch: settings.settings?.pitch || "",
-          stylePrompt: settings.settings?.stylePrompt || "",
-          apiKey: "",
-        });
-      } else {
-        setDraft({
-          baseUrl: info.defaults?.baseUrl || "",
-          model: info.defaults?.model || "",
-          voice: info.defaults?.voice || "",
-          language: info.defaults?.language || "",
-          apiKey: "",
-        });
-      }
-    }, [info.id, settings]);
-
-    function update(field, value) {
-      setDraft(d => ({...d, [field]: value}));
-    }
-
-    function handleSave() {
-      const s = {};
-      const sec = {};
-      if (draft.baseUrl) s.baseUrl = draft.baseUrl;
-      if (draft.model) s.model = draft.model;
-      if (draft.voice) s.voice = draft.voice;
-      if (draft.language) s.language = draft.language;
-      if (draft.rate) s.rate = draft.rate;
-      if (draft.pitch) s.pitch = draft.pitch;
-      if (draft.stylePrompt) s.stylePrompt = draft.stylePrompt;
-      if (draft.apiKey) sec.apiKey = draft.apiKey;
-      onSave(s, sec);
-    }
-
-    const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-    const showFields = info.settingsKeys || [];
-
-    return h("div", {className: "yaoyao-provider-editor"},
-      h("div", {className: "yaoyao-provider-actions"},
-        h(Button, {variant: "outline", size: "sm", onClick: () => setExpanded(e => !e)},
-          expanded ? "收起" : "展开"),
-        onActivate ? h(Button, {variant: "ghost", size: "sm", onClick: onActivate}, "设为当前") : null,
-      ),
-      expanded ? h("div", {className: "yaoyao-provider-fields"},
-        showFields.includes("baseUrl") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "Base URL"),
-          h(Input, {type: "text", value: draft.baseUrl, onChange: e => update("baseUrl", e.target.value),
-            placeholder: "https://..."})
-        ) : null,
-        showFields.includes("model") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "模型"),
-          h(Input, {type: "text", value: draft.model, onChange: e => update("model", e.target.value),
-            placeholder: "model id"})
-        ) : null,
-        showFields.includes("voice") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "声音"),
-          h(Input, {type: "text", value: draft.voice, onChange: e => update("voice", e.target.value),
-            placeholder: "voice id"})
-        ) : null,
-        showFields.includes("language") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语言"),
-          h(Input, {type: "text", value: draft.language, onChange: e => update("language", e.target.value),
-            placeholder: "zh / en / ..."})
-        ) : null,
-        showFields.includes("rate") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语速"),
-          h(Input, {type: "text", value: draft.rate, onChange: e => update("rate", e.target.value),
-            placeholder: "+0%"})
-        ) : null,
-        showFields.includes("pitch") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "音调"),
-          h(Input, {type: "text", value: draft.pitch, onChange: e => update("pitch", e.target.value),
-            placeholder: "+0Hz"})
-        ) : null,
-        showFields.includes("stylePrompt") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "风格提示"),
-          h(Input, {type: "text", value: draft.stylePrompt, onChange: e => update("stylePrompt", e.target.value),
-            placeholder: "style prompt"})
-        ) : null,
-        info.needsKey ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "API Key"),
-          h(Input, {type: "password", value: draft.apiKey,
-            onChange: e => update("apiKey", e.target.value),
-            placeholder: hasKey ? "已存储 (留空保持不变)" : "输入 API Key"})
-        ) : null,
-        h("div", {className: "yaoyao-voice-actions"},
-          h(Button, {size: "sm", onClick: handleSave, disabled: saving},
-            saving ? "保存中…" : "保存"),
-          onDelete ? h(Button, {variant: "ghost", size: "sm", onClick: onDelete}, "删除") : null,
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Top-level page with internal tab switcher (Files / Duplex / Engines)
-  // ---------------------------------------------------------------------
-
-  function YaoyaoPage() {
-    const [tab, setTab] = useState("files");
-    return h("div", { className: "yaoyao-root" },
-      h("div", { className: "yaoyao-tabs" },
-        h("button", {
-          className: cn("yaoyao-tab", tab === "files" && "yaoyao-tab-active"),
-          onClick: () => setTab("files"),
-        }, "文件库"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "duplex" && "yaoyao-tab-active"),
-          onClick: () => setTab("duplex"),
-        }, "App双流直连"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "engines" && "yaoyao-tab-active"),
-          onClick: () => setTab("engines"),
-        }, "语音引擎")
-      ),
-      tab === "files" ? h(YaoyaoFilesPage)
-      : tab === "duplex" ? h(VoiceSettingsPage)
-      : h(VoiceProvidersPage)
-    );
-  }
-
-  // Register the plugin page. The name MUST match manifest.json "name".
-  if (window.__HERMES_PLUGINS__ &&
-      typeof window.__HERMES_PLUGINS__.register === "function") {
-    window.__HERMES_PLUGINS__.register("yaoyao", YaoyaoPage);
-  }
-})();

+ 0 - 934
hermes-plugins/yaoyao/dashboard/dist/index.v1.3.0.js

@@ -1,934 +0,0 @@
-/**
- * Yaoyao File Library - dashboard plugin frontend.
- *
- * Plain IIFE, no build step. Uses window.__HERMES_PLUGIN_SDK__ for React +
- * shadcn-ui primitives + fetchJSON / authedFetch. Backend routes live under
- * /api/plugins/yaoyao/ (auto-mounted by the dashboard plugin loader).
- */
-(function () {
-  "use strict";
-
-  const SDK = window.__HERMES_PLUGIN_SDK__;
-  if (!SDK) return;
-  const { React } = SDK;
-  const h = React.createElement;
-  const { useState, useEffect, useCallback, useRef, useMemo } = SDK.hooks;
-  const {
-    Card,
-    CardContent,
-    Badge,
-    Button,
-    Input,
-    Label,
-    Select,
-    SelectOption,
-  } = SDK.components;
-  const { cn, timeAgo } = SDK.utils;
-  const fetchJSON = SDK.fetchJSON;
-  const authedFetch = SDK.authedFetch;
-
-  const API = "/api/plugins/yaoyao";
-
-  // ---------------------------------------------------------------------
-  // Helpers
-  // ---------------------------------------------------------------------
-
-  function inferKind(name, mimeType) {
-    const ext = (name.split(".").pop() || "").toLowerCase();
-    if ((mimeType || "").startsWith("image/") ||
-        ["png","jpg","jpeg","gif","webp","bmp","svg","tiff","tif"].includes(ext))
-      return "image";
-    if ((mimeType || "").startsWith("video/") ||
-        ["mp4","mov","avi","mkv","webm","m4v","wmv","flv"].includes(ext))
-      return "video";
-    if ((mimeType || "").startsWith("text/") ||
-        ["txt","md","json","yaml","yml","csv","log","py","js","ts","html","xml","rst"].includes(ext))
-      return "text";
-    return "file";
-  }
-
-  function formatBytes(n) {
-    if (!n || n <= 0) return "0 B";
-    const units = ["B", "KB", "MB", "GB"];
-    let i = 0, v = n;
-    while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
-    return v >= 100 ? v.toFixed(0) + " " + units[i]
-         : v >= 10  ? v.toFixed(1) + " " + units[i]
-                    : v.toFixed(2) + " " + units[i];
-  }
-
-  function senderLabel(s) {
-    return s === "user" ? "用户" : s === "agent" ? "Agent" : s;
-  }
-
-  function kindIcon(kind) {
-    switch (kind) {
-      case "image": return "🖼";
-      case "video": return "🎬";
-      case "text": return "📄";
-      default: return "📦";
-    }
-  }
-
-  // ---------------------------------------------------------------------
-  // Thumbnail image: fetch as blob via authedFetch (img tags can't set
-  // Authorization headers), then create an object URL.
-  // ---------------------------------------------------------------------
-
-  function Thumbnail({ item, profile }) {
-    const [url, setUrl] = useState(null);
-    const [err, setErr] = useState(false);
-    const kind = inferKind(item.name, item.mimeType);
-
-    useEffect(() => {
-      if (kind !== "image") return;
-      let revoke = null;
-      let cancelled = false;
-      const dlUrl = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-      authedFetch(dlUrl)
-        .then((res) => res.blob())
-        .then((blob) => {
-          if (cancelled) return;
-          const u = URL.createObjectURL(blob);
-          revoke = u;
-          setUrl(u);
-        })
-        .catch(() => { if (!cancelled) setErr(true); });
-      return () => {
-        cancelled = true;
-        if (revoke) URL.revokeObjectURL(revoke);
-      };
-    }, [item.id, profile]);
-
-    if (kind !== "image") {
-      return h("div", {
-        className: "yaoyao-thumb yaoyao-thumb-icon",
-      }, kindIcon(kind));
-    }
-    if (err) return h("div", { className: "yaoyao-thumb yaoyao-thumb-icon" }, "🖼");
-    if (!url) return h("div", { className: "yaoyao-thumb yaoyao-thumb-loading" }, "…");
-    return h("img", {
-      src: url,
-      alt: item.name,
-      className: "yaoyao-thumb yaoyao-thumb-img",
-      loading: "lazy",
-    });
-  }
-
-  // ---------------------------------------------------------------------
-  // File card
-  // ---------------------------------------------------------------------
-
-  function FileCard({ item, onDownload, profile }) {
-    const kind = inferKind(item.name, item.mimeType);
-    return h(Card, { className: "yaoyao-card" },
-      h(CardContent, { className: "yaoyao-card-content" },
-        h("div", { className: "yaoyao-card-preview" },
-          h(Thumbnail, { item: item, profile: profile })
-        ),
-        h("div", { className: "yaoyao-card-info" },
-          h("div", { className: "yaoyao-card-name", title: item.name }, item.name),
-          h("div", { className: "yaoyao-card-meta" },
-            h(Badge, { variant: "secondary" }, senderLabel(item.origins && item.origins[0] ? item.origins[0].authorKind : "agent")),
-            h("span", { className: "yaoyao-card-size" }, formatBytes(item.size)),
-            item.messageTimestamp
-              ? h("span", { className: "yaoyao-card-time" }, timeAgo(item.messageTimestamp * 1000))
-              : null
-          ),
-          h("div", { className: "yaoyao-card-actions" },
-            h(Button, {
-              variant: "outline",
-              size: "sm",
-              onClick: () => onDownload(item),
-            }, "下载")
-          )
-        )
-      )
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Main page
-  // ---------------------------------------------------------------------
-
-  function YaoyaoFilesPage() {
-    const [items, setItems] = useState([]);
-    const [loading, setLoading] = useState(true);
-    const [loadingMore, setLoadingMore] = useState(false);
-    const [error, setError] = useState(null);
-    const [cursor, setCursor] = useState(null);
-    const [hasMore, setHasMore] = useState(false);
-    const [stats, setStats] = useState(null);
-    const [profiles, setProfiles] = useState([]);
-    // Initial profile from the URL (?profile=gril) so deep links / shared
-    // links land on the right agent's library; fall back to "default".
-    const [profile, setProfile] = useState(() => {
-      try {
-        const u = new URL(window.location.href);
-        const p = u.searchParams.get("profile");
-        return p || "default";
-      } catch (e) {
-        return "default";
-      }
-    });
-    const [filter, setFilter] = useState({ sender: "", kind: "" });
-    const [search, setSearch] = useState("");
-    const [searchInput, setSearchInput] = useState("");
-    const sentinelRef = useRef(null);
-
-    // Keep the URL ?profile= in sync with the dropdown selection so the
-    // address bar reflects what's shown (and is shareable / refreshable).
-    useEffect(() => {
-      try {
-        const u = new URL(window.location.href);
-        if (profile && profile !== "default") {
-          u.searchParams.set("profile", profile);
-        } else {
-          u.searchParams.delete("profile");
-        }
-        window.history.replaceState(null, "", u.toString());
-      } catch (e) { /* ignore */ }
-    }, [profile]);
-
-    // Also react to back/forward navigation so the dropdown follows the URL.
-    useEffect(() => {
-      const onPop = () => {
-        try {
-          const u = new URL(window.location.href);
-          const p = u.searchParams.get("profile") || "default";
-          setProfile(p);
-        } catch (e) { /* ignore */ }
-      };
-      window.addEventListener("popstate", onPop);
-      return () => window.removeEventListener("popstate", onPop);
-    }, []);
-
-    // Profiles dropdown: which agents have libraries. default always present.
-    useEffect(() => {
-      fetchJSON(`${API}/profiles`)
-        .then((res) => {
-          const list = (res.profiles || []);
-          setProfiles(list);
-          // If the current selection vanished (profile deleted), fall back.
-          if (list.length && !list.some((p) => p.name === profile)) {
-            setProfile("default");
-          }
-        })
-        .catch(() => {});
-    }, []); // eslint-disable-line
-
-    // Fetch first page whenever filter / search / profile changes.
-    const loadFirst = useCallback(async () => {
-      setLoading(true);
-      setError(null);
-      try {
-        const params = { limit: 50 };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems(res.items || []);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }, [filter, search, profile]);
-
-    useEffect(() => { loadFirst(); }, [loadFirst]);
-
-    // Stats (re-fetch when profile changes)
-    useEffect(() => {
-      const params = {};
-      if (profile) params.profile = profile;
-      const qs = new URLSearchParams(params).toString();
-      fetchJSON(`${API}/stats?${qs}`).then(setStats).catch(() => {});
-    }, [profile]);
-
-    // Load more
-    const loadMore = useCallback(async () => {
-      if (!cursor || loadingMore) return;
-      setLoadingMore(true);
-      try {
-        const params = { limit: 50, cursor };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems((prev) => [...prev, ...(res.items || [])]);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoadingMore(false);
-      }
-    }, [cursor, filter, search, profile, loadingMore]);
-
-    // Infinite scroll via IntersectionObserver
-    useEffect(() => {
-      const el = sentinelRef.current;
-      if (!el || !hasMore) return;
-      const obs = new IntersectionObserver((entries) => {
-        if (entries[0].isIntersecting) loadMore();
-      }, { rootMargin: "200px" });
-      obs.observe(el);
-      return () => obs.disconnect();
-    }, [hasMore, loadMore]);
-
-    const onDownload = useCallback(async (item) => {
-      try {
-        const url = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-        const res = await authedFetch(url);
-        const blob = await res.blob();
-        const urlObj = URL.createObjectURL(blob);
-        const a = document.createElement("a");
-        a.href = urlObj;
-        a.download = item.name;
-        document.body.appendChild(a);
-        a.click();
-        document.body.removeChild(a);
-        setTimeout(() => URL.revokeObjectURL(urlObj), 10000);
-      } catch (e) {
-        alert("下载失败: " + (e.message || e));
-      }
-    }, [profile]);
-
-    const onSearchSubmit = useCallback((e) => {
-      e.preventDefault();
-      setSearch(searchInput.trim());
-    }, [searchInput]);
-
-    return h("div", { className: "yaoyao-page" },
-      // Header + stats
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "夭夭文件库"),
-        stats ? h("div", { className: "yaoyao-stats" },
-          profile && profile !== "default"
-            ? h(Badge, { variant: "secondary" }, `Agent: ${profile}`)
-            : null,
-          h(Badge, { variant: "secondary" }, `共 ${stats.totalAttachments} 个文件`),
-          h(Badge, { variant: "secondary" }, `${formatBytes(stats.totalBytes)}`),
-          stats.bySender && stats.bySender.agent
-            ? h(Badge, { variant: "outline" }, `Agent ${stats.bySender.agent}`)
-            : null,
-          stats.bySender && stats.bySender.user
-            ? h(Badge, { variant: "outline" }, `用户 ${stats.bySender.user}`)
-            : null,
-        ) : null
-      ),
-
-      // Filters
-      h("div", { className: "yaoyao-filters" },
-        h(Label, null, "Agent"),
-        h(Select, {
-          value: profile,
-          onChange: (e) => setProfile(e.target.value),
-          disabled: profiles.length === 0,
-        },
-          profiles.length === 0
-            ? h(SelectOption, { value: "default" }, "默认")
-            : profiles.map((p) =>
-                h(SelectOption, { key: p.name, value: p.name }, p.label)
-              )
-        ),
-        h(Label, null, "来源"),
-        h(Select, {
-          value: filter.sender,
-          onChange: (e) => setFilter((f) => ({ ...f, sender: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "agent" }, "Agent"),
-          h(SelectOption, { value: "user" }, "用户")
-        ),
-        h(Label, null, "类型"),
-        h(Select, {
-          value: filter.kind,
-          onChange: (e) => setFilter((f) => ({ ...f, kind: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "image" }, "图片"),
-          h(SelectOption, { value: "video" }, "视频"),
-          h(SelectOption, { value: "text" }, "文本"),
-          h(SelectOption, { value: "file" }, "文档")
-        ),
-        h("form", { onSubmit: onSearchSubmit, className: "yaoyao-search" },
-          h(Input, {
-            type: "text",
-            placeholder: "搜索文件名…",
-            value: searchInput,
-            onChange: (e) => setSearchInput(e.target.value),
-          }),
-          h(Button, { type: "submit", size: "sm" }, "搜索")
-        )
-      ),
-
-      // Error
-      error ? h("div", { className: "yaoyao-error" }, "错误: " + error) : null,
-
-      // Loading
-      loading ? h("div", { className: "yaoyao-loading" }, "加载中…") :
-      // Grid
-      items.length === 0
-        ? h("div", { className: "yaoyao-empty" }, "暂无文件")
-        : h("div", { className: "yaoyao-grid" },
-            items.map((item) =>
-              h(FileCard, { key: item.id, item: item, onDownload: onDownload, profile: profile })
-            )
-          ),
-
-      // Infinite scroll sentinel
-      hasMore ? h("div", {
-        ref: sentinelRef,
-        className: "yaoyao-sentinel"
-      }, loadingMore ? "加载更多…" : "") : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Voice settings page
-  // ---------------------------------------------------------------------
-
-  // ---------------------------------------------------------------------
-  // Duplex voice settings page
-  // Mirrors yaoyao-webui's IosDuplexVoiceSettings.vue contract:
-  // {hasApiKey, voices:[{id,name}], currentVoiceId, updatedAt}
-  // ---------------------------------------------------------------------
-
-  function VoiceSettingsPage() {
-    const [settings, setSettings] = useState(null);
-    const [loading, setLoading] = useState(true);
-    const [saving, setSaving] = useState(false);
-    const [switching, setSwitching] = useState(false);
-    const [error, setError] = useState(null);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    // Draft state for the editor
-    const [draftApiKey, setDraftApiKey] = useState("");
-    const [draftVoices, setDraftVoices] = useState([]);
-    const [draftCurrent, setDraftCurrent] = useState("");
-    const [editing, setEditing] = useState(false);
-
-    useEffect(() => {
-      load();
-    }, []);
-
-    async function load() {
-      setLoading(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/settings`);
-        setSettings(s);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }
-
-    const voiceOptions = useMemo(() => {
-      if (!settings) return [];
-      return settings.voices
-        .filter((v) => v.id.trim() && v.name.trim())
-        .map((v) => ({ label: v.name, value: v.id }));
-    }, [settings]);
-
-    const isConfigured = settings
-      && settings.hasApiKey
-      && voiceOptions.length > 0
-      && voiceOptions.some((o) => o.value === settings.currentVoiceId);
-
-    function openEditor() {
-      setDraftApiKey("");
-      setDraftVoices((settings?.voices || []).map((v) => ({ ...v })));
-      setDraftCurrent(settings?.currentVoiceId || "");
-      setEditing(true);
-    }
-
-    function addVoice() {
-      setDraftVoices((prev) => [...prev, { id: "", name: "" }]);
-    }
-
-    function removeVoice(idx) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        const removed = next[idx];
-        next.splice(idx, 1);
-        if (removed?.id === draftCurrent) {
-          setDraftCurrent(next[0]?.id || "");
-        }
-        return next;
-      });
-    }
-
-    function updateVoice(idx, field, value) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        next[idx] = { ...next[idx], [field]: value };
-        return next;
-      });
-    }
-
-    async function saveSettings() {
-      setSaving(true);
-      setError(null);
-      try {
-        const body = {
-          voices: draftVoices.map((v) => ({ id: v.id.trim(), name: v.name.trim() })),
-          currentVoiceId: draftCurrent,
-        };
-        if (draftApiKey.trim()) body.apiKey = draftApiKey.trim();
-        const s = await fetchJSON(`${API}/voice/settings`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify(body),
-        });
-        setSettings(s);
-        setEditing(false);
-        setSavedMsg("已保存");
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function switchVoice(voiceId) {
-      if (switching || voiceId === settings.currentVoiceId) return;
-      setSwitching(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/current-voice`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify({ currentVoiceId: voiceId }),
-        });
-        setSettings((prev) => ({ ...prev, ...s }));
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSwitching(false);
-      }
-    }
-
-    if (loading) return h("div", { className: "yaoyao-loading" }, "加载中…");
-    if (!settings) return h("div", { className: "yaoyao-error" }, "加载失败: " + error);
-
-    const currentVoiceName = voiceOptions.find((o) => o.value === settings.currentVoiceId)?.label
-      || settings.currentVoiceId
-      || "未选择";
-
-    return h("div", { className: "yaoyao-page" },
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "App 双流直连配置"),
-        savedMsg ? h(Badge, { variant: "secondary" }, savedMsg) : null
-      ),
-
-      // Status card
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-duplex-status" },
-            h("div", { className: "yaoyao-duplex-icon" }, "D"),
-            h("div", { className: "yaoyao-duplex-info" },
-              h("div", { className: "yaoyao-duplex-title-row" },
-                h("h5", null, "火山引擎 / 豆包 TTS"),
-                h(Badge, {
-                  variant: isConfigured ? "default" : "secondary",
-                }, isConfigured ? "已配置" : "未配置")
-              ),
-              h("p", { className: "yaoyao-hint" },
-                "iOS App 直连 TTS 引擎进行双流语音对话。API Key 和声音列表在此配置后,App 从 /voice/runtime 拉取。")
-            )
-          ),
-          h("div", { className: "yaoyao-duplex-meta" },
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "当前声音"), h("span", null, currentVoiceName)),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "API Key"), h("span", null, settings.hasApiKey ? "已存储" : "未设置")),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "声音数量"), h("span", null, String(settings.voices.length))),
-          )
-        )
-      ),
-
-      // Current voice quick switch
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-current" }, "当前声音"),
-            h("div", { className: "yaoyao-voice-switch" },
-              h(Select, {
-                id: "duplex-current",
-                value: settings.currentVoiceId,
-                onChange: (e) => switchVoice(e.target.value),
-                disabled: switching || voiceOptions.length === 0,
-              },
-                voiceOptions.map((o) =>
-                  h(SelectOption, { key: o.value, value: o.value }, o.label)
-                )
-              ),
-              h(Button, {
-                variant: "outline",
-                size: "sm",
-                onClick: openEditor,
-              }, "编辑配置")
-            )
-          )
-        )
-      ),
-
-      error ? h("div", { className: "yaoyao-error" }, error) : null,
-
-      // Editor (inline form)
-      editing ? h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("h3", { className: "yaoyao-section-title" }, "编辑双流配置"),
-
-          // API Key
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-key" }, "API Key"),
-            h(Input, {
-              id: "duplex-key",
-              type: "password",
-              value: draftApiKey,
-              placeholder: settings.hasApiKey ? "已存储 (留空保持不变)" : "输入 API Key",
-              onChange: (e) => setDraftApiKey(e.target.value),
-            })
-          ),
-
-          // Current voice in draft
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-draft-current" }, "当前声音"),
-            h(Select, {
-              id: "duplex-draft-current",
-              value: draftCurrent,
-              onChange: (e) => setDraftCurrent(e.target.value),
-            },
-              draftVoices
-                .filter((v) => v.id.trim())
-                .map((v) =>
-                  h(SelectOption, { key: v.id, value: v.id }, v.name || v.id)
-                )
-            )
-          ),
-
-          // Voice list editor
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, null, "声音列表"),
-            h("div", { className: "yaoyao-voice-editor" },
-              draftVoices.map((voice, idx) =>
-                h("div", { key: idx, className: "yaoyao-voice-editor-row" },
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音名称 (如 小何 2.0)",
-                    value: voice.name,
-                    onChange: (e) => updateVoice(idx, "name", e.target.value),
-                  }),
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音 ID (如 zh_female_xiaohe_uranus_bigtts)",
-                    value: voice.id,
-                    onChange: (e) => updateVoice(idx, "id", e.target.value),
-                  }),
-                  h(Button, {
-                    variant: "ghost",
-                    size: "sm",
-                    disabled: draftVoices.length <= 1,
-                    onClick: () => removeVoice(idx),
-                  }, "×")
-                )
-              ),
-              h(Button, { variant: "outline", size: "sm", onClick: addVoice }, "+ 添加声音")
-            )
-          ),
-
-          h("div", { className: "yaoyao-voice-actions" },
-            h(Button, { variant: "ghost", onClick: () => setEditing(false) }, "取消"),
-            h(Button, { onClick: saveSettings, disabled: saving }, saving ? "保存中…" : "保存")
-          )
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // TTS / STT provider settings page
-  // Mirrors yaoyao-webui's VoiceSettings.vue + VoiceApiConfigurator.vue.
-  // ---------------------------------------------------------------------
-
-  function VoiceProvidersPage() {
-    const [ttsData, setTtsData] = useState(null);
-    const [sttData, setSttData] = useState(null);
-    const [providersInfo, setProvidersInfo] = useState(null);
-    const [error, setError] = useState(null);
-    const [saving, setSaving] = useState(false);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    useEffect(() => {
-      Promise.all([
-        fetchJSON(`${API}/tts/settings`),
-        fetchJSON(`${API}/stt/settings`),
-        fetchJSON(`${API}/voice/providers-info`),
-      ]).then(([t, s, p]) => {
-        setTtsData(t);
-        setSttData(s);
-        setProvidersInfo(p);
-      }).catch((e) => setError(String(e.message || e)));
-    }, []);
-
-    async function setTtsActive(provider) {
-      try {
-        await fetchJSON(`${API}/tts/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setTtsData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function setSttActive(provider) {
-      try {
-        await fetchJSON(`${API}/stt/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setSttData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function saveProvider(kind, provider, settings, secrets) {
-      setSaving(true);
-      setError(null);
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        const res = await fetchJSON(endpoint, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({settings, secrets}),
-        });
-        // Refresh
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-        setSavedMsg(`${provider} 已保存`);
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function deleteProvider(kind, provider) {
-      if (!confirm(`确定删除 ${provider} 配置?`)) return;
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        await fetchJSON(endpoint, {method: "DELETE"});
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    if (!ttsData || !sttData || !providersInfo) {
-      return h("div", {className: "yaoyao-loading"}, "加载中…");
-    }
-
-    const ttsProviders = providersInfo.tts.providers;
-    const sttProviders = providersInfo.stt.providers;
-
-    function renderProviderCard(kind, info, data) {
-      const settings = (data.settings || []).find(s => s.provider === info.id);
-      const isActive = data.activeProvider === info.id;
-      const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-      const isConfigured = info.id === "edge" || info.id === "browser" || hasKey;
-
-      return h(Card, {key: info.id, className: cn("yaoyao-provider-card", isActive && "yaoyao-provider-active")},
-        h(CardContent, {className: "yaoyao-voice-card"},
-          h("div", {className: "yaoyao-provider-header"},
-            h("div", {className: "yaoyao-provider-title-row"},
-              h("h5", null, info.label),
-              h(Badge, {variant: isActive ? "default" : "secondary"},
-                isActive ? "当前" : (isConfigured ? "已配置" : "未配置"))
-            ),
-            h("p", {className: "yaoyao-hint"},
-              info.needsKey ? "需要 API Key" : "免费 / 内置")
-          ),
-          h(ProviderEditor, {
-            kind, info, settings: settings || null, saving,
-            onSave: (s, sec) => saveProvider(kind, info.id, s, sec),
-            onDelete: info.id !== "edge" && info.id !== "browser"
-              ? () => deleteProvider(kind, info.id) : null,
-            onActivate: () => kind === "tts" ? setTtsActive(info.id) : setSttActive(info.id),
-          })
-        )
-      );
-    }
-
-    return h("div", {className: "yaoyao-page"},
-      h("div", {className: "yaoyao-header"},
-        h("h2", null, "语音引擎配置"),
-        savedMsg ? h(Badge, {variant: "secondary"}, savedMsg) : null
-      ),
-      error ? h("div", {className: "yaoyao-error"}, error) : null,
-
-      h("h3", {className: "yaoyao-section-title"}, "TTS (文字转语音)"),
-      h("div", {className: "yaoyao-provider-list"},
-        ttsProviders.map(info => renderProviderCard("tts", info, ttsData))
-      ),
-
-      h("h3", {className: "yaoyao-section-title"}, "STT (语音转文字)"),
-      h("div", {className: "yaoyao-provider-list"},
-        sttProviders.map(info => renderProviderCard("stt", info, sttData))
-      )
-    );
-  }
-
-  // Inline provider editor (expandable)
-  function ProviderEditor({kind, info, settings, saving, onSave, onDelete, onActivate}) {
-    const [expanded, setExpanded] = useState(false);
-    const [draft, setDraft] = useState({});
-
-    useEffect(() => {
-      if (settings) {
-        setDraft({
-          baseUrl: settings.settings?.baseUrl || info.defaults?.baseUrl || "",
-          model: settings.settings?.model || info.defaults?.model || "",
-          voice: settings.settings?.voice || info.defaults?.voice || "",
-          language: settings.settings?.language || info.defaults?.language || "",
-          rate: settings.settings?.rate || "",
-          pitch: settings.settings?.pitch || "",
-          stylePrompt: settings.settings?.stylePrompt || "",
-          apiKey: "",
-        });
-      } else {
-        setDraft({
-          baseUrl: info.defaults?.baseUrl || "",
-          model: info.defaults?.model || "",
-          voice: info.defaults?.voice || "",
-          language: info.defaults?.language || "",
-          apiKey: "",
-        });
-      }
-    }, [info.id, settings]);
-
-    function update(field, value) {
-      setDraft(d => ({...d, [field]: value}));
-    }
-
-    function handleSave() {
-      const s = {};
-      const sec = {};
-      if (draft.baseUrl) s.baseUrl = draft.baseUrl;
-      if (draft.model) s.model = draft.model;
-      if (draft.voice) s.voice = draft.voice;
-      if (draft.language) s.language = draft.language;
-      if (draft.rate) s.rate = draft.rate;
-      if (draft.pitch) s.pitch = draft.pitch;
-      if (draft.stylePrompt) s.stylePrompt = draft.stylePrompt;
-      if (draft.apiKey) sec.apiKey = draft.apiKey;
-      onSave(s, sec);
-    }
-
-    const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-    const showFields = info.settingsKeys || [];
-
-    return h("div", {className: "yaoyao-provider-editor"},
-      h("div", {className: "yaoyao-provider-actions"},
-        h(Button, {variant: "outline", size: "sm", onClick: () => setExpanded(e => !e)},
-          expanded ? "收起" : "展开"),
-        onActivate ? h(Button, {variant: "ghost", size: "sm", onClick: onActivate}, "设为当前") : null,
-      ),
-      expanded ? h("div", {className: "yaoyao-provider-fields"},
-        showFields.includes("baseUrl") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "Base URL"),
-          h(Input, {type: "text", value: draft.baseUrl, onChange: e => update("baseUrl", e.target.value),
-            placeholder: "https://..."})
-        ) : null,
-        showFields.includes("model") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "模型"),
-          h(Input, {type: "text", value: draft.model, onChange: e => update("model", e.target.value),
-            placeholder: "model id"})
-        ) : null,
-        showFields.includes("voice") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "声音"),
-          h(Input, {type: "text", value: draft.voice, onChange: e => update("voice", e.target.value),
-            placeholder: "voice id"})
-        ) : null,
-        showFields.includes("language") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语言"),
-          h(Input, {type: "text", value: draft.language, onChange: e => update("language", e.target.value),
-            placeholder: "zh / en / ..."})
-        ) : null,
-        showFields.includes("rate") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语速"),
-          h(Input, {type: "text", value: draft.rate, onChange: e => update("rate", e.target.value),
-            placeholder: "+0%"})
-        ) : null,
-        showFields.includes("pitch") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "音调"),
-          h(Input, {type: "text", value: draft.pitch, onChange: e => update("pitch", e.target.value),
-            placeholder: "+0Hz"})
-        ) : null,
-        showFields.includes("stylePrompt") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "风格提示"),
-          h(Input, {type: "text", value: draft.stylePrompt, onChange: e => update("stylePrompt", e.target.value),
-            placeholder: "style prompt"})
-        ) : null,
-        info.needsKey ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "API Key"),
-          h(Input, {type: "password", value: draft.apiKey,
-            onChange: e => update("apiKey", e.target.value),
-            placeholder: hasKey ? "已存储 (留空保持不变)" : "输入 API Key"})
-        ) : null,
-        h("div", {className: "yaoyao-voice-actions"},
-          h(Button, {size: "sm", onClick: handleSave, disabled: saving},
-            saving ? "保存中…" : "保存"),
-          onDelete ? h(Button, {variant: "ghost", size: "sm", onClick: onDelete}, "删除") : null,
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Top-level page with internal tab switcher (Files / Duplex / Engines)
-  // ---------------------------------------------------------------------
-
-  function YaoyaoPage() {
-    const [tab, setTab] = useState("files");
-    return h("div", { className: "yaoyao-root" },
-      h("div", { className: "yaoyao-tabs" },
-        h("button", {
-          className: cn("yaoyao-tab", tab === "files" && "yaoyao-tab-active"),
-          onClick: () => setTab("files"),
-        }, "文件库"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "duplex" && "yaoyao-tab-active"),
-          onClick: () => setTab("duplex"),
-        }, "App双流直连"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "engines" && "yaoyao-tab-active"),
-          onClick: () => setTab("engines"),
-        }, "语音引擎")
-      ),
-      tab === "files" ? h(YaoyaoFilesPage)
-      : tab === "duplex" ? h(VoiceSettingsPage)
-      : h(VoiceProvidersPage)
-    );
-  }
-
-  // Register the plugin page. The name MUST match manifest.json "name".
-  if (window.__HERMES_PLUGINS__ &&
-      typeof window.__HERMES_PLUGINS__.register === "function") {
-    window.__HERMES_PLUGINS__.register("yaoyao", YaoyaoPage);
-  }
-})();

+ 0 - 934
hermes-plugins/yaoyao/dashboard/dist/index.v1.4.0.js

@@ -1,934 +0,0 @@
-/**
- * Yaoyao File Library - dashboard plugin frontend.
- *
- * Plain IIFE, no build step. Uses window.__HERMES_PLUGIN_SDK__ for React +
- * shadcn-ui primitives + fetchJSON / authedFetch. Backend routes live under
- * /api/plugins/yaoyao/ (auto-mounted by the dashboard plugin loader).
- */
-(function () {
-  "use strict";
-
-  const SDK = window.__HERMES_PLUGIN_SDK__;
-  if (!SDK) return;
-  const { React } = SDK;
-  const h = React.createElement;
-  const { useState, useEffect, useCallback, useRef, useMemo } = SDK.hooks;
-  const {
-    Card,
-    CardContent,
-    Badge,
-    Button,
-    Input,
-    Label,
-    Select,
-    SelectOption,
-  } = SDK.components;
-  const { cn, timeAgo } = SDK.utils;
-  const fetchJSON = SDK.fetchJSON;
-  const authedFetch = SDK.authedFetch;
-
-  const API = "/api/plugins/yaoyao";
-
-  // ---------------------------------------------------------------------
-  // Helpers
-  // ---------------------------------------------------------------------
-
-  function inferKind(name, mimeType) {
-    const ext = (name.split(".").pop() || "").toLowerCase();
-    if ((mimeType || "").startsWith("image/") ||
-        ["png","jpg","jpeg","gif","webp","bmp","svg","tiff","tif"].includes(ext))
-      return "image";
-    if ((mimeType || "").startsWith("video/") ||
-        ["mp4","mov","avi","mkv","webm","m4v","wmv","flv"].includes(ext))
-      return "video";
-    if ((mimeType || "").startsWith("text/") ||
-        ["txt","md","json","yaml","yml","csv","log","py","js","ts","html","xml","rst"].includes(ext))
-      return "text";
-    return "file";
-  }
-
-  function formatBytes(n) {
-    if (!n || n <= 0) return "0 B";
-    const units = ["B", "KB", "MB", "GB"];
-    let i = 0, v = n;
-    while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
-    return v >= 100 ? v.toFixed(0) + " " + units[i]
-         : v >= 10  ? v.toFixed(1) + " " + units[i]
-                    : v.toFixed(2) + " " + units[i];
-  }
-
-  function senderLabel(s) {
-    return s === "user" ? "用户" : s === "agent" ? "Agent" : s;
-  }
-
-  function kindIcon(kind) {
-    switch (kind) {
-      case "image": return "🖼";
-      case "video": return "🎬";
-      case "text": return "📄";
-      default: return "📦";
-    }
-  }
-
-  // ---------------------------------------------------------------------
-  // Thumbnail image: fetch as blob via authedFetch (img tags can't set
-  // Authorization headers), then create an object URL.
-  // ---------------------------------------------------------------------
-
-  function Thumbnail({ item, profile }) {
-    const [url, setUrl] = useState(null);
-    const [err, setErr] = useState(false);
-    const kind = inferKind(item.name, item.mimeType);
-
-    useEffect(() => {
-      if (kind !== "image") return;
-      let revoke = null;
-      let cancelled = false;
-      const dlUrl = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-      authedFetch(dlUrl)
-        .then((res) => res.blob())
-        .then((blob) => {
-          if (cancelled) return;
-          const u = URL.createObjectURL(blob);
-          revoke = u;
-          setUrl(u);
-        })
-        .catch(() => { if (!cancelled) setErr(true); });
-      return () => {
-        cancelled = true;
-        if (revoke) URL.revokeObjectURL(revoke);
-      };
-    }, [item.id, profile]);
-
-    if (kind !== "image") {
-      return h("div", {
-        className: "yaoyao-thumb yaoyao-thumb-icon",
-      }, kindIcon(kind));
-    }
-    if (err) return h("div", { className: "yaoyao-thumb yaoyao-thumb-icon" }, "🖼");
-    if (!url) return h("div", { className: "yaoyao-thumb yaoyao-thumb-loading" }, "…");
-    return h("img", {
-      src: url,
-      alt: item.name,
-      className: "yaoyao-thumb yaoyao-thumb-img",
-      loading: "lazy",
-    });
-  }
-
-  // ---------------------------------------------------------------------
-  // File card
-  // ---------------------------------------------------------------------
-
-  function FileCard({ item, onDownload, profile }) {
-    const kind = inferKind(item.name, item.mimeType);
-    return h(Card, { className: "yaoyao-card" },
-      h(CardContent, { className: "yaoyao-card-content" },
-        h("div", { className: "yaoyao-card-preview" },
-          h(Thumbnail, { item: item, profile: profile })
-        ),
-        h("div", { className: "yaoyao-card-info" },
-          h("div", { className: "yaoyao-card-name", title: item.name }, item.name),
-          h("div", { className: "yaoyao-card-meta" },
-            h(Badge, { variant: "secondary" }, senderLabel(item.origins && item.origins[0] ? item.origins[0].authorKind : "agent")),
-            h("span", { className: "yaoyao-card-size" }, formatBytes(item.size)),
-            item.messageTimestamp
-              ? h("span", { className: "yaoyao-card-time" }, timeAgo(item.messageTimestamp * 1000))
-              : null
-          ),
-          h("div", { className: "yaoyao-card-actions" },
-            h(Button, {
-              variant: "outline",
-              size: "sm",
-              onClick: () => onDownload(item),
-            }, "下载")
-          )
-        )
-      )
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Main page
-  // ---------------------------------------------------------------------
-
-  function YaoyaoFilesPage() {
-    const [items, setItems] = useState([]);
-    const [loading, setLoading] = useState(true);
-    const [loadingMore, setLoadingMore] = useState(false);
-    const [error, setError] = useState(null);
-    const [cursor, setCursor] = useState(null);
-    const [hasMore, setHasMore] = useState(false);
-    const [stats, setStats] = useState(null);
-    const [profiles, setProfiles] = useState([]);
-    // Initial profile from the URL (?profile=gril) so deep links / shared
-    // links land on the right agent's library; fall back to "default".
-    const [profile, setProfile] = useState(() => {
-      try {
-        const u = new URL(window.location.href);
-        const p = u.searchParams.get("profile");
-        return p || "default";
-      } catch (e) {
-        return "default";
-      }
-    });
-    const [filter, setFilter] = useState({ sender: "", kind: "" });
-    const [search, setSearch] = useState("");
-    const [searchInput, setSearchInput] = useState("");
-    const sentinelRef = useRef(null);
-
-    // Keep the URL ?profile= in sync with the dropdown selection so the
-    // address bar reflects what's shown (and is shareable / refreshable).
-    useEffect(() => {
-      try {
-        const u = new URL(window.location.href);
-        if (profile && profile !== "default") {
-          u.searchParams.set("profile", profile);
-        } else {
-          u.searchParams.delete("profile");
-        }
-        window.history.replaceState(null, "", u.toString());
-      } catch (e) { /* ignore */ }
-    }, [profile]);
-
-    // Also react to back/forward navigation so the dropdown follows the URL.
-    useEffect(() => {
-      const onPop = () => {
-        try {
-          const u = new URL(window.location.href);
-          const p = u.searchParams.get("profile") || "default";
-          setProfile(p);
-        } catch (e) { /* ignore */ }
-      };
-      window.addEventListener("popstate", onPop);
-      return () => window.removeEventListener("popstate", onPop);
-    }, []);
-
-    // Profiles dropdown: which agents have libraries. default always present.
-    useEffect(() => {
-      fetchJSON(`${API}/profiles`)
-        .then((res) => {
-          const list = (res.profiles || []);
-          setProfiles(list);
-          // If the current selection vanished (profile deleted), fall back.
-          if (list.length && !list.some((p) => p.name === profile)) {
-            setProfile("default");
-          }
-        })
-        .catch(() => {});
-    }, []); // eslint-disable-line
-
-    // Fetch first page whenever filter / search / profile changes.
-    const loadFirst = useCallback(async () => {
-      setLoading(true);
-      setError(null);
-      try {
-        const params = { limit: 50 };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems(res.items || []);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }, [filter, search, profile]);
-
-    useEffect(() => { loadFirst(); }, [loadFirst]);
-
-    // Stats (re-fetch when profile changes)
-    useEffect(() => {
-      const params = {};
-      if (profile) params.profile = profile;
-      const qs = new URLSearchParams(params).toString();
-      fetchJSON(`${API}/stats?${qs}`).then(setStats).catch(() => {});
-    }, [profile]);
-
-    // Load more
-    const loadMore = useCallback(async () => {
-      if (!cursor || loadingMore) return;
-      setLoadingMore(true);
-      try {
-        const params = { limit: 50, cursor };
-        if (profile) params.profile = profile;
-        if (filter.sender) params.sender = filter.sender;
-        if (filter.kind) params.kind = filter.kind;
-        if (search) params.search = search;
-        const qs = new URLSearchParams(params).toString();
-        const res = await fetchJSON(`${API}/files?${qs}`);
-        setItems((prev) => [...prev, ...(res.items || [])]);
-        setCursor(res.nextCursor || null);
-        setHasMore(!!res.nextCursor);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoadingMore(false);
-      }
-    }, [cursor, filter, search, profile, loadingMore]);
-
-    // Infinite scroll via IntersectionObserver
-    useEffect(() => {
-      const el = sentinelRef.current;
-      if (!el || !hasMore) return;
-      const obs = new IntersectionObserver((entries) => {
-        if (entries[0].isIntersecting) loadMore();
-      }, { rootMargin: "200px" });
-      obs.observe(el);
-      return () => obs.disconnect();
-    }, [hasMore, loadMore]);
-
-    const onDownload = useCallback(async (item) => {
-      try {
-        const url = `${API}/${item.id}/download` + (profile ? `?profile=${encodeURIComponent(profile)}` : "");
-        const res = await authedFetch(url);
-        const blob = await res.blob();
-        const urlObj = URL.createObjectURL(blob);
-        const a = document.createElement("a");
-        a.href = urlObj;
-        a.download = item.name;
-        document.body.appendChild(a);
-        a.click();
-        document.body.removeChild(a);
-        setTimeout(() => URL.revokeObjectURL(urlObj), 10000);
-      } catch (e) {
-        alert("下载失败: " + (e.message || e));
-      }
-    }, [profile]);
-
-    const onSearchSubmit = useCallback((e) => {
-      e.preventDefault();
-      setSearch(searchInput.trim());
-    }, [searchInput]);
-
-    return h("div", { className: "yaoyao-page" },
-      // Header + stats
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "夭夭文件库"),
-        stats ? h("div", { className: "yaoyao-stats" },
-          profile && profile !== "default"
-            ? h(Badge, { variant: "secondary" }, `Agent: ${profile}`)
-            : null,
-          h(Badge, { variant: "secondary" }, `共 ${stats.totalAttachments} 个文件`),
-          h(Badge, { variant: "secondary" }, `${formatBytes(stats.totalBytes)}`),
-          stats.bySender && stats.bySender.agent
-            ? h(Badge, { variant: "outline" }, `Agent ${stats.bySender.agent}`)
-            : null,
-          stats.bySender && stats.bySender.user
-            ? h(Badge, { variant: "outline" }, `用户 ${stats.bySender.user}`)
-            : null,
-        ) : null
-      ),
-
-      // Filters
-      h("div", { className: "yaoyao-filters" },
-        h(Label, null, "Agent"),
-        h(Select, {
-          value: profile,
-          onChange: (e) => setProfile(e.target.value),
-          disabled: profiles.length === 0,
-        },
-          profiles.length === 0
-            ? h(SelectOption, { value: "default" }, "默认")
-            : profiles.map((p) =>
-                h(SelectOption, { key: p.name, value: p.name }, p.label)
-              )
-        ),
-        h(Label, null, "来源"),
-        h(Select, {
-          value: filter.sender,
-          onChange: (e) => setFilter((f) => ({ ...f, sender: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "agent" }, "Agent"),
-          h(SelectOption, { value: "user" }, "用户")
-        ),
-        h(Label, null, "类型"),
-        h(Select, {
-          value: filter.kind,
-          onChange: (e) => setFilter((f) => ({ ...f, kind: e.target.value })),
-        },
-          h(SelectOption, { value: "" }, "全部"),
-          h(SelectOption, { value: "image" }, "图片"),
-          h(SelectOption, { value: "video" }, "视频"),
-          h(SelectOption, { value: "text" }, "文本"),
-          h(SelectOption, { value: "file" }, "文档")
-        ),
-        h("form", { onSubmit: onSearchSubmit, className: "yaoyao-search" },
-          h(Input, {
-            type: "text",
-            placeholder: "搜索文件名…",
-            value: searchInput,
-            onChange: (e) => setSearchInput(e.target.value),
-          }),
-          h(Button, { type: "submit", size: "sm" }, "搜索")
-        )
-      ),
-
-      // Error
-      error ? h("div", { className: "yaoyao-error" }, "错误: " + error) : null,
-
-      // Loading
-      loading ? h("div", { className: "yaoyao-loading" }, "加载中…") :
-      // Grid
-      items.length === 0
-        ? h("div", { className: "yaoyao-empty" }, "暂无文件")
-        : h("div", { className: "yaoyao-grid" },
-            items.map((item) =>
-              h(FileCard, { key: item.id, item: item, onDownload: onDownload, profile: profile })
-            )
-          ),
-
-      // Infinite scroll sentinel
-      hasMore ? h("div", {
-        ref: sentinelRef,
-        className: "yaoyao-sentinel"
-      }, loadingMore ? "加载更多…" : "") : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Voice settings page
-  // ---------------------------------------------------------------------
-
-  // ---------------------------------------------------------------------
-  // Duplex voice settings page
-  // Mirrors yaoyao-webui's IosDuplexVoiceSettings.vue contract:
-  // {hasApiKey, voices:[{id,name}], currentVoiceId, updatedAt}
-  // ---------------------------------------------------------------------
-
-  function VoiceSettingsPage() {
-    const [settings, setSettings] = useState(null);
-    const [loading, setLoading] = useState(true);
-    const [saving, setSaving] = useState(false);
-    const [switching, setSwitching] = useState(false);
-    const [error, setError] = useState(null);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    // Draft state for the editor
-    const [draftApiKey, setDraftApiKey] = useState("");
-    const [draftVoices, setDraftVoices] = useState([]);
-    const [draftCurrent, setDraftCurrent] = useState("");
-    const [editing, setEditing] = useState(false);
-
-    useEffect(() => {
-      load();
-    }, []);
-
-    async function load() {
-      setLoading(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/settings`);
-        setSettings(s);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setLoading(false);
-      }
-    }
-
-    const voiceOptions = useMemo(() => {
-      if (!settings) return [];
-      return settings.voices
-        .filter((v) => v.id.trim() && v.name.trim())
-        .map((v) => ({ label: v.name, value: v.id }));
-    }, [settings]);
-
-    const isConfigured = settings
-      && settings.hasApiKey
-      && voiceOptions.length > 0
-      && voiceOptions.some((o) => o.value === settings.currentVoiceId);
-
-    function openEditor() {
-      setDraftApiKey("");
-      setDraftVoices((settings?.voices || []).map((v) => ({ ...v })));
-      setDraftCurrent(settings?.currentVoiceId || "");
-      setEditing(true);
-    }
-
-    function addVoice() {
-      setDraftVoices((prev) => [...prev, { id: "", name: "" }]);
-    }
-
-    function removeVoice(idx) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        const removed = next[idx];
-        next.splice(idx, 1);
-        if (removed?.id === draftCurrent) {
-          setDraftCurrent(next[0]?.id || "");
-        }
-        return next;
-      });
-    }
-
-    function updateVoice(idx, field, value) {
-      setDraftVoices((prev) => {
-        const next = [...prev];
-        next[idx] = { ...next[idx], [field]: value };
-        return next;
-      });
-    }
-
-    async function saveSettings() {
-      setSaving(true);
-      setError(null);
-      try {
-        const body = {
-          voices: draftVoices.map((v) => ({ id: v.id.trim(), name: v.name.trim() })),
-          currentVoiceId: draftCurrent,
-        };
-        if (draftApiKey.trim()) body.apiKey = draftApiKey.trim();
-        const s = await fetchJSON(`${API}/voice/settings`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify(body),
-        });
-        setSettings(s);
-        setEditing(false);
-        setSavedMsg("已保存");
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function switchVoice(voiceId) {
-      if (switching || voiceId === settings.currentVoiceId) return;
-      setSwitching(true);
-      try {
-        const s = await fetchJSON(`${API}/voice/current-voice`, {
-          method: "PUT",
-          headers: { "Content-Type": "application/json" },
-          body: JSON.stringify({ currentVoiceId: voiceId }),
-        });
-        setSettings((prev) => ({ ...prev, ...s }));
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSwitching(false);
-      }
-    }
-
-    if (loading) return h("div", { className: "yaoyao-loading" }, "加载中…");
-    if (!settings) return h("div", { className: "yaoyao-error" }, "加载失败: " + error);
-
-    const currentVoiceName = voiceOptions.find((o) => o.value === settings.currentVoiceId)?.label
-      || settings.currentVoiceId
-      || "未选择";
-
-    return h("div", { className: "yaoyao-page" },
-      h("div", { className: "yaoyao-header" },
-        h("h2", null, "App 双流直连配置"),
-        savedMsg ? h(Badge, { variant: "secondary" }, savedMsg) : null
-      ),
-
-      // Status card
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-duplex-status" },
-            h("div", { className: "yaoyao-duplex-icon" }, "D"),
-            h("div", { className: "yaoyao-duplex-info" },
-              h("div", { className: "yaoyao-duplex-title-row" },
-                h("h5", null, "火山引擎 / 豆包 TTS"),
-                h(Badge, {
-                  variant: isConfigured ? "default" : "secondary",
-                }, isConfigured ? "已配置" : "未配置")
-              ),
-              h("p", { className: "yaoyao-hint" },
-                "iOS App 直连 TTS 引擎进行双流语音对话。API Key 和声音列表在此配置后,App 从 /voice/runtime 拉取。")
-            )
-          ),
-          h("div", { className: "yaoyao-duplex-meta" },
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "当前声音"), h("span", null, currentVoiceName)),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "API Key"), h("span", null, settings.hasApiKey ? "已存储" : "未设置")),
-            h("div", null, h("span", { className: "yaoyao-meta-label" }, "声音数量"), h("span", null, String(settings.voices.length))),
-          )
-        )
-      ),
-
-      // Current voice quick switch
-      h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-current" }, "当前声音"),
-            h("div", { className: "yaoyao-voice-switch" },
-              h(Select, {
-                id: "duplex-current",
-                value: settings.currentVoiceId,
-                onChange: (e) => switchVoice(e.target.value),
-                disabled: switching || voiceOptions.length === 0,
-              },
-                voiceOptions.map((o) =>
-                  h(SelectOption, { key: o.value, value: o.value }, o.label)
-                )
-              ),
-              h(Button, {
-                variant: "outline",
-                size: "sm",
-                onClick: openEditor,
-              }, "编辑配置")
-            )
-          )
-        )
-      ),
-
-      error ? h("div", { className: "yaoyao-error" }, error) : null,
-
-      // Editor (inline form)
-      editing ? h(Card, null,
-        h(CardContent, { className: "yaoyao-voice-card" },
-          h("h3", { className: "yaoyao-section-title" }, "编辑双流配置"),
-
-          // API Key
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-key" }, "API Key"),
-            h(Input, {
-              id: "duplex-key",
-              type: "password",
-              value: draftApiKey,
-              placeholder: settings.hasApiKey ? "已存储 (留空保持不变)" : "输入 API Key",
-              onChange: (e) => setDraftApiKey(e.target.value),
-            })
-          ),
-
-          // Current voice in draft
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, { htmlFor: "duplex-draft-current" }, "当前声音"),
-            h(Select, {
-              id: "duplex-draft-current",
-              value: draftCurrent,
-              onChange: (e) => setDraftCurrent(e.target.value),
-            },
-              draftVoices
-                .filter((v) => v.id.trim())
-                .map((v) =>
-                  h(SelectOption, { key: v.id, value: v.id }, v.name || v.id)
-                )
-            )
-          ),
-
-          // Voice list editor
-          h("div", { className: "yaoyao-voice-row" },
-            h(Label, null, "声音列表"),
-            h("div", { className: "yaoyao-voice-editor" },
-              draftVoices.map((voice, idx) =>
-                h("div", { key: idx, className: "yaoyao-voice-editor-row" },
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音名称 (如 小何 2.0)",
-                    value: voice.name,
-                    onChange: (e) => updateVoice(idx, "name", e.target.value),
-                  }),
-                  h(Input, {
-                    type: "text",
-                    placeholder: "声音 ID (如 zh_female_xiaohe_uranus_bigtts)",
-                    value: voice.id,
-                    onChange: (e) => updateVoice(idx, "id", e.target.value),
-                  }),
-                  h(Button, {
-                    variant: "ghost",
-                    size: "sm",
-                    disabled: draftVoices.length <= 1,
-                    onClick: () => removeVoice(idx),
-                  }, "×")
-                )
-              ),
-              h(Button, { variant: "outline", size: "sm", onClick: addVoice }, "+ 添加声音")
-            )
-          ),
-
-          h("div", { className: "yaoyao-voice-actions" },
-            h(Button, { variant: "ghost", onClick: () => setEditing(false) }, "取消"),
-            h(Button, { onClick: saveSettings, disabled: saving }, saving ? "保存中…" : "保存")
-          )
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // TTS / STT provider settings page
-  // Mirrors yaoyao-webui's VoiceSettings.vue + VoiceApiConfigurator.vue.
-  // ---------------------------------------------------------------------
-
-  function VoiceProvidersPage() {
-    const [ttsData, setTtsData] = useState(null);
-    const [sttData, setSttData] = useState(null);
-    const [providersInfo, setProvidersInfo] = useState(null);
-    const [error, setError] = useState(null);
-    const [saving, setSaving] = useState(false);
-    const [savedMsg, setSavedMsg] = useState(null);
-
-    useEffect(() => {
-      Promise.all([
-        fetchJSON(`${API}/tts/settings`),
-        fetchJSON(`${API}/stt/settings`),
-        fetchJSON(`${API}/voice/providers-info`),
-      ]).then(([t, s, p]) => {
-        setTtsData(t);
-        setSttData(s);
-        setProvidersInfo(p);
-      }).catch((e) => setError(String(e.message || e)));
-    }, []);
-
-    async function setTtsActive(provider) {
-      try {
-        await fetchJSON(`${API}/tts/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setTtsData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function setSttActive(provider) {
-      try {
-        await fetchJSON(`${API}/stt/settings/active`, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({provider}),
-        });
-        setSttData((d) => ({...d, activeProvider: provider}));
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    async function saveProvider(kind, provider, settings, secrets) {
-      setSaving(true);
-      setError(null);
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        const res = await fetchJSON(endpoint, {
-          method: "PUT", headers: {"Content-Type":"application/json"},
-          body: JSON.stringify({settings, secrets}),
-        });
-        // Refresh
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-        setSavedMsg(`${provider} 已保存`);
-        setTimeout(() => setSavedMsg(null), 2000);
-      } catch (e) {
-        setError(String(e.message || e));
-      } finally {
-        setSaving(false);
-      }
-    }
-
-    async function deleteProvider(kind, provider) {
-      if (!confirm(`确定删除 ${provider} 配置?`)) return;
-      try {
-        const endpoint = kind === "tts" ? `${API}/tts/settings/${provider}` : `${API}/stt/settings/${provider}`;
-        await fetchJSON(endpoint, {method: "DELETE"});
-        if (kind === "tts") {
-          const fresh = await fetchJSON(`${API}/tts/settings`);
-          setTtsData(fresh);
-        } else {
-          const fresh = await fetchJSON(`${API}/stt/settings`);
-          setSttData(fresh);
-        }
-      } catch (e) { setError(String(e.message || e)); }
-    }
-
-    if (!ttsData || !sttData || !providersInfo) {
-      return h("div", {className: "yaoyao-loading"}, "加载中…");
-    }
-
-    const ttsProviders = providersInfo.tts.providers;
-    const sttProviders = providersInfo.stt.providers;
-
-    function renderProviderCard(kind, info, data) {
-      const settings = (data.settings || []).find(s => s.provider === info.id);
-      const isActive = data.activeProvider === info.id;
-      const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-      const isConfigured = info.id === "edge" || info.id === "browser" || hasKey;
-
-      return h(Card, {key: info.id, className: cn("yaoyao-provider-card", isActive && "yaoyao-provider-active")},
-        h(CardContent, {className: "yaoyao-voice-card"},
-          h("div", {className: "yaoyao-provider-header"},
-            h("div", {className: "yaoyao-provider-title-row"},
-              h("h5", null, info.label),
-              h(Badge, {variant: isActive ? "default" : "secondary"},
-                isActive ? "当前" : (isConfigured ? "已配置" : "未配置"))
-            ),
-            h("p", {className: "yaoyao-hint"},
-              info.needsKey ? "需要 API Key" : "免费 / 内置")
-          ),
-          h(ProviderEditor, {
-            kind, info, settings: settings || null, saving,
-            onSave: (s, sec) => saveProvider(kind, info.id, s, sec),
-            onDelete: info.id !== "edge" && info.id !== "browser"
-              ? () => deleteProvider(kind, info.id) : null,
-            onActivate: () => kind === "tts" ? setTtsActive(info.id) : setSttActive(info.id),
-          })
-        )
-      );
-    }
-
-    return h("div", {className: "yaoyao-page"},
-      h("div", {className: "yaoyao-header"},
-        h("h2", null, "语音引擎配置"),
-        savedMsg ? h(Badge, {variant: "secondary"}, savedMsg) : null
-      ),
-      error ? h("div", {className: "yaoyao-error"}, error) : null,
-
-      h("h3", {className: "yaoyao-section-title"}, "TTS (文字转语音)"),
-      h("div", {className: "yaoyao-provider-list"},
-        ttsProviders.map(info => renderProviderCard("tts", info, ttsData))
-      ),
-
-      h("h3", {className: "yaoyao-section-title"}, "STT (语音转文字)"),
-      h("div", {className: "yaoyao-provider-list"},
-        sttProviders.map(info => renderProviderCard("stt", info, sttData))
-      )
-    );
-  }
-
-  // Inline provider editor (expandable)
-  function ProviderEditor({kind, info, settings, saving, onSave, onDelete, onActivate}) {
-    const [expanded, setExpanded] = useState(false);
-    const [draft, setDraft] = useState({});
-
-    useEffect(() => {
-      if (settings) {
-        setDraft({
-          baseUrl: settings.settings?.baseUrl || info.defaults?.baseUrl || "",
-          model: settings.settings?.model || info.defaults?.model || "",
-          voice: settings.settings?.voice || info.defaults?.voice || "",
-          language: settings.settings?.language || info.defaults?.language || "",
-          rate: settings.settings?.rate || "",
-          pitch: settings.settings?.pitch || "",
-          stylePrompt: settings.settings?.stylePrompt || "",
-          apiKey: "",
-        });
-      } else {
-        setDraft({
-          baseUrl: info.defaults?.baseUrl || "",
-          model: info.defaults?.model || "",
-          voice: info.defaults?.voice || "",
-          language: info.defaults?.language || "",
-          apiKey: "",
-        });
-      }
-    }, [info.id, settings]);
-
-    function update(field, value) {
-      setDraft(d => ({...d, [field]: value}));
-    }
-
-    function handleSave() {
-      const s = {};
-      const sec = {};
-      if (draft.baseUrl) s.baseUrl = draft.baseUrl;
-      if (draft.model) s.model = draft.model;
-      if (draft.voice) s.voice = draft.voice;
-      if (draft.language) s.language = draft.language;
-      if (draft.rate) s.rate = draft.rate;
-      if (draft.pitch) s.pitch = draft.pitch;
-      if (draft.stylePrompt) s.stylePrompt = draft.stylePrompt;
-      if (draft.apiKey) sec.apiKey = draft.apiKey;
-      onSave(s, sec);
-    }
-
-    const hasKey = settings && settings.secrets && settings.secrets.apiKey === "[stored]";
-    const showFields = info.settingsKeys || [];
-
-    return h("div", {className: "yaoyao-provider-editor"},
-      h("div", {className: "yaoyao-provider-actions"},
-        h(Button, {variant: "outline", size: "sm", onClick: () => setExpanded(e => !e)},
-          expanded ? "收起" : "展开"),
-        onActivate ? h(Button, {variant: "ghost", size: "sm", onClick: onActivate}, "设为当前") : null,
-      ),
-      expanded ? h("div", {className: "yaoyao-provider-fields"},
-        showFields.includes("baseUrl") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "Base URL"),
-          h(Input, {type: "text", value: draft.baseUrl, onChange: e => update("baseUrl", e.target.value),
-            placeholder: "https://..."})
-        ) : null,
-        showFields.includes("model") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "模型"),
-          h(Input, {type: "text", value: draft.model, onChange: e => update("model", e.target.value),
-            placeholder: "model id"})
-        ) : null,
-        showFields.includes("voice") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "声音"),
-          h(Input, {type: "text", value: draft.voice, onChange: e => update("voice", e.target.value),
-            placeholder: "voice id"})
-        ) : null,
-        showFields.includes("language") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语言"),
-          h(Input, {type: "text", value: draft.language, onChange: e => update("language", e.target.value),
-            placeholder: "zh / en / ..."})
-        ) : null,
-        showFields.includes("rate") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "语速"),
-          h(Input, {type: "text", value: draft.rate, onChange: e => update("rate", e.target.value),
-            placeholder: "+0%"})
-        ) : null,
-        showFields.includes("pitch") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "音调"),
-          h(Input, {type: "text", value: draft.pitch, onChange: e => update("pitch", e.target.value),
-            placeholder: "+0Hz"})
-        ) : null,
-        showFields.includes("stylePrompt") ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "风格提示"),
-          h(Input, {type: "text", value: draft.stylePrompt, onChange: e => update("stylePrompt", e.target.value),
-            placeholder: "style prompt"})
-        ) : null,
-        info.needsKey ? h("div", {className: "yaoyao-voice-row"},
-          h(Label, null, "API Key"),
-          h(Input, {type: "password", value: draft.apiKey,
-            onChange: e => update("apiKey", e.target.value),
-            placeholder: hasKey ? "已存储 (留空保持不变)" : "输入 API Key"})
-        ) : null,
-        h("div", {className: "yaoyao-voice-actions"},
-          h(Button, {size: "sm", onClick: handleSave, disabled: saving},
-            saving ? "保存中…" : "保存"),
-          onDelete ? h(Button, {variant: "ghost", size: "sm", onClick: onDelete}, "删除") : null,
-        )
-      ) : null
-    );
-  }
-
-  // ---------------------------------------------------------------------
-  // Top-level page with internal tab switcher (Files / Duplex / Engines)
-  // ---------------------------------------------------------------------
-
-  function YaoyaoPage() {
-    const [tab, setTab] = useState("files");
-    return h("div", { className: "yaoyao-root" },
-      h("div", { className: "yaoyao-tabs" },
-        h("button", {
-          className: cn("yaoyao-tab", tab === "files" && "yaoyao-tab-active"),
-          onClick: () => setTab("files"),
-        }, "文件库"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "duplex" && "yaoyao-tab-active"),
-          onClick: () => setTab("duplex"),
-        }, "App双流直连"),
-        h("button", {
-          className: cn("yaoyao-tab", tab === "engines" && "yaoyao-tab-active"),
-          onClick: () => setTab("engines"),
-        }, "语音引擎")
-      ),
-      tab === "files" ? h(YaoyaoFilesPage)
-      : tab === "duplex" ? h(VoiceSettingsPage)
-      : h(VoiceProvidersPage)
-    );
-  }
-
-  // Register the plugin page. The name MUST match manifest.json "name".
-  if (window.__HERMES_PLUGINS__ &&
-      typeof window.__HERMES_PLUGINS__.register === "function") {
-    window.__HERMES_PLUGINS__.register("yaoyao", YaoyaoPage);
-  }
-})();

+ 0 - 433
hermes-plugins/yaoyao/dashboard/dist/style.css

@@ -1,433 +0,0 @@
-/* Yaoyao file library - dashboard plugin styles */
-
-.yaoyao-root {
-  width: 100%;
-}
-
-.yaoyao-tabs {
-  display: flex;
-  gap: 0.25rem;
-  padding: 0 1.5rem;
-  border-bottom: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.08));
-  max-width: 1200px;
-  margin: 0 auto;
-}
-
-.yaoyao-tab {
-  padding: 0.6rem 1rem;
-  border: none;
-  background: none;
-  cursor: pointer;
-  font-size: 0.9rem;
-  color: var(--muted-foreground, #888);
-  border-bottom: 2px solid transparent;
-  transition: color 0.15s, border-color 0.15s;
-}
-
-.yaoyao-tab:hover {
-  color: var(--foreground, #333);
-}
-
-.yaoyao-tab-active {
-  color: var(--foreground, #333);
-  border-bottom-color: var(--primary, #6366f1);
-  font-weight: 500;
-}
-
-.yaoyao-page {
-  width: 100%;
-  padding: 1.5rem;
-  max-width: 1200px;
-  margin: 0 auto;
-  box-sizing: border-box;
-}
-
-.yaoyao-header {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  flex-wrap: wrap;
-  gap: 0.75rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-header h2 {
-  margin: 0;
-  font-size: 1.4rem;
-  font-weight: 600;
-}
-
-.yaoyao-stats {
-  display: flex;
-  gap: 0.4rem;
-  flex-wrap: wrap;
-}
-
-.yaoyao-filters {
-  display: flex;
-  align-items: flex-end;
-  gap: 0.75rem;
-  flex-wrap: wrap;
-  margin-bottom: 1.25rem;
-  padding: 0.75rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.02));
-  border-radius: 0.5rem;
-}
-
-.yaoyao-filters label {
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-  margin-bottom: 0.15rem;
-  display: block;
-}
-
-.yaoyao-filters select,
-.yaoyao-filters input {
-  min-width: 100px;
-}
-
-.yaoyao-search {
-  display: flex;
-  gap: 0.4rem;
-  flex: 1;
-  min-width: 200px;
-}
-
-.yaoyao-search input {
-  flex: 1;
-}
-
-/* Grid */
-.yaoyao-grid {
-  display: grid;
-  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
-  gap: 0.75rem;
-}
-
-/* Card */
-.yaoyao-card {
-  overflow: hidden;
-}
-
-.yaoyao-card-content {
-  padding: 0.5rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-card-preview {
-  width: 100%;
-  aspect-ratio: 16 / 10;
-  background: rgba(0, 0, 0, 0.03);
-  border-radius: 0.4rem;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  overflow: hidden;
-}
-
-.yaoyao-thumb {
-  width: 100%;
-  height: 100%;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-}
-
-.yaoyao-thumb-img {
-  width: 100%;
-  height: 100%;
-  object-fit: cover;
-}
-
-.yaoyao-thumb-icon {
-  font-size: 2.5rem;
-  opacity: 0.5;
-}
-
-.yaoyao-thumb-loading {
-  font-size: 1.2rem;
-  opacity: 0.4;
-}
-
-.yaoyao-card-info {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-card-name {
-  font-size: 0.8rem;
-  font-weight: 500;
-  white-space: nowrap;
-  overflow: hidden;
-  text-overflow: ellipsis;
-}
-
-.yaoyao-card-meta {
-  display: flex;
-  align-items: center;
-  gap: 0.3rem;
-  flex-wrap: wrap;
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-card-size {
-  font-variant-numeric: tabular-nums;
-}
-
-.yaoyao-card-actions {
-  display: flex;
-  justify-content: flex-end;
-}
-
-/* States */
-.yaoyao-error {
-  padding: 0.75rem;
-  background: rgba(239, 68, 68, 0.1);
-  border-radius: 0.5rem;
-  color: #b91c1c;
-  font-size: 0.85rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-loading,
-.yaoyao-empty {
-  text-align: center;
-  padding: 3rem 1rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.95rem;
-}
-
-.yaoyao-sentinel {
-  text-align: center;
-  padding: 1.5rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.85rem;
-}
-
-/* Voice settings */
-.yaoyao-voice-card {
-  padding: 1rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-voice-row {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-voice-row label {
-  font-size: 0.8rem;
-  font-weight: 500;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-row select,
-.yaoyao-voice-row input[type="number"] {
-  max-width: 320px;
-}
-
-.yaoyao-voice-check {
-  flex-direction: row;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-check label {
-  display: flex;
-  align-items: center;
-  gap: 0.4rem;
-  cursor: pointer;
-  font-size: 0.85rem;
-  color: var(--foreground, #333);
-}
-
-.yaoyao-voice-actions {
-  display: flex;
-  gap: 0.5rem;
-  margin-top: 0.25rem;
-}
-
-.yaoyao-tts-textarea {
-  width: 100%;
-  max-width: 600px;
-  padding: 0.5rem;
-  border: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.12));
-  border-radius: 0.375rem;
-  font-size: 0.85rem;
-  resize: vertical;
-  background: var(--hermes-input-bg, transparent);
-  color: var(--foreground, inherit);
-  box-sizing: border-box;
-}
-
-.yaoyao-audio-player {
-  width: 100%;
-  max-width: 600px;
-  margin-top: 0.5rem;
-}
-
-.yaoyao-section-title {
-  margin: 0 0 0.25rem 0;
-  font-size: 1rem;
-  font-weight: 600;
-}
-
-.yaoyao-hint {
-  margin: 0 0 0.5rem 0;
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-agent-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-agent-item {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  padding: 0.3rem 0.5rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.03));
-  border-radius: 0.3rem;
-  font-size: 0.85rem;
-}
-
-.yaoyao-agent-add {
-  display: flex;
-  gap: 0.4rem;
-}
-
-/* Duplex voice status card */
-.yaoyao-duplex-status {
-  display: flex;
-  align-items: flex-start;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-duplex-icon {
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  width: 32px;
-  height: 32px;
-  flex-shrink: 0;
-  border: 1px solid var(--hermes-border, rgba(0,0,0,0.12));
-  border-radius: 0.3rem;
-  background: var(--hermes-card, rgba(0,0,0,0.03));
-  font-size: 0.8rem;
-  font-weight: 700;
-}
-
-.yaoyao-duplex-info {
-  min-width: 0;
-}
-
-.yaoyao-duplex-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-  margin-bottom: 0.25rem;
-}
-
-.yaoyao-duplex-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-duplex-meta {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  gap: 0.5rem 1rem;
-  font-size: 0.8rem;
-}
-
-.yaoyao-duplex-meta > div {
-  display: flex;
-  flex-direction: column;
-  gap: 0.1rem;
-}
-
-.yaoyao-meta-label {
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-switch {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor-row {
-  display: grid;
-  grid-template-columns: 0.85fr 1.15fr auto;
-  gap: 0.4rem;
-  align-items: center;
-}
-
-/* Provider cards */
-.yaoyao-provider-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 1.5rem;
-}
-
-.yaoyao-provider-card {
-  position: relative;
-  overflow: hidden;
-}
-
-.yaoyao-provider-card.yaoyao-provider-active::before {
-  content: '';
-  position: absolute;
-  inset: 0 auto 0 0;
-  width: 3px;
-  background: var(--primary, #6366f1);
-}
-
-.yaoyao-provider-header {
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-provider-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-provider-actions {
-  display: flex;
-  gap: 0.4rem;
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-fields {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}

+ 0 - 433
hermes-plugins/yaoyao/dashboard/dist/style.v1.1.0.css

@@ -1,433 +0,0 @@
-/* Yaoyao file library - dashboard plugin styles */
-
-.yaoyao-root {
-  width: 100%;
-}
-
-.yaoyao-tabs {
-  display: flex;
-  gap: 0.25rem;
-  padding: 0 1.5rem;
-  border-bottom: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.08));
-  max-width: 1200px;
-  margin: 0 auto;
-}
-
-.yaoyao-tab {
-  padding: 0.6rem 1rem;
-  border: none;
-  background: none;
-  cursor: pointer;
-  font-size: 0.9rem;
-  color: var(--muted-foreground, #888);
-  border-bottom: 2px solid transparent;
-  transition: color 0.15s, border-color 0.15s;
-}
-
-.yaoyao-tab:hover {
-  color: var(--foreground, #333);
-}
-
-.yaoyao-tab-active {
-  color: var(--foreground, #333);
-  border-bottom-color: var(--primary, #6366f1);
-  font-weight: 500;
-}
-
-.yaoyao-page {
-  width: 100%;
-  padding: 1.5rem;
-  max-width: 1200px;
-  margin: 0 auto;
-  box-sizing: border-box;
-}
-
-.yaoyao-header {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  flex-wrap: wrap;
-  gap: 0.75rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-header h2 {
-  margin: 0;
-  font-size: 1.4rem;
-  font-weight: 600;
-}
-
-.yaoyao-stats {
-  display: flex;
-  gap: 0.4rem;
-  flex-wrap: wrap;
-}
-
-.yaoyao-filters {
-  display: flex;
-  align-items: flex-end;
-  gap: 0.75rem;
-  flex-wrap: wrap;
-  margin-bottom: 1.25rem;
-  padding: 0.75rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.02));
-  border-radius: 0.5rem;
-}
-
-.yaoyao-filters label {
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-  margin-bottom: 0.15rem;
-  display: block;
-}
-
-.yaoyao-filters select,
-.yaoyao-filters input {
-  min-width: 100px;
-}
-
-.yaoyao-search {
-  display: flex;
-  gap: 0.4rem;
-  flex: 1;
-  min-width: 200px;
-}
-
-.yaoyao-search input {
-  flex: 1;
-}
-
-/* Grid */
-.yaoyao-grid {
-  display: grid;
-  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
-  gap: 0.75rem;
-}
-
-/* Card */
-.yaoyao-card {
-  overflow: hidden;
-}
-
-.yaoyao-card-content {
-  padding: 0.5rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-card-preview {
-  width: 100%;
-  aspect-ratio: 16 / 10;
-  background: rgba(0, 0, 0, 0.03);
-  border-radius: 0.4rem;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  overflow: hidden;
-}
-
-.yaoyao-thumb {
-  width: 100%;
-  height: 100%;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-}
-
-.yaoyao-thumb-img {
-  width: 100%;
-  height: 100%;
-  object-fit: cover;
-}
-
-.yaoyao-thumb-icon {
-  font-size: 2.5rem;
-  opacity: 0.5;
-}
-
-.yaoyao-thumb-loading {
-  font-size: 1.2rem;
-  opacity: 0.4;
-}
-
-.yaoyao-card-info {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-card-name {
-  font-size: 0.8rem;
-  font-weight: 500;
-  white-space: nowrap;
-  overflow: hidden;
-  text-overflow: ellipsis;
-}
-
-.yaoyao-card-meta {
-  display: flex;
-  align-items: center;
-  gap: 0.3rem;
-  flex-wrap: wrap;
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-card-size {
-  font-variant-numeric: tabular-nums;
-}
-
-.yaoyao-card-actions {
-  display: flex;
-  justify-content: flex-end;
-}
-
-/* States */
-.yaoyao-error {
-  padding: 0.75rem;
-  background: rgba(239, 68, 68, 0.1);
-  border-radius: 0.5rem;
-  color: #b91c1c;
-  font-size: 0.85rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-loading,
-.yaoyao-empty {
-  text-align: center;
-  padding: 3rem 1rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.95rem;
-}
-
-.yaoyao-sentinel {
-  text-align: center;
-  padding: 1.5rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.85rem;
-}
-
-/* Voice settings */
-.yaoyao-voice-card {
-  padding: 1rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-voice-row {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-voice-row label {
-  font-size: 0.8rem;
-  font-weight: 500;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-row select,
-.yaoyao-voice-row input[type="number"] {
-  max-width: 320px;
-}
-
-.yaoyao-voice-check {
-  flex-direction: row;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-check label {
-  display: flex;
-  align-items: center;
-  gap: 0.4rem;
-  cursor: pointer;
-  font-size: 0.85rem;
-  color: var(--foreground, #333);
-}
-
-.yaoyao-voice-actions {
-  display: flex;
-  gap: 0.5rem;
-  margin-top: 0.25rem;
-}
-
-.yaoyao-tts-textarea {
-  width: 100%;
-  max-width: 600px;
-  padding: 0.5rem;
-  border: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.12));
-  border-radius: 0.375rem;
-  font-size: 0.85rem;
-  resize: vertical;
-  background: var(--hermes-input-bg, transparent);
-  color: var(--foreground, inherit);
-  box-sizing: border-box;
-}
-
-.yaoyao-audio-player {
-  width: 100%;
-  max-width: 600px;
-  margin-top: 0.5rem;
-}
-
-.yaoyao-section-title {
-  margin: 0 0 0.25rem 0;
-  font-size: 1rem;
-  font-weight: 600;
-}
-
-.yaoyao-hint {
-  margin: 0 0 0.5rem 0;
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-agent-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-agent-item {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  padding: 0.3rem 0.5rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.03));
-  border-radius: 0.3rem;
-  font-size: 0.85rem;
-}
-
-.yaoyao-agent-add {
-  display: flex;
-  gap: 0.4rem;
-}
-
-/* Duplex voice status card */
-.yaoyao-duplex-status {
-  display: flex;
-  align-items: flex-start;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-duplex-icon {
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  width: 32px;
-  height: 32px;
-  flex-shrink: 0;
-  border: 1px solid var(--hermes-border, rgba(0,0,0,0.12));
-  border-radius: 0.3rem;
-  background: var(--hermes-card, rgba(0,0,0,0.03));
-  font-size: 0.8rem;
-  font-weight: 700;
-}
-
-.yaoyao-duplex-info {
-  min-width: 0;
-}
-
-.yaoyao-duplex-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-  margin-bottom: 0.25rem;
-}
-
-.yaoyao-duplex-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-duplex-meta {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  gap: 0.5rem 1rem;
-  font-size: 0.8rem;
-}
-
-.yaoyao-duplex-meta > div {
-  display: flex;
-  flex-direction: column;
-  gap: 0.1rem;
-}
-
-.yaoyao-meta-label {
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-switch {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor-row {
-  display: grid;
-  grid-template-columns: 0.85fr 1.15fr auto;
-  gap: 0.4rem;
-  align-items: center;
-}
-
-/* Provider cards */
-.yaoyao-provider-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 1.5rem;
-}
-
-.yaoyao-provider-card {
-  position: relative;
-  overflow: hidden;
-}
-
-.yaoyao-provider-card.yaoyao-provider-active::before {
-  content: '';
-  position: absolute;
-  inset: 0 auto 0 0;
-  width: 3px;
-  background: var(--primary, #6366f1);
-}
-
-.yaoyao-provider-header {
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-provider-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-provider-actions {
-  display: flex;
-  gap: 0.4rem;
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-fields {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}

+ 0 - 433
hermes-plugins/yaoyao/dashboard/dist/style.v1.2.0.css

@@ -1,433 +0,0 @@
-/* Yaoyao file library - dashboard plugin styles */
-
-.yaoyao-root {
-  width: 100%;
-}
-
-.yaoyao-tabs {
-  display: flex;
-  gap: 0.25rem;
-  padding: 0 1.5rem;
-  border-bottom: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.08));
-  max-width: 1200px;
-  margin: 0 auto;
-}
-
-.yaoyao-tab {
-  padding: 0.6rem 1rem;
-  border: none;
-  background: none;
-  cursor: pointer;
-  font-size: 0.9rem;
-  color: var(--muted-foreground, #888);
-  border-bottom: 2px solid transparent;
-  transition: color 0.15s, border-color 0.15s;
-}
-
-.yaoyao-tab:hover {
-  color: var(--foreground, #333);
-}
-
-.yaoyao-tab-active {
-  color: var(--foreground, #333);
-  border-bottom-color: var(--primary, #6366f1);
-  font-weight: 500;
-}
-
-.yaoyao-page {
-  width: 100%;
-  padding: 1.5rem;
-  max-width: 1200px;
-  margin: 0 auto;
-  box-sizing: border-box;
-}
-
-.yaoyao-header {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  flex-wrap: wrap;
-  gap: 0.75rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-header h2 {
-  margin: 0;
-  font-size: 1.4rem;
-  font-weight: 600;
-}
-
-.yaoyao-stats {
-  display: flex;
-  gap: 0.4rem;
-  flex-wrap: wrap;
-}
-
-.yaoyao-filters {
-  display: flex;
-  align-items: flex-end;
-  gap: 0.75rem;
-  flex-wrap: wrap;
-  margin-bottom: 1.25rem;
-  padding: 0.75rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.02));
-  border-radius: 0.5rem;
-}
-
-.yaoyao-filters label {
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-  margin-bottom: 0.15rem;
-  display: block;
-}
-
-.yaoyao-filters select,
-.yaoyao-filters input {
-  min-width: 100px;
-}
-
-.yaoyao-search {
-  display: flex;
-  gap: 0.4rem;
-  flex: 1;
-  min-width: 200px;
-}
-
-.yaoyao-search input {
-  flex: 1;
-}
-
-/* Grid */
-.yaoyao-grid {
-  display: grid;
-  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
-  gap: 0.75rem;
-}
-
-/* Card */
-.yaoyao-card {
-  overflow: hidden;
-}
-
-.yaoyao-card-content {
-  padding: 0.5rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-card-preview {
-  width: 100%;
-  aspect-ratio: 16 / 10;
-  background: rgba(0, 0, 0, 0.03);
-  border-radius: 0.4rem;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  overflow: hidden;
-}
-
-.yaoyao-thumb {
-  width: 100%;
-  height: 100%;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-}
-
-.yaoyao-thumb-img {
-  width: 100%;
-  height: 100%;
-  object-fit: cover;
-}
-
-.yaoyao-thumb-icon {
-  font-size: 2.5rem;
-  opacity: 0.5;
-}
-
-.yaoyao-thumb-loading {
-  font-size: 1.2rem;
-  opacity: 0.4;
-}
-
-.yaoyao-card-info {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-card-name {
-  font-size: 0.8rem;
-  font-weight: 500;
-  white-space: nowrap;
-  overflow: hidden;
-  text-overflow: ellipsis;
-}
-
-.yaoyao-card-meta {
-  display: flex;
-  align-items: center;
-  gap: 0.3rem;
-  flex-wrap: wrap;
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-card-size {
-  font-variant-numeric: tabular-nums;
-}
-
-.yaoyao-card-actions {
-  display: flex;
-  justify-content: flex-end;
-}
-
-/* States */
-.yaoyao-error {
-  padding: 0.75rem;
-  background: rgba(239, 68, 68, 0.1);
-  border-radius: 0.5rem;
-  color: #b91c1c;
-  font-size: 0.85rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-loading,
-.yaoyao-empty {
-  text-align: center;
-  padding: 3rem 1rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.95rem;
-}
-
-.yaoyao-sentinel {
-  text-align: center;
-  padding: 1.5rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.85rem;
-}
-
-/* Voice settings */
-.yaoyao-voice-card {
-  padding: 1rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-voice-row {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-voice-row label {
-  font-size: 0.8rem;
-  font-weight: 500;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-row select,
-.yaoyao-voice-row input[type="number"] {
-  max-width: 320px;
-}
-
-.yaoyao-voice-check {
-  flex-direction: row;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-check label {
-  display: flex;
-  align-items: center;
-  gap: 0.4rem;
-  cursor: pointer;
-  font-size: 0.85rem;
-  color: var(--foreground, #333);
-}
-
-.yaoyao-voice-actions {
-  display: flex;
-  gap: 0.5rem;
-  margin-top: 0.25rem;
-}
-
-.yaoyao-tts-textarea {
-  width: 100%;
-  max-width: 600px;
-  padding: 0.5rem;
-  border: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.12));
-  border-radius: 0.375rem;
-  font-size: 0.85rem;
-  resize: vertical;
-  background: var(--hermes-input-bg, transparent);
-  color: var(--foreground, inherit);
-  box-sizing: border-box;
-}
-
-.yaoyao-audio-player {
-  width: 100%;
-  max-width: 600px;
-  margin-top: 0.5rem;
-}
-
-.yaoyao-section-title {
-  margin: 0 0 0.25rem 0;
-  font-size: 1rem;
-  font-weight: 600;
-}
-
-.yaoyao-hint {
-  margin: 0 0 0.5rem 0;
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-agent-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-agent-item {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  padding: 0.3rem 0.5rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.03));
-  border-radius: 0.3rem;
-  font-size: 0.85rem;
-}
-
-.yaoyao-agent-add {
-  display: flex;
-  gap: 0.4rem;
-}
-
-/* Duplex voice status card */
-.yaoyao-duplex-status {
-  display: flex;
-  align-items: flex-start;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-duplex-icon {
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  width: 32px;
-  height: 32px;
-  flex-shrink: 0;
-  border: 1px solid var(--hermes-border, rgba(0,0,0,0.12));
-  border-radius: 0.3rem;
-  background: var(--hermes-card, rgba(0,0,0,0.03));
-  font-size: 0.8rem;
-  font-weight: 700;
-}
-
-.yaoyao-duplex-info {
-  min-width: 0;
-}
-
-.yaoyao-duplex-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-  margin-bottom: 0.25rem;
-}
-
-.yaoyao-duplex-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-duplex-meta {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  gap: 0.5rem 1rem;
-  font-size: 0.8rem;
-}
-
-.yaoyao-duplex-meta > div {
-  display: flex;
-  flex-direction: column;
-  gap: 0.1rem;
-}
-
-.yaoyao-meta-label {
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-switch {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor-row {
-  display: grid;
-  grid-template-columns: 0.85fr 1.15fr auto;
-  gap: 0.4rem;
-  align-items: center;
-}
-
-/* Provider cards */
-.yaoyao-provider-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 1.5rem;
-}
-
-.yaoyao-provider-card {
-  position: relative;
-  overflow: hidden;
-}
-
-.yaoyao-provider-card.yaoyao-provider-active::before {
-  content: '';
-  position: absolute;
-  inset: 0 auto 0 0;
-  width: 3px;
-  background: var(--primary, #6366f1);
-}
-
-.yaoyao-provider-header {
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-provider-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-provider-actions {
-  display: flex;
-  gap: 0.4rem;
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-fields {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}

+ 0 - 433
hermes-plugins/yaoyao/dashboard/dist/style.v1.3.0.css

@@ -1,433 +0,0 @@
-/* Yaoyao file library - dashboard plugin styles */
-
-.yaoyao-root {
-  width: 100%;
-}
-
-.yaoyao-tabs {
-  display: flex;
-  gap: 0.25rem;
-  padding: 0 1.5rem;
-  border-bottom: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.08));
-  max-width: 1200px;
-  margin: 0 auto;
-}
-
-.yaoyao-tab {
-  padding: 0.6rem 1rem;
-  border: none;
-  background: none;
-  cursor: pointer;
-  font-size: 0.9rem;
-  color: var(--muted-foreground, #888);
-  border-bottom: 2px solid transparent;
-  transition: color 0.15s, border-color 0.15s;
-}
-
-.yaoyao-tab:hover {
-  color: var(--foreground, #333);
-}
-
-.yaoyao-tab-active {
-  color: var(--foreground, #333);
-  border-bottom-color: var(--primary, #6366f1);
-  font-weight: 500;
-}
-
-.yaoyao-page {
-  width: 100%;
-  padding: 1.5rem;
-  max-width: 1200px;
-  margin: 0 auto;
-  box-sizing: border-box;
-}
-
-.yaoyao-header {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  flex-wrap: wrap;
-  gap: 0.75rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-header h2 {
-  margin: 0;
-  font-size: 1.4rem;
-  font-weight: 600;
-}
-
-.yaoyao-stats {
-  display: flex;
-  gap: 0.4rem;
-  flex-wrap: wrap;
-}
-
-.yaoyao-filters {
-  display: flex;
-  align-items: flex-end;
-  gap: 0.75rem;
-  flex-wrap: wrap;
-  margin-bottom: 1.25rem;
-  padding: 0.75rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.02));
-  border-radius: 0.5rem;
-}
-
-.yaoyao-filters label {
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-  margin-bottom: 0.15rem;
-  display: block;
-}
-
-.yaoyao-filters select,
-.yaoyao-filters input {
-  min-width: 100px;
-}
-
-.yaoyao-search {
-  display: flex;
-  gap: 0.4rem;
-  flex: 1;
-  min-width: 200px;
-}
-
-.yaoyao-search input {
-  flex: 1;
-}
-
-/* Grid */
-.yaoyao-grid {
-  display: grid;
-  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
-  gap: 0.75rem;
-}
-
-/* Card */
-.yaoyao-card {
-  overflow: hidden;
-}
-
-.yaoyao-card-content {
-  padding: 0.5rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-card-preview {
-  width: 100%;
-  aspect-ratio: 16 / 10;
-  background: rgba(0, 0, 0, 0.03);
-  border-radius: 0.4rem;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  overflow: hidden;
-}
-
-.yaoyao-thumb {
-  width: 100%;
-  height: 100%;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-}
-
-.yaoyao-thumb-img {
-  width: 100%;
-  height: 100%;
-  object-fit: cover;
-}
-
-.yaoyao-thumb-icon {
-  font-size: 2.5rem;
-  opacity: 0.5;
-}
-
-.yaoyao-thumb-loading {
-  font-size: 1.2rem;
-  opacity: 0.4;
-}
-
-.yaoyao-card-info {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-card-name {
-  font-size: 0.8rem;
-  font-weight: 500;
-  white-space: nowrap;
-  overflow: hidden;
-  text-overflow: ellipsis;
-}
-
-.yaoyao-card-meta {
-  display: flex;
-  align-items: center;
-  gap: 0.3rem;
-  flex-wrap: wrap;
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-card-size {
-  font-variant-numeric: tabular-nums;
-}
-
-.yaoyao-card-actions {
-  display: flex;
-  justify-content: flex-end;
-}
-
-/* States */
-.yaoyao-error {
-  padding: 0.75rem;
-  background: rgba(239, 68, 68, 0.1);
-  border-radius: 0.5rem;
-  color: #b91c1c;
-  font-size: 0.85rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-loading,
-.yaoyao-empty {
-  text-align: center;
-  padding: 3rem 1rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.95rem;
-}
-
-.yaoyao-sentinel {
-  text-align: center;
-  padding: 1.5rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.85rem;
-}
-
-/* Voice settings */
-.yaoyao-voice-card {
-  padding: 1rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-voice-row {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-voice-row label {
-  font-size: 0.8rem;
-  font-weight: 500;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-row select,
-.yaoyao-voice-row input[type="number"] {
-  max-width: 320px;
-}
-
-.yaoyao-voice-check {
-  flex-direction: row;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-check label {
-  display: flex;
-  align-items: center;
-  gap: 0.4rem;
-  cursor: pointer;
-  font-size: 0.85rem;
-  color: var(--foreground, #333);
-}
-
-.yaoyao-voice-actions {
-  display: flex;
-  gap: 0.5rem;
-  margin-top: 0.25rem;
-}
-
-.yaoyao-tts-textarea {
-  width: 100%;
-  max-width: 600px;
-  padding: 0.5rem;
-  border: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.12));
-  border-radius: 0.375rem;
-  font-size: 0.85rem;
-  resize: vertical;
-  background: var(--hermes-input-bg, transparent);
-  color: var(--foreground, inherit);
-  box-sizing: border-box;
-}
-
-.yaoyao-audio-player {
-  width: 100%;
-  max-width: 600px;
-  margin-top: 0.5rem;
-}
-
-.yaoyao-section-title {
-  margin: 0 0 0.25rem 0;
-  font-size: 1rem;
-  font-weight: 600;
-}
-
-.yaoyao-hint {
-  margin: 0 0 0.5rem 0;
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-agent-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-agent-item {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  padding: 0.3rem 0.5rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.03));
-  border-radius: 0.3rem;
-  font-size: 0.85rem;
-}
-
-.yaoyao-agent-add {
-  display: flex;
-  gap: 0.4rem;
-}
-
-/* Duplex voice status card */
-.yaoyao-duplex-status {
-  display: flex;
-  align-items: flex-start;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-duplex-icon {
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  width: 32px;
-  height: 32px;
-  flex-shrink: 0;
-  border: 1px solid var(--hermes-border, rgba(0,0,0,0.12));
-  border-radius: 0.3rem;
-  background: var(--hermes-card, rgba(0,0,0,0.03));
-  font-size: 0.8rem;
-  font-weight: 700;
-}
-
-.yaoyao-duplex-info {
-  min-width: 0;
-}
-
-.yaoyao-duplex-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-  margin-bottom: 0.25rem;
-}
-
-.yaoyao-duplex-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-duplex-meta {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  gap: 0.5rem 1rem;
-  font-size: 0.8rem;
-}
-
-.yaoyao-duplex-meta > div {
-  display: flex;
-  flex-direction: column;
-  gap: 0.1rem;
-}
-
-.yaoyao-meta-label {
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-switch {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor-row {
-  display: grid;
-  grid-template-columns: 0.85fr 1.15fr auto;
-  gap: 0.4rem;
-  align-items: center;
-}
-
-/* Provider cards */
-.yaoyao-provider-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 1.5rem;
-}
-
-.yaoyao-provider-card {
-  position: relative;
-  overflow: hidden;
-}
-
-.yaoyao-provider-card.yaoyao-provider-active::before {
-  content: '';
-  position: absolute;
-  inset: 0 auto 0 0;
-  width: 3px;
-  background: var(--primary, #6366f1);
-}
-
-.yaoyao-provider-header {
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-provider-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-provider-actions {
-  display: flex;
-  gap: 0.4rem;
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-fields {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}

+ 0 - 433
hermes-plugins/yaoyao/dashboard/dist/style.v1.4.0.css

@@ -1,433 +0,0 @@
-/* Yaoyao file library - dashboard plugin styles */
-
-.yaoyao-root {
-  width: 100%;
-}
-
-.yaoyao-tabs {
-  display: flex;
-  gap: 0.25rem;
-  padding: 0 1.5rem;
-  border-bottom: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.08));
-  max-width: 1200px;
-  margin: 0 auto;
-}
-
-.yaoyao-tab {
-  padding: 0.6rem 1rem;
-  border: none;
-  background: none;
-  cursor: pointer;
-  font-size: 0.9rem;
-  color: var(--muted-foreground, #888);
-  border-bottom: 2px solid transparent;
-  transition: color 0.15s, border-color 0.15s;
-}
-
-.yaoyao-tab:hover {
-  color: var(--foreground, #333);
-}
-
-.yaoyao-tab-active {
-  color: var(--foreground, #333);
-  border-bottom-color: var(--primary, #6366f1);
-  font-weight: 500;
-}
-
-.yaoyao-page {
-  width: 100%;
-  padding: 1.5rem;
-  max-width: 1200px;
-  margin: 0 auto;
-  box-sizing: border-box;
-}
-
-.yaoyao-header {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  flex-wrap: wrap;
-  gap: 0.75rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-header h2 {
-  margin: 0;
-  font-size: 1.4rem;
-  font-weight: 600;
-}
-
-.yaoyao-stats {
-  display: flex;
-  gap: 0.4rem;
-  flex-wrap: wrap;
-}
-
-.yaoyao-filters {
-  display: flex;
-  align-items: flex-end;
-  gap: 0.75rem;
-  flex-wrap: wrap;
-  margin-bottom: 1.25rem;
-  padding: 0.75rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.02));
-  border-radius: 0.5rem;
-}
-
-.yaoyao-filters label {
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-  margin-bottom: 0.15rem;
-  display: block;
-}
-
-.yaoyao-filters select,
-.yaoyao-filters input {
-  min-width: 100px;
-}
-
-.yaoyao-search {
-  display: flex;
-  gap: 0.4rem;
-  flex: 1;
-  min-width: 200px;
-}
-
-.yaoyao-search input {
-  flex: 1;
-}
-
-/* Grid */
-.yaoyao-grid {
-  display: grid;
-  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
-  gap: 0.75rem;
-}
-
-/* Card */
-.yaoyao-card {
-  overflow: hidden;
-}
-
-.yaoyao-card-content {
-  padding: 0.5rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-card-preview {
-  width: 100%;
-  aspect-ratio: 16 / 10;
-  background: rgba(0, 0, 0, 0.03);
-  border-radius: 0.4rem;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  overflow: hidden;
-}
-
-.yaoyao-thumb {
-  width: 100%;
-  height: 100%;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-}
-
-.yaoyao-thumb-img {
-  width: 100%;
-  height: 100%;
-  object-fit: cover;
-}
-
-.yaoyao-thumb-icon {
-  font-size: 2.5rem;
-  opacity: 0.5;
-}
-
-.yaoyao-thumb-loading {
-  font-size: 1.2rem;
-  opacity: 0.4;
-}
-
-.yaoyao-card-info {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-card-name {
-  font-size: 0.8rem;
-  font-weight: 500;
-  white-space: nowrap;
-  overflow: hidden;
-  text-overflow: ellipsis;
-}
-
-.yaoyao-card-meta {
-  display: flex;
-  align-items: center;
-  gap: 0.3rem;
-  flex-wrap: wrap;
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-card-size {
-  font-variant-numeric: tabular-nums;
-}
-
-.yaoyao-card-actions {
-  display: flex;
-  justify-content: flex-end;
-}
-
-/* States */
-.yaoyao-error {
-  padding: 0.75rem;
-  background: rgba(239, 68, 68, 0.1);
-  border-radius: 0.5rem;
-  color: #b91c1c;
-  font-size: 0.85rem;
-  margin-bottom: 1rem;
-}
-
-.yaoyao-loading,
-.yaoyao-empty {
-  text-align: center;
-  padding: 3rem 1rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.95rem;
-}
-
-.yaoyao-sentinel {
-  text-align: center;
-  padding: 1.5rem;
-  color: var(--muted-foreground, #888);
-  font-size: 0.85rem;
-}
-
-/* Voice settings */
-.yaoyao-voice-card {
-  padding: 1rem !important;
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-voice-row {
-  display: flex;
-  flex-direction: column;
-  gap: 0.25rem;
-}
-
-.yaoyao-voice-row label {
-  font-size: 0.8rem;
-  font-weight: 500;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-row select,
-.yaoyao-voice-row input[type="number"] {
-  max-width: 320px;
-}
-
-.yaoyao-voice-check {
-  flex-direction: row;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-check label {
-  display: flex;
-  align-items: center;
-  gap: 0.4rem;
-  cursor: pointer;
-  font-size: 0.85rem;
-  color: var(--foreground, #333);
-}
-
-.yaoyao-voice-actions {
-  display: flex;
-  gap: 0.5rem;
-  margin-top: 0.25rem;
-}
-
-.yaoyao-tts-textarea {
-  width: 100%;
-  max-width: 600px;
-  padding: 0.5rem;
-  border: 1px solid var(--hermes-border, rgba(0, 0, 0, 0.12));
-  border-radius: 0.375rem;
-  font-size: 0.85rem;
-  resize: vertical;
-  background: var(--hermes-input-bg, transparent);
-  color: var(--foreground, inherit);
-  box-sizing: border-box;
-}
-
-.yaoyao-audio-player {
-  width: 100%;
-  max-width: 600px;
-  margin-top: 0.5rem;
-}
-
-.yaoyao-section-title {
-  margin: 0 0 0.25rem 0;
-  font-size: 1rem;
-  font-weight: 600;
-}
-
-.yaoyao-hint {
-  margin: 0 0 0.5rem 0;
-  font-size: 0.75rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-agent-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.4rem;
-}
-
-.yaoyao-agent-item {
-  display: flex;
-  align-items: center;
-  justify-content: space-between;
-  padding: 0.3rem 0.5rem;
-  background: var(--hermes-card, rgba(0, 0, 0, 0.03));
-  border-radius: 0.3rem;
-  font-size: 0.85rem;
-}
-
-.yaoyao-agent-add {
-  display: flex;
-  gap: 0.4rem;
-}
-
-/* Duplex voice status card */
-.yaoyao-duplex-status {
-  display: flex;
-  align-items: flex-start;
-  gap: 0.75rem;
-  margin-bottom: 0.75rem;
-}
-
-.yaoyao-duplex-icon {
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  width: 32px;
-  height: 32px;
-  flex-shrink: 0;
-  border: 1px solid var(--hermes-border, rgba(0,0,0,0.12));
-  border-radius: 0.3rem;
-  background: var(--hermes-card, rgba(0,0,0,0.03));
-  font-size: 0.8rem;
-  font-weight: 700;
-}
-
-.yaoyao-duplex-info {
-  min-width: 0;
-}
-
-.yaoyao-duplex-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-  margin-bottom: 0.25rem;
-}
-
-.yaoyao-duplex-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-duplex-meta {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  gap: 0.5rem 1rem;
-  font-size: 0.8rem;
-}
-
-.yaoyao-duplex-meta > div {
-  display: flex;
-  flex-direction: column;
-  gap: 0.1rem;
-}
-
-.yaoyao-meta-label {
-  font-size: 0.7rem;
-  color: var(--muted-foreground, #888);
-}
-
-.yaoyao-voice-switch {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}
-
-.yaoyao-voice-editor-row {
-  display: grid;
-  grid-template-columns: 0.85fr 1.15fr auto;
-  gap: 0.4rem;
-  align-items: center;
-}
-
-/* Provider cards */
-.yaoyao-provider-list {
-  display: flex;
-  flex-direction: column;
-  gap: 0.75rem;
-  margin-bottom: 1.5rem;
-}
-
-.yaoyao-provider-card {
-  position: relative;
-  overflow: hidden;
-}
-
-.yaoyao-provider-card.yaoyao-provider-active::before {
-  content: '';
-  position: absolute;
-  inset: 0 auto 0 0;
-  width: 3px;
-  background: var(--primary, #6366f1);
-}
-
-.yaoyao-provider-header {
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-title-row {
-  display: flex;
-  align-items: center;
-  gap: 0.5rem;
-}
-
-.yaoyao-provider-title-row h5 {
-  margin: 0;
-  font-size: 0.9rem;
-  font-weight: 600;
-}
-
-.yaoyao-provider-actions {
-  display: flex;
-  gap: 0.4rem;
-  margin-bottom: 0.5rem;
-}
-
-.yaoyao-provider-fields {
-  display: flex;
-  flex-direction: column;
-  gap: 0.5rem;
-}

+ 0 - 2050
hermes-plugins/yaoyao/dashboard/group_gateway.py

@@ -1,2050 +0,0 @@
-"""Stable in-process adapter for the Hermes TUI Gateway JSON-RPC API."""
-
-from __future__ import annotations
-
-import copy
-import inspect
-import logging
-import math
-import threading
-import time
-import uuid
-from collections import deque
-from dataclasses import dataclass, field
-from functools import partial
-from pathlib import Path
-from typing import Any, Callable
-
-
-logger = logging.getLogger(__name__)
-
-_DELTA_EVENTS = frozenset({
-    "message.delta",
-    "reasoning.delta",
-    "thinking.delta",
-})
-_APPROVAL_CHOICES = frozenset({"once", "session", "always", "deny"})
-
-MAX_DELTA_BUFFER_BYTES = 64 * 1024
-MAX_CONTROL_PAYLOAD_BYTES = 256 * 1024
-MAX_TERMINAL_TEXT_BYTES = 64 * 1024
-MAX_SAFE_JSON_INTEGER = (1 << 53) - 1
-_MAX_DELTA_METADATA_BYTES = 16 * 1024
-_MAX_CONTROL_STRING_BYTES = 32 * 1024
-_MAX_DIAGNOSTIC_BYTES = 12 * 1024
-_MAX_SUMMARY_BYTES = 12 * 1024
-_MAX_PREVIEW_BYTES = 32 * 1024
-_MAX_TOOL_PREVIEW_BYTES = 16 * 1024
-_MAX_ROUTE_FIELD_BYTES = 4096
-_MAX_EVENT_TYPE_BYTES = 256
-_MAX_RUNTIME_ID_BYTES = 4096
-_MAX_JSON_DEPTH = 64
-_MAX_JSON_NODES = 100_000
-_MAX_JSON_INSPECTION_BYTES = 4 * 1024 * 1024
-_MAX_FINITE_JSON_FLOAT = 1.7976931348623157e308
-_SESSION_INFO_STRING_LIMITS = {
-    "model": _MAX_ROUTE_FIELD_BYTES,
-    "provider": _MAX_ROUTE_FIELD_BYTES,
-    "reasoning_effort": _MAX_ROUTE_FIELD_BYTES,
-    "service_tier": _MAX_ROUTE_FIELD_BYTES,
-    "approval_mode": _MAX_ROUTE_FIELD_BYTES,
-    "cwd": _MAX_CONTROL_STRING_BYTES,
-    "branch": _MAX_ROUTE_FIELD_BYTES,
-    "personality": _MAX_ROUTE_FIELD_BYTES,
-    "title": _MAX_DIAGNOSTIC_BYTES,
-    "stored_session_id": _MAX_ROUTE_FIELD_BYTES,
-    "version": _MAX_ROUTE_FIELD_BYTES,
-    "release_date": _MAX_ROUTE_FIELD_BYTES,
-    "update_command": _MAX_DIAGNOSTIC_BYTES,
-    "credential_warning": _MAX_DIAGNOSTIC_BYTES,
-    "profile_name": _MAX_ROUTE_FIELD_BYTES,
-}
-_SESSION_INFO_PREVIEW_LIMITS = {
-    "tools": _MAX_TOOL_PREVIEW_BYTES,
-    "skills": _MAX_TOOL_PREVIEW_BYTES,
-    "project": _MAX_SUMMARY_BYTES,
-    "usage": _MAX_SUMMARY_BYTES,
-    "mcp_servers": _MAX_TOOL_PREVIEW_BYTES,
-}
-_SESSION_INFO_BOOLEAN_FIELDS = ("running", "fast", "yolo")
-_SESSION_INFO_INTEGER_FIELDS = ("desktop_contract",)
-_SESSION_INFO_OPTIONAL_INTEGER_FIELDS = ("update_behind",)
-_SESSION_INFO_DROPPED_FIELDS = frozenset({"system_prompt"})
-_SESSION_INFO_EXACT_ROUTE_FIELDS = frozenset({
-    "stored_session_id",
-    "profile_name",
-    "cwd",
-})
-
-
-class GatewayError(RuntimeError):
-    """Base exception for the plugin's stable Gateway boundary."""
-
-
-class GatewayValidationError(GatewayError):
-    """A caller supplied an invalid Gateway argument."""
-
-
-class GatewayTransportClosed(GatewayError):
-    """The in-process transport was closed while a request was pending."""
-
-
-class GatewayTimeoutError(GatewayError):
-    """A Gateway request did not receive a response before its deadline."""
-
-    def __init__(self, method: str) -> None:
-        self.method = method
-        super().__init__(f"{method} timed out")
-
-
-class GatewayDispatchError(GatewayError):
-    """The core dispatcher failed synchronously."""
-
-    def __init__(self, method: str) -> None:
-        self.method = method
-        super().__init__(f"{method} dispatcher failed")
-
-
-class GatewayProtocolError(GatewayError):
-    """The core dispatcher returned a response outside the stable contract."""
-
-    def __init__(self, method: str, detail: str) -> None:
-        self.method = method
-        self.detail = detail
-        super().__init__(f"{method}: {detail}")
-
-
-class GatewayRPCError(GatewayError):
-    """A well-formed JSON-RPC error returned by the core Gateway."""
-
-    def __init__(
-        self,
-        method: str,
-        code: int,
-        rpc_message: str,
-        data: Any = None,
-    ) -> None:
-        self.method = method
-        self.code = code
-        self.rpc_message = rpc_message
-        self.data = data
-        # Do not place core-provided text/data in the display string. HTTP callers
-        # can safely surface this exception without disclosing internal details.
-        super().__init__(f"{method} RPC failed ({code})")
-
-
-@dataclass(frozen=True)
-class SessionIdentity:
-    """Persistent and process-local identities returned by session operations."""
-
-    stored_id: str
-    runtime_id: str
-    running: bool
-
-
-@dataclass
-class _ResponseWaiter:
-    request_id: str
-    method: str
-    on_late_response: Callable[[str, dict[str, Any]], None] | None = None
-    event: threading.Event = field(default_factory=threading.Event)
-    response: dict[str, Any] | None = None
-    error: BaseException | None = None
-
-
-@dataclass(frozen=True)
-class _LateResponseTombstone:
-    method: str
-    expires_at: float
-    callback: Callable[[str, dict[str, Any]], None]
-
-
-@dataclass(frozen=True)
-class _LateSessionContext:
-    request_id: str
-    method: str
-    profile: str
-    requested_stored_id: str | None
-    adoption_generation: int
-
-
-@dataclass(frozen=True)
-class _JsonInspection:
-    valid: bool
-    encoded_bytes: int
-    reason: str = ""
-
-
-@dataclass
-class _QueuedEvent:
-    runtime_id: str
-    event_type: str
-    payload: dict[str, Any]
-    delta_key: tuple[str, str] | None = None
-    delta_bytes: int = 0
-
-
-EventCallback = Callable[..., None]
-Dispatcher = Callable[[dict[str, Any], "GroupGatewayTransport"], dict[str, Any] | None]
-
-
-def _is_safe_json_integer(value: Any) -> bool:
-    """Return whether an exact integer round-trips through IEEE-754 JSON peers."""
-
-    return (
-        type(value) is int
-        and value.bit_length() <= MAX_SAFE_JSON_INTEGER.bit_length()
-        and -MAX_SAFE_JSON_INTEGER <= value <= MAX_SAFE_JSON_INTEGER
-    )
-
-
-def _is_safe_json_float(value: Any) -> bool:
-    """Return whether an exact float is a finite JSON-interoperable scalar."""
-
-    return (
-        type(value) is float
-        and math.isfinite(value)
-        and abs(value) <= _MAX_FINITE_JSON_FLOAT
-    )
-
-
-def _is_safe_json_scalar(value: Any) -> bool:
-    return (
-        value is None
-        or type(value) is bool
-        or _is_safe_json_integer(value)
-        or _is_safe_json_float(value)
-    )
-
-
-def _inspect_json_payload(value: Any) -> _JsonInspection:
-    """Validate strict JSON and measure its UTF-8 encoding without serializing."""
-
-    encoded_bytes = 0
-    nodes = 0
-    ancestors: set[int] = set()
-    failure_reason = ""
-
-    def consume(size: int) -> bool:
-        nonlocal encoded_bytes, failure_reason
-        encoded_bytes += size
-        if encoded_bytes > _MAX_JSON_INSPECTION_BYTES:
-            failure_reason = "payload exceeds inspection budget"
-            return False
-        return True
-
-    def string_size(text: str) -> int | None:
-        nonlocal failure_reason
-        if len(text) > _MAX_JSON_INSPECTION_BYTES:
-            failure_reason = "string exceeds inspection budget"
-            return None
-        size = 2
-        for character in text:
-            codepoint = ord(character)
-            if 0xD800 <= codepoint <= 0xDFFF:
-                failure_reason = "string contains an invalid Unicode surrogate"
-                return None
-            if character in {'"', "\\"}:
-                size += 2
-            elif codepoint <= 0x1F:
-                size += 6
-            else:
-                size += len(character.encode("utf-8"))
-            if size > _MAX_JSON_INSPECTION_BYTES:
-                failure_reason = "string exceeds inspection budget"
-                return None
-        return size
-
-    def walk(item: Any, depth: int) -> bool:
-        nonlocal nodes, failure_reason
-        nodes += 1
-        if nodes > _MAX_JSON_NODES:
-            failure_reason = "payload contains too many JSON nodes"
-            return False
-        if depth > _MAX_JSON_DEPTH:
-            failure_reason = "payload exceeds the JSON depth limit"
-            return False
-        if item is None:
-            return consume(4)
-        if type(item) is bool:
-            return consume(4 if item else 5)
-        if type(item) is int:
-            if not _is_safe_json_integer(item):
-                failure_reason = "integer exceeds the interoperable JSON range"
-                return False
-            return consume(len(str(item)))
-        if type(item) is float:
-            if not _is_safe_json_float(item):
-                failure_reason = "float is outside the finite JSON range"
-                return False
-            return consume(len(repr(item)))
-        if isinstance(item, str):
-            encoded_size = string_size(item)
-            return encoded_size is not None and consume(encoded_size)
-        if isinstance(item, list):
-            identity = id(item)
-            if identity in ancestors:
-                failure_reason = "cyclic list is not JSON"
-                return False
-            if not consume(2 + max(0, len(item) - 1)):
-                return False
-            ancestors.add(identity)
-            try:
-                return all(walk(child, depth + 1) for child in item)
-            finally:
-                ancestors.remove(identity)
-        if isinstance(item, dict):
-            identity = id(item)
-            if identity in ancestors:
-                failure_reason = "cyclic object is not JSON"
-                return False
-            if not consume(2 + max(0, len(item) - 1)):
-                return False
-            ancestors.add(identity)
-            try:
-                for key, child in item.items():
-                    if not isinstance(key, str):
-                        failure_reason = "JSON object keys must be strings"
-                        return False
-                    encoded_size = string_size(key)
-                    if encoded_size is None or not consume(encoded_size + 1):
-                        return False
-                    if not walk(child, depth + 1):
-                        return False
-                return True
-            finally:
-                ancestors.remove(identity)
-        failure_reason = "payload contains a non-JSON value"
-        return False
-
-    try:
-        valid = walk(value, 0)
-    except Exception:  # noqa: BLE001 - malformed core payloads are rejected
-        return _JsonInspection(False, encoded_bytes, "payload validation failed")
-    return _JsonInspection(valid, encoded_bytes, failure_reason)
-
-
-def _json_payload_within_limit(value: Any, limit: int) -> bool:
-    inspection = _inspect_json_payload(value)
-    return inspection.valid and inspection.encoded_bytes <= limit
-
-
-def _utf8_chunks(text: str, limit: int):
-    """Yield non-empty codepoint-safe chunks no larger than ``limit`` bytes."""
-
-    if not text:
-        yield "", 0
-        return
-    characters: list[str] = []
-    encoded_bytes = 0
-    for character in text:
-        character_bytes = len(character.encode("utf-8"))
-        if characters and encoded_bytes + character_bytes > limit:
-            yield "".join(characters), encoded_bytes
-            characters = []
-            encoded_bytes = 0
-        characters.append(character)
-        encoded_bytes += character_bytes
-    if characters:
-        yield "".join(characters), encoded_bytes
-
-
-def _bounded_utf8(text: str, limit: int) -> bool:
-    if len(text) > limit:
-        return False
-    try:
-        return len(text.encode("utf-8")) <= limit
-    except UnicodeError:
-        return False
-
-
-def _utf8_prefix(text: str, limit: int) -> tuple[str, bool]:
-    characters: list[str] = []
-    encoded_bytes = 0
-    try:
-        for character in text:
-            character_bytes = len(character.encode("utf-8"))
-            if encoded_bytes + character_bytes > limit:
-                return "".join(characters), True
-            characters.append(character)
-            encoded_bytes += character_bytes
-    except UnicodeError:
-        return "".join(characters), True
-    return text, False
-
-
-def _json_string_prefix(text: str, limit: int) -> tuple[str, bool]:
-    """Bound a string by its strict UTF-8 JSON encoding, including escapes."""
-
-    characters: list[str] = []
-    encoded_bytes = 2  # Opening and closing quotes.
-    for character in text:
-        codepoint = ord(character)
-        if 0xD800 <= codepoint <= 0xDFFF:
-            return "".join(characters), True
-        if character in {'"', "\\"}:
-            character_bytes = 2
-        elif codepoint <= 0x1F:
-            character_bytes = 6
-        else:
-            character_bytes = len(character.encode("utf-8"))
-        if encoded_bytes + character_bytes > limit:
-            return "".join(characters), True
-        characters.append(character)
-        encoded_bytes += character_bytes
-    return text, False
-
-
-def _contains_control_character(text: str) -> bool:
-    return any(
-        ord(character) <= 0x1F or ord(character) == 0x7F
-        for character in text
-    )
-
-
-@dataclass
-class _PreviewBudget:
-    remaining_bytes: int
-    remaining_nodes: int = 128
-    truncated: bool = False
-
-
-def _bounded_json_preview(value: Any, limit: int) -> tuple[Any, bool]:
-    if _json_payload_within_limit(value, limit):
-        try:
-            return copy.deepcopy(value), False
-        except Exception:  # noqa: BLE001 - fall through to the safe projector
-            pass
-
-    budget = _PreviewBudget(limit)
-
-    def walk(item: Any, depth: int) -> Any:
-        budget.remaining_nodes -= 1
-        if budget.remaining_nodes < 0 or depth > 4:
-            budget.truncated = True
-            return "<truncated>"
-        if item is None or type(item) is bool:
-            return item
-        if type(item) is int:
-            if _is_safe_json_integer(item):
-                return item
-            budget.truncated = True
-            return "<integer outside safe JSON range>"
-        if type(item) is float:
-            if _is_safe_json_float(item):
-                return item
-            budget.truncated = True
-            return "<float outside finite JSON range>"
-        if isinstance(item, str):
-            per_string_limit = min(8192, max(0, budget.remaining_bytes))
-            projected, truncated = _utf8_prefix(item, per_string_limit)
-            budget.remaining_bytes -= len(projected.encode("utf-8"))
-            budget.truncated = budget.truncated or truncated
-            return projected
-        if isinstance(item, list):
-            projected_items = []
-            for child in item[:32]:
-                projected_items.append(walk(child, depth + 1))
-            if len(item) > len(projected_items):
-                budget.truncated = True
-            return projected_items
-        if isinstance(item, dict):
-            projected_object: dict[str, Any] = {}
-            for index, (key, child) in enumerate(item.items()):
-                if index >= 32 or budget.remaining_nodes <= 0:
-                    budget.truncated = True
-                    break
-                if not isinstance(key, str):
-                    budget.truncated = True
-                    continue
-                projected_key, key_truncated = _utf8_prefix(key, 256)
-                if not projected_key or projected_key in projected_object:
-                    budget.truncated = True
-                    continue
-                budget.truncated = budget.truncated or key_truncated
-                projected_object[projected_key] = walk(child, depth + 1)
-            return projected_object
-        budget.truncated = True
-        return "<invalid value>"
-
-    projected = walk(value, 0)
-    if not _json_payload_within_limit(projected, limit):
-        return "<preview omitted>", True
-    return projected, True
-
-
-def _copy_bounded_string(
-    source: dict[str, Any],
-    target: dict[str, Any],
-    field_name: str,
-    limit: int,
-    truncated_fields: list[str],
-) -> None:
-    if field_name not in source:
-        return
-    value = source[field_name]
-    if not isinstance(value, str):
-        truncated_fields.append(field_name)
-        return
-    projected, truncated = _utf8_prefix(value, limit)
-    target[field_name] = projected
-    if truncated:
-        truncated_fields.append(field_name)
-
-
-def _copy_bounded_preview(
-    source: dict[str, Any],
-    target: dict[str, Any],
-    field_name: str,
-    limit: int,
-    truncated_fields: list[str],
-) -> None:
-    if field_name not in source:
-        return
-    projected, truncated = _bounded_json_preview(source[field_name], limit)
-    target[field_name] = projected
-    if truncated:
-        truncated_fields.append(field_name)
-
-
-def _copy_scalar_fields(
-    source: dict[str, Any],
-    target: dict[str, Any],
-    fields: tuple[str, ...],
-    invalid_fields: list[str],
-) -> None:
-    for field_name in fields:
-        if field_name not in source:
-            continue
-        value = source[field_name]
-        if _is_safe_json_scalar(value):
-            target[field_name] = value
-        else:
-            invalid_fields.append(field_name)
-
-
-def _is_session_info_scalar_valid(field_name: str, value: Any) -> bool:
-    if field_name in _SESSION_INFO_BOOLEAN_FIELDS:
-        return type(value) is bool
-    if field_name in _SESSION_INFO_INTEGER_FIELDS:
-        return _is_safe_json_integer(value)
-    if field_name in _SESSION_INFO_OPTIONAL_INTEGER_FIELDS:
-        return value is None or _is_safe_json_integer(value)
-    return False
-
-
-def _copy_session_info_scalars(
-    source: dict[str, Any],
-    target: dict[str, Any],
-    invalid_fields: list[str],
-) -> None:
-    scalar_fields = (
-        *_SESSION_INFO_BOOLEAN_FIELDS,
-        *_SESSION_INFO_INTEGER_FIELDS,
-        *_SESSION_INFO_OPTIONAL_INTEGER_FIELDS,
-    )
-    for field_name in scalar_fields:
-        if field_name not in source:
-            continue
-        value = source[field_name]
-        if _is_session_info_scalar_valid(field_name, value):
-            target[field_name] = value
-        else:
-            invalid_fields.append(field_name)
-
-
-def _copy_session_info_string(
-    source: dict[str, Any],
-    target: dict[str, Any],
-    field_name: str,
-    limit: int,
-    truncated_fields: list[str],
-    invalid_fields: list[str],
-) -> None:
-    if field_name not in source:
-        return
-    value = source[field_name]
-    if not isinstance(value, str):
-        invalid_fields.append(field_name)
-        return
-    if field_name in _SESSION_INFO_EXACT_ROUTE_FIELDS:
-        if _contains_control_character(value):
-            invalid_fields.append(field_name)
-            return
-        if not _json_payload_within_limit(value, limit):
-            truncated_fields.append(field_name)
-            return
-        target[field_name] = value
-        return
-    projected, truncated = _json_string_prefix(value, limit)
-    target[field_name] = projected
-    if truncated:
-        truncated_fields.append(field_name)
-
-
-def _append_dropped_fields(
-    source: dict[str, Any],
-    selected: set[str],
-    truncated_fields: list[str],
-) -> None:
-    for field_name in source:
-        if not isinstance(field_name, str) or field_name in selected:
-            continue
-        if len(truncated_fields) >= 64:
-            break
-        projected_name, _truncated = _utf8_prefix(field_name, 256)
-        if projected_name:
-            truncated_fields.append(projected_name)
-
-
-def _mark_projected_control(
-    payload: dict[str, Any],
-    inspection: _JsonInspection,
-    truncated_fields: list[str],
-    invalid_fields: list[str],
-) -> dict[str, Any]:
-    if inspection.valid:
-        payload["transportTruncated"] = True
-        payload["originalBytes"] = inspection.encoded_bytes
-        payload["transportWarning"] = "Gateway control payload was safely truncated"
-    else:
-        payload["transportInvalidPayload"] = True
-        payload["transportWarning"] = (
-            "Gateway control payload was invalid and safely projected"
-        )
-    unique_fields = list(dict.fromkeys(truncated_fields))[:64]
-    if unique_fields:
-        payload["truncatedFields"] = unique_fields
-    unique_invalid_fields = list(dict.fromkeys(invalid_fields))[:64]
-    if unique_invalid_fields:
-        payload["invalidFields"] = unique_invalid_fields
-    return payload
-
-
-def _project_message_control(
-    source: dict[str, Any],
-    inspection: _JsonInspection,
-) -> dict[str, Any]:
-    projected: dict[str, Any] = {}
-    truncated_fields: list[str] = []
-    invalid_fields: list[str] = []
-    string_limits = {
-        "status": 256,
-        "text": MAX_TERMINAL_TEXT_BYTES,
-        "reasoning": MAX_TERMINAL_TEXT_BYTES,
-        "error": _MAX_DIAGNOSTIC_BYTES,
-        "failure_reason": _MAX_DIAGNOSTIC_BYTES,
-        "warning": _MAX_DIAGNOSTIC_BYTES,
-        "message": _MAX_DIAGNOSTIC_BYTES,
-    }
-    for field_name, limit in string_limits.items():
-        _copy_bounded_string(source, projected, field_name, limit, truncated_fields)
-    _copy_scalar_fields(
-        source,
-        projected,
-        ("recoverable", "partial", "response_previewed"),
-        invalid_fields,
-    )
-    for field_name in ("usage", "billing"):
-        _copy_bounded_preview(
-            source, projected, field_name, _MAX_SUMMARY_BYTES, truncated_fields
-        )
-    selected = set(string_limits) | {
-        "recoverable",
-        "partial",
-        "response_previewed",
-        "usage",
-        "billing",
-    }
-    _append_dropped_fields(source, selected, truncated_fields)
-    return _mark_projected_control(
-        projected, inspection, truncated_fields, invalid_fields
-    )
-
-
-def _project_interaction_control(
-    source: dict[str, Any],
-    inspection: _JsonInspection,
-) -> dict[str, Any]:
-    projected: dict[str, Any] = {}
-    truncated_fields: list[str] = []
-    invalid_fields: list[str] = []
-    string_limits = {
-        "request_id": _MAX_ROUTE_FIELD_BYTES,
-        "interaction_id": _MAX_ROUTE_FIELD_BYTES,
-        "question": _MAX_CONTROL_STRING_BYTES,
-        "command": _MAX_CONTROL_STRING_BYTES,
-        "reason": _MAX_DIAGNOSTIC_BYTES,
-        "message": _MAX_DIAGNOSTIC_BYTES,
-        "description": _MAX_DIAGNOSTIC_BYTES,
-        "tool": _MAX_ROUTE_FIELD_BYTES,
-        "name": _MAX_ROUTE_FIELD_BYTES,
-    }
-    for field_name, limit in string_limits.items():
-        _copy_bounded_string(source, projected, field_name, limit, truncated_fields)
-    for field_name in ("choices", "flags"):
-        _copy_bounded_preview(
-            source, projected, field_name, _MAX_PREVIEW_BYTES, truncated_fields
-        )
-    scalar_fields = (
-        "allow_permanent",
-        "smart_denied",
-        "multi_select",
-        "redacted",
-        "all",
-    )
-    _copy_scalar_fields(source, projected, scalar_fields, invalid_fields)
-    selected = set(string_limits) | {"choices", "flags", *scalar_fields}
-    _append_dropped_fields(source, selected, truncated_fields)
-    return _mark_projected_control(
-        projected, inspection, truncated_fields, invalid_fields
-    )
-
-
-def _project_tool_control(
-    source: dict[str, Any],
-    inspection: _JsonInspection,
-) -> dict[str, Any]:
-    projected: dict[str, Any] = {}
-    truncated_fields: list[str] = []
-    invalid_fields: list[str] = []
-    string_limits = {
-        "tool_id": _MAX_ROUTE_FIELD_BYTES,
-        "id": _MAX_ROUTE_FIELD_BYTES,
-        "name": _MAX_ROUTE_FIELD_BYTES,
-        "status": 256,
-        "risk": _MAX_ROUTE_FIELD_BYTES,
-        "summary": _MAX_SUMMARY_BYTES,
-        "context": _MAX_SUMMARY_BYTES,
-        "error": _MAX_DIAGNOSTIC_BYTES,
-        "warning": _MAX_DIAGNOSTIC_BYTES,
-        "args_text": _MAX_TOOL_PREVIEW_BYTES,
-        "result_text": _MAX_TOOL_PREVIEW_BYTES,
-        "inline_diff": _MAX_TOOL_PREVIEW_BYTES,
-    }
-    for field_name, limit in string_limits.items():
-        _copy_bounded_string(source, projected, field_name, limit, truncated_fields)
-    for field_name in ("args", "result", "findings", "todos", "metadata"):
-        _copy_bounded_preview(
-            source, projected, field_name, _MAX_TOOL_PREVIEW_BYTES, truncated_fields
-        )
-    scalar_fields = ("redacted", "duration_s", "progress")
-    _copy_scalar_fields(source, projected, scalar_fields, invalid_fields)
-    selected = set(string_limits) | {
-        "args",
-        "result",
-        "findings",
-        "todos",
-        "metadata",
-        *scalar_fields,
-    }
-    _append_dropped_fields(source, selected, truncated_fields)
-    return _mark_projected_control(
-        projected, inspection, truncated_fields, invalid_fields
-    )
-
-
-def _project_session_info_control(
-    source: dict[str, Any],
-    inspection: _JsonInspection,
-) -> dict[str, Any]:
-    """Keep session routing and settle state when diagnostics exceed the wire cap."""
-
-    projected: dict[str, Any] = {}
-    truncated_fields: list[str] = []
-    invalid_fields: list[str] = []
-    for field_name, limit in _SESSION_INFO_STRING_LIMITS.items():
-        _copy_session_info_string(
-            source,
-            projected,
-            field_name,
-            limit,
-            truncated_fields,
-            invalid_fields,
-        )
-    _copy_session_info_scalars(source, projected, invalid_fields)
-    for field_name, limit in _SESSION_INFO_PREVIEW_LIMITS.items():
-        _copy_bounded_preview(
-            source, projected, field_name, limit, truncated_fields
-        )
-    for field_name in _SESSION_INFO_DROPPED_FIELDS:
-        if field_name in source:
-            truncated_fields.append(field_name)
-    selected = (
-        set(_SESSION_INFO_STRING_LIMITS)
-        | set(_SESSION_INFO_PREVIEW_LIMITS)
-        | set(_SESSION_INFO_BOOLEAN_FIELDS)
-        | set(_SESSION_INFO_INTEGER_FIELDS)
-        | set(_SESSION_INFO_OPTIONAL_INTEGER_FIELDS)
-        | set(_SESSION_INFO_DROPPED_FIELDS)
-    )
-    _append_dropped_fields(source, selected, truncated_fields)
-    marked = _mark_projected_control(
-        projected, inspection, truncated_fields, invalid_fields
-    )
-    if invalid_fields:
-        marked["transportInvalidPayload"] = True
-    return marked
-
-
-def _control_payload_sentinel(inspection: _JsonInspection) -> dict[str, Any]:
-    if not inspection.valid:
-        return {
-            "transportInvalidPayload": True,
-            "transportWarning": "Gateway control payload was invalid and replaced",
-        }
-    return {
-        "transportTruncated": True,
-        "originalBytes": inspection.encoded_bytes,
-        "transportWarning": "Gateway control payload was replaced at the size limit",
-    }
-
-
-def _sanitize_control_payload(
-    event_type: str,
-    source: Any,
-    inspection: _JsonInspection,
-) -> dict[str, Any]:
-    if not isinstance(source, dict):
-        return _control_payload_sentinel(inspection)
-    if event_type == "session.info":
-        projected = _project_session_info_control(source, inspection)
-    elif (
-        event_type == "message.complete"
-        or event_type == "error"
-        or event_type.endswith((".error", ".failed"))
-    ):
-        projected = _project_message_control(source, inspection)
-    elif event_type == "approval.request" or event_type in {
-        "clarify.request",
-        "clarify.expire",
-    }:
-        projected = _project_interaction_control(source, inspection)
-    elif event_type.startswith("tool."):
-        projected = _project_tool_control(source, inspection)
-    else:
-        return _control_payload_sentinel(inspection)
-
-    if _json_payload_within_limit(projected, MAX_CONTROL_PAYLOAD_BYTES):
-        return projected
-    logger.error("Gateway control projection exceeded its hard byte limit")
-    return _control_payload_sentinel(
-        _JsonInspection(False, inspection.encoded_bytes, "projection exceeded limit")
-    )
-
-
-def _control_requires_projection(
-    event_type: str,
-    source: Any,
-    inspection: _JsonInspection,
-) -> bool:
-    if (
-        not isinstance(source, dict)
-        or not inspection.valid
-        or inspection.encoded_bytes > MAX_CONTROL_PAYLOAD_BYTES
-    ):
-        return True
-    limits: dict[str, int] = {}
-    preview_limits: dict[str, int] = {}
-    scalar_fields: tuple[str, ...] = ()
-    typed_session_info_scalars = False
-    if event_type == "session.info":
-        limits = _SESSION_INFO_STRING_LIMITS
-        preview_limits = _SESSION_INFO_PREVIEW_LIMITS
-        typed_session_info_scalars = True
-    elif (
-        event_type == "message.complete"
-        or event_type == "error"
-        or event_type.endswith((".error", ".failed"))
-    ):
-        limits = {
-            "status": 256,
-            "text": MAX_TERMINAL_TEXT_BYTES,
-            "reasoning": MAX_TERMINAL_TEXT_BYTES,
-            "error": _MAX_DIAGNOSTIC_BYTES,
-            "failure_reason": _MAX_DIAGNOSTIC_BYTES,
-            "warning": _MAX_DIAGNOSTIC_BYTES,
-            "message": _MAX_DIAGNOSTIC_BYTES,
-        }
-        preview_limits = {"usage": _MAX_SUMMARY_BYTES, "billing": _MAX_SUMMARY_BYTES}
-        scalar_fields = ("recoverable", "partial", "response_previewed")
-    elif event_type == "approval.request" or event_type in {
-        "clarify.request",
-        "clarify.expire",
-    }:
-        limits = {
-            "request_id": _MAX_ROUTE_FIELD_BYTES,
-            "interaction_id": _MAX_ROUTE_FIELD_BYTES,
-            "question": _MAX_CONTROL_STRING_BYTES,
-            "command": _MAX_CONTROL_STRING_BYTES,
-            "reason": _MAX_DIAGNOSTIC_BYTES,
-            "message": _MAX_DIAGNOSTIC_BYTES,
-            "description": _MAX_DIAGNOSTIC_BYTES,
-            "tool": _MAX_ROUTE_FIELD_BYTES,
-            "name": _MAX_ROUTE_FIELD_BYTES,
-        }
-        preview_limits = {
-            "choices": _MAX_PREVIEW_BYTES,
-            "flags": _MAX_PREVIEW_BYTES,
-        }
-        scalar_fields = (
-            "allow_permanent",
-            "smart_denied",
-            "multi_select",
-            "redacted",
-            "all",
-        )
-    elif event_type.startswith("tool."):
-        limits = {
-            "tool_id": _MAX_ROUTE_FIELD_BYTES,
-            "id": _MAX_ROUTE_FIELD_BYTES,
-            "name": _MAX_ROUTE_FIELD_BYTES,
-            "status": 256,
-            "risk": _MAX_ROUTE_FIELD_BYTES,
-            "summary": _MAX_SUMMARY_BYTES,
-            "context": _MAX_SUMMARY_BYTES,
-            "error": _MAX_DIAGNOSTIC_BYTES,
-            "warning": _MAX_DIAGNOSTIC_BYTES,
-            "args_text": _MAX_TOOL_PREVIEW_BYTES,
-            "result_text": _MAX_TOOL_PREVIEW_BYTES,
-            "inline_diff": _MAX_TOOL_PREVIEW_BYTES,
-        }
-        preview_limits = {
-            field_name: _MAX_TOOL_PREVIEW_BYTES
-            for field_name in ("args", "result", "findings", "todos", "metadata")
-        }
-        scalar_fields = ("redacted", "duration_s", "progress")
-    for field_name, limit in limits.items():
-        if field_name not in source:
-            continue
-        value = source[field_name]
-        if not isinstance(value, str):
-            return True
-        if event_type == "session.info":
-            if (
-                field_name in _SESSION_INFO_EXACT_ROUTE_FIELDS
-                and _contains_control_character(value)
-            ):
-                return True
-            if not _json_payload_within_limit(value, limit):
-                return True
-        elif not _bounded_utf8(value, limit):
-            return True
-    if any(
-        field_name in source
-        and not _json_payload_within_limit(source[field_name], limit)
-        for field_name, limit in preview_limits.items()
-    ):
-        return True
-    if typed_session_info_scalars:
-        typed_fields = (
-            *_SESSION_INFO_BOOLEAN_FIELDS,
-            *_SESSION_INFO_INTEGER_FIELDS,
-            *_SESSION_INFO_OPTIONAL_INTEGER_FIELDS,
-        )
-        return any(
-            field_name in source
-            and not _is_session_info_scalar_valid(field_name, source[field_name])
-            for field_name in typed_fields
-        )
-    return any(
-        field_name in source and not _is_safe_json_scalar(source[field_name])
-        for field_name in scalar_fields
-    )
-
-
-class GroupGatewayTransport:
-    """Thread-safe response router and bounded serial event transport."""
-
-    def __init__(
-        self,
-        on_event: EventCallback,
-        *,
-        max_control_frames: int = 128,
-        late_response_ttl: float = 30.0,
-        max_late_responses: int = 128,
-    ) -> None:
-        if not callable(on_event):
-            raise GatewayValidationError("on_event must be callable")
-        if (
-            isinstance(max_control_frames, bool)
-            or not isinstance(max_control_frames, int)
-            or max_control_frames < 1
-        ):
-            raise GatewayValidationError(
-                "max_control_frames must be a positive integer"
-            )
-        if (
-            isinstance(late_response_ttl, bool)
-            or not isinstance(late_response_ttl, (int, float))
-            or not math.isfinite(late_response_ttl)
-            or late_response_ttl <= 0
-        ):
-            raise GatewayValidationError("late_response_ttl must be positive")
-        if (
-            isinstance(max_late_responses, bool)
-            or not isinstance(max_late_responses, int)
-            or max_late_responses < 1
-        ):
-            raise GatewayValidationError(
-                "max_late_responses must be a positive integer"
-            )
-
-        self._on_event = self._normalize_callback(on_event)
-        self._max_queued_frames = max_control_frames
-        self._late_response_ttl = float(late_response_ttl)
-        self._max_late_responses = max_late_responses
-        self._condition = threading.Condition(threading.RLock())
-        self._closed = False
-        self._waiters: dict[str, _ResponseWaiter] = {}
-        self._tombstones: dict[str, _LateResponseTombstone] = {}
-        self._events: deque[_QueuedEvent] = deque()
-        self._callback_active = False
-        self._worker = threading.Thread(
-            target=self._event_worker,
-            name="yaoyao-group-gateway-events",
-            daemon=True,
-        )
-        self._worker.start()
-
-    @staticmethod
-    def _normalize_callback(on_event: EventCallback) -> EventCallback:
-        try:
-            signature = inspect.signature(on_event)
-        except (TypeError, ValueError):
-            return on_event
-        try:
-            signature.bind("runtime", "event.type", {})
-        except TypeError:
-            try:
-                signature.bind("runtime", {"type": "event.type", "payload": {}})
-            except TypeError as exc:
-                raise GatewayValidationError(
-                    "on_event must accept either two or three positional arguments"
-                ) from exc
-
-            def design_callback(
-                runtime_id: str, event_type: str, payload: dict[str, Any]
-            ) -> None:
-                on_event(runtime_id, {"type": event_type, "payload": payload})
-
-            return design_callback
-        return on_event
-
-    @property
-    def closed(self) -> bool:
-        with self._condition:
-            return self._closed
-
-    @property
-    def pending_waiter_count(self) -> int:
-        with self._condition:
-            return len(self._waiters)
-
-    @property
-    def pending_tombstone_count(self) -> int:
-        with self._condition:
-            self._prune_tombstones_locked(time.monotonic())
-            return len(self._tombstones)
-
-    def register_waiter(
-        self,
-        request_id: str,
-        *,
-        method: str = "request",
-        on_late_response: Callable[[str, dict[str, Any]], None] | None = None,
-    ) -> _ResponseWaiter:
-        if on_late_response is not None and not callable(on_late_response):
-            raise GatewayValidationError("on_late_response must be callable")
-        waiter = _ResponseWaiter(
-            request_id=request_id,
-            method=method,
-            on_late_response=on_late_response,
-        )
-        with self._condition:
-            if self._closed:
-                raise GatewayTransportClosed("Gateway transport is closed")
-            self._prune_tombstones_locked(time.monotonic())
-            if request_id in self._waiters or request_id in self._tombstones:
-                raise GatewayProtocolError("request", "duplicate request id")
-            self._waiters[request_id] = waiter
-        return waiter
-
-    def cancel_waiter(self, waiter: _ResponseWaiter) -> None:
-        with self._condition:
-            current = self._waiters.get(waiter.request_id)
-            if current is waiter:
-                del self._waiters[waiter.request_id]
-
-    def wait_for_response(
-        self,
-        waiter: _ResponseWaiter,
-        *,
-        timeout: float,
-        method: str,
-    ) -> dict[str, Any]:
-        if not waiter.event.wait(timeout):
-            with self._condition:
-                current = self._waiters.get(waiter.request_id)
-                if current is waiter:
-                    del self._waiters[waiter.request_id]
-                    if waiter.on_late_response is not None:
-                        self._add_tombstone_locked(waiter, time.monotonic())
-                    raise GatewayTimeoutError(method)
-                # A response or close won the timeout race while this thread
-                # was acquiring the condition. Its waiter state is complete.
-
-        if waiter.error is not None:
-            raise waiter.error
-        if waiter.response is None:
-            raise GatewayProtocolError(
-                method, "response waiter completed without a response"
-            )
-        return waiter.response
-
-    def write(self, obj: dict[str, Any]) -> bool:
-        """Route a core response or event; return false after close."""
-
-        with self._condition:
-            if self._closed:
-                return False
-
-        if not isinstance(obj, dict):
-            return True
-
-        if "id" in obj and obj.get("method") != "event":
-            self._write_response(obj)
-            return True
-        if obj.get("method") == "event":
-            event = self._parse_event(obj)
-            if event is not None:
-                return self._enqueue_event(event)
-        return True
-
-    def _write_response(self, response: dict[str, Any]) -> None:
-        request_id = response.get("id")
-        if not isinstance(request_id, str):
-            return
-        late_callback: Callable[[str, dict[str, Any]], None] | None = None
-        late_method = ""
-        late_response: dict[str, Any] | None = None
-        with self._condition:
-            if self._closed:
-                return
-            self._prune_tombstones_locked(time.monotonic())
-            waiter = self._waiters.pop(request_id, None)
-            if waiter is not None:
-                try:
-                    waiter.response = copy.deepcopy(response)
-                except Exception:  # noqa: BLE001 - malformed core objects are ignored safely
-                    waiter.response = dict(response)
-                waiter.event.set()
-                return
-            tombstone = self._tombstones.pop(request_id, None)
-            if tombstone is not None:
-                late_callback = tombstone.callback
-                late_method = tombstone.method
-                try:
-                    late_response = copy.deepcopy(response)
-                except Exception:  # noqa: BLE001 - malformed late results are ignored
-                    late_response = dict(response)
-
-        if late_callback is not None and late_response is not None:
-            try:
-                late_callback(late_method, late_response)
-            except Exception:  # noqa: BLE001 - never bind core response writers
-                logger.exception("YaoYao group late Gateway response callback failed")
-
-    def _prune_tombstones_locked(self, now: float) -> None:
-        expired = [
-            request_id
-            for request_id, tombstone in self._tombstones.items()
-            if tombstone.expires_at <= now
-        ]
-        for request_id in expired:
-            self._tombstones.pop(request_id, None)
-
-    def _add_tombstone_locked(self, waiter: _ResponseWaiter, now: float) -> None:
-        callback = waiter.on_late_response
-        if callback is None:
-            return
-        self._prune_tombstones_locked(now)
-        while len(self._tombstones) >= self._max_late_responses:
-            oldest = next(iter(self._tombstones))
-            del self._tombstones[oldest]
-            logger.warning("Evicted an expired-session cleanup tombstone at capacity")
-        self._tombstones[waiter.request_id] = _LateResponseTombstone(
-            method=waiter.method,
-            expires_at=now + self._late_response_ttl,
-            callback=callback,
-        )
-        self._condition.notify_all()
-
-    @staticmethod
-    def _parse_event(frame: dict[str, Any]) -> _QueuedEvent | None:
-        params = frame.get("params")
-        if not isinstance(params, dict):
-            return None
-        runtime_id = params.get("session_id")
-        event_type = params.get("type")
-        if not isinstance(runtime_id, str) or not runtime_id:
-            return None
-        if not isinstance(event_type, str) or not event_type:
-            return None
-        if not _bounded_utf8(runtime_id, _MAX_RUNTIME_ID_BYTES) or not _bounded_utf8(
-            event_type, _MAX_EVENT_TYPE_BYTES
-        ):
-            logger.warning("Rejected oversized YaoYao group Gateway event identity")
-            return None
-        raw_payload = params.get("payload", {})
-        if raw_payload is None:
-            raw_payload = {}
-        delta_key: tuple[str, str] | None = None
-        if event_type in _DELTA_EVENTS:
-            if not isinstance(raw_payload, dict):
-                return None
-            text = raw_payload.get("text")
-            if not isinstance(text, str):
-                return None
-            if any(0xD800 <= ord(character) <= 0xDFFF for character in text):
-                logger.warning("Rejected non-UTF-8 Gateway delta text")
-                return None
-            metadata = dict(raw_payload)
-            metadata["text"] = ""
-            if not _json_payload_within_limit(metadata, _MAX_DELTA_METADATA_BYTES):
-                logger.warning("Rejected oversized or non-JSON Gateway delta metadata")
-                return None
-            delta_key = (runtime_id, event_type)
-            try:
-                payload = copy.deepcopy(raw_payload)
-            except Exception:  # noqa: BLE001 - malformed delta objects are ignored safely
-                return None
-        else:
-            inspection = _inspect_json_payload(raw_payload)
-            if inspection.valid and not isinstance(raw_payload, dict):
-                inspection = _JsonInspection(
-                    False,
-                    inspection.encoded_bytes,
-                    "event payload must be a JSON object",
-                )
-            if (
-                isinstance(raw_payload, dict)
-                and inspection.valid
-                and not _control_requires_projection(
-                    event_type,
-                    raw_payload,
-                    inspection,
-                )
-            ):
-                try:
-                    payload = copy.deepcopy(raw_payload)
-                except Exception:  # noqa: BLE001 - deliver an invalid sentinel instead
-                    payload = _control_payload_sentinel(
-                        _JsonInspection(False, 0, "payload copy failed")
-                    )
-            else:
-                payload = _sanitize_control_payload(
-                    event_type,
-                    raw_payload,
-                    inspection,
-                )
-        return _QueuedEvent(runtime_id, event_type, payload, delta_key)
-
-    def _enqueue_event(self, event: _QueuedEvent) -> bool:
-        if event.delta_key is not None:
-            return self._enqueue_delta(event)
-        return self._enqueue_control(event)
-
-    def _enqueue_delta(self, event: _QueuedEvent) -> bool:
-        source_text = event.payload["text"]
-        for chunk, chunk_bytes in _utf8_chunks(source_text, MAX_DELTA_BUFFER_BYTES):
-            payload = dict(event.payload)
-            payload["text"] = chunk
-            queued = _QueuedEvent(
-                event.runtime_id,
-                event.event_type,
-                payload,
-                event.delta_key,
-                chunk_bytes,
-            )
-            with self._condition:
-                while True:
-                    if self._closed:
-                        return False
-                    previous = self._events[-1] if self._events else None
-                    if (
-                        previous is not None
-                        and previous.delta_key == queued.delta_key
-                        and previous.delta_bytes + queued.delta_bytes
-                        <= MAX_DELTA_BUFFER_BYTES
-                    ):
-                        merged_text = previous.payload["text"] + queued.payload["text"]
-                        previous.payload.update(queued.payload)
-                        previous.payload["text"] = merged_text
-                        previous.delta_bytes += queued.delta_bytes
-                        break
-                    if len(self._events) < self._max_queued_frames:
-                        self._events.append(queued)
-                        self._condition.notify_all()
-                        break
-                    self._condition.wait()
-        return True
-
-    def _enqueue_control(self, event: _QueuedEvent) -> bool:
-        with self._condition:
-            if self._closed:
-                return False
-            while len(self._events) >= self._max_queued_frames and not self._closed:
-                self._condition.wait()
-            if self._closed:
-                return False
-            self._events.append(event)
-            self._condition.notify_all()
-            return True
-
-    def _event_worker(self) -> None:
-        while True:
-            with self._condition:
-                while not self._events and not self._closed:
-                    now = time.monotonic()
-                    self._prune_tombstones_locked(now)
-                    if self._tombstones:
-                        next_expiry = min(
-                            tombstone.expires_at
-                            for tombstone in self._tombstones.values()
-                        )
-                        self._condition.wait(max(0.0, next_expiry - now))
-                    else:
-                        self._condition.wait()
-                if self._closed:
-                    return
-                event = self._events.popleft()
-                self._callback_active = True
-                self._condition.notify_all()
-
-            try:
-                self._on_event(event.runtime_id, event.event_type, event.payload)
-            except Exception:  # noqa: BLE001 - isolate plugin consumer failures
-                logger.exception("YaoYao group Gateway event callback failed")
-            finally:
-                with self._condition:
-                    self._callback_active = False
-                    self._condition.notify_all()
-
-    def drain(self, timeout: float | None = None) -> bool:
-        """Wait until queued callbacks finish; intended for orderly shutdown/tests."""
-
-        if timeout is not None and timeout < 0:
-            raise GatewayValidationError("drain timeout must be non-negative")
-        deadline = None if timeout is None else time.monotonic() + timeout
-        with self._condition:
-            if threading.current_thread() is self._worker:
-                return not self._events
-            while self._events or self._callback_active:
-                if deadline is None:
-                    self._condition.wait()
-                    continue
-                remaining = deadline - time.monotonic()
-                if remaining <= 0:
-                    return False
-                self._condition.wait(remaining)
-            return True
-
-    def close(self) -> None:
-        waiters: list[_ResponseWaiter]
-        with self._condition:
-            if not self._closed:
-                self._closed = True
-                waiters = list(self._waiters.values())
-                self._waiters.clear()
-                self._tombstones.clear()
-                self._events.clear()
-                for waiter in waiters:
-                    waiter.error = GatewayTransportClosed("Gateway transport is closed")
-                    waiter.event.set()
-                self._condition.notify_all()
-
-        if threading.current_thread() is not self._worker:
-            self._worker.join()
-
-
-def _default_dispatcher(
-    request: dict[str, Any],
-    transport: GroupGatewayTransport,
-) -> dict[str, Any] | None:
-    # tui_gateway.server is intentionally private and expensive. Keep the import
-    # inside this one boundary and defer it until the first actual request.
-    from tui_gateway.server import dispatch
-
-    return dispatch(request, transport)
-
-
-def _nonempty_string(value: Any, field_name: str) -> str:
-    if not isinstance(value, str) or not value.strip():
-        raise GatewayValidationError(f"{field_name} must be a non-empty string")
-    return value
-
-
-def _response_string(result: dict[str, Any], field_name: str, method: str) -> str:
-    value = result.get(field_name)
-    if not isinstance(value, str) or not value:
-        raise GatewayProtocolError(method, f"missing or invalid {field_name}")
-    return value
-
-
-def _response_bool(
-    result: dict[str, Any],
-    field_name: str,
-    method: str,
-    *,
-    default: bool | None = None,
-) -> bool:
-    if field_name not in result and default is not None:
-        return default
-    value = result.get(field_name)
-    if not isinstance(value, bool):
-        raise GatewayProtocolError(method, f"missing or invalid {field_name}")
-    return value
-
-
-class GroupGatewayAdapter:
-    """Stable plugin facade over ``tui_gateway.server.dispatch``."""
-
-    def __init__(
-        self,
-        *,
-        dispatcher: Dispatcher | None = None,
-        on_event: EventCallback | None = None,
-        request_timeout: float = 30.0,
-        max_control_frames: int = 128,
-        late_response_ttl: float = 30.0,
-        max_late_responses: int = 128,
-    ) -> None:
-        if dispatcher is not None and not callable(dispatcher):
-            raise GatewayValidationError("dispatcher must be callable")
-        if (
-            isinstance(request_timeout, bool)
-            or not isinstance(request_timeout, (int, float))
-            or not math.isfinite(request_timeout)
-            or request_timeout <= 0
-        ):
-            raise GatewayValidationError("request_timeout must be positive")
-        self._dispatcher = _default_dispatcher if dispatcher is None else dispatcher
-        self._request_timeout = float(request_timeout)
-        self._dispatch_condition = threading.Condition(threading.RLock())
-        self._lifecycle_state = "open"
-        self._dispatch_inflight = 0
-        self._cleanup_timeout = min(self._request_timeout, 5.0)
-        self._cleanup_condition = threading.Condition(threading.RLock())
-        self._cleanup_queue: deque[tuple[str, int]] = deque()
-        self._cleanup_pending: set[str] = set()
-        self._cleanup_claimed: set[str] = set()
-        self._cleanup_active: str | None = None
-        self._adoption_generation = 0
-        self._cleanup_closed = False
-        self._max_cleanup_queue = max_late_responses
-        self.transport = GroupGatewayTransport(
-            on_event
-            if on_event is not None
-            else (lambda _runtime_id, _event_type, _payload: None),
-            max_control_frames=max_control_frames,
-            late_response_ttl=late_response_ttl,
-            max_late_responses=max_late_responses,
-        )
-        self._cleanup_worker = threading.Thread(
-            target=self._late_cleanup_worker,
-            name="yaoyao-group-gateway-late-cleanup",
-            daemon=True,
-        )
-        self._cleanup_worker.start()
-
-    def _call_dispatcher(
-        self,
-        request: dict[str, Any],
-        transport: GroupGatewayTransport,
-    ) -> dict[str, Any] | None:
-        with self._dispatch_condition:
-            if self._lifecycle_state != "open":
-                raise GatewayTransportClosed("Gateway adapter is shutting down")
-            self._dispatch_inflight += 1
-        try:
-            return self._dispatcher(request, transport)
-        finally:
-            with self._dispatch_condition:
-                self._dispatch_inflight -= 1
-                self._dispatch_condition.notify_all()
-
-    def request(
-        self,
-        method: str,
-        params: dict[str, Any],
-        timeout: float | None = None,
-    ) -> Any:
-        method = _nonempty_string(method, "method")
-        if not isinstance(params, dict):
-            raise GatewayValidationError("params must be an object")
-        effective_timeout = self._request_timeout if timeout is None else timeout
-        if (
-            isinstance(effective_timeout, bool)
-            or not isinstance(effective_timeout, (int, float))
-            or not math.isfinite(effective_timeout)
-            or effective_timeout <= 0
-        ):
-            raise GatewayValidationError("timeout must be positive")
-
-        try:
-            request_params = copy.deepcopy(params)
-        except Exception:  # noqa: BLE001 - reject caller objects at the boundary
-            raise GatewayValidationError(
-                "params must contain copyable values"
-            ) from None
-
-        request_id = str(uuid.uuid4())
-        request = {
-            "jsonrpc": "2.0",
-            "id": request_id,
-            "method": method,
-            "params": request_params,
-        }
-        late_context = self._late_session_context(request_id, method, request_params)
-        late_callback = (
-            partial(self._handle_late_session_response, late_context)
-            if late_context is not None
-            else None
-        )
-
-        waiter = self.transport.register_waiter(
-            request_id,
-            method=method,
-            on_late_response=late_callback,
-        )
-        try:
-            inline_response = self._call_dispatcher(request, self.transport)
-        except GatewayTransportClosed:
-            self.transport.cancel_waiter(waiter)
-            raise
-        except Exception as exc:
-            self.transport.cancel_waiter(waiter)
-            raise GatewayDispatchError(method) from exc
-
-        if inline_response is not None:
-            if not isinstance(inline_response, dict):
-                self.transport.cancel_waiter(waiter)
-                raise GatewayProtocolError(
-                    method, "dispatcher returned a non-object response"
-                )
-            if (
-                inline_response.get("jsonrpc") != "2.0"
-                or inline_response.get("id") != request_id
-                or "method" in inline_response
-            ):
-                self.transport.cancel_waiter(waiter)
-                raise GatewayProtocolError(
-                    method, "dispatcher returned an unrelated or invalid response"
-                )
-            accepted = self.transport.write(inline_response)
-            if not accepted:
-                # close() has already completed the registered waiter.
-                return self._parse_response(
-                    self.transport.wait_for_response(
-                        waiter,
-                        timeout=float(effective_timeout),
-                        method=method,
-                    ),
-                    request_id,
-                    method,
-                )
-
-        response = self.transport.wait_for_response(
-            waiter,
-            timeout=float(effective_timeout),
-            method=method,
-        )
-        return self._parse_response(response, request_id, method)
-
-    @staticmethod
-    def _parse_response(
-        response: dict[str, Any],
-        request_id: str,
-        method: str,
-    ) -> Any:
-        if response.get("jsonrpc") != "2.0" or response.get("id") != request_id:
-            raise GatewayProtocolError(method, "invalid JSON-RPC response envelope")
-        has_result = "result" in response
-        has_error = "error" in response
-        if has_result == has_error:
-            raise GatewayProtocolError(
-                method, "response must contain exactly one of result or error"
-            )
-        if has_error:
-            error = response["error"]
-            if not isinstance(error, dict):
-                raise GatewayProtocolError(method, "invalid JSON-RPC error")
-            code = error.get("code")
-            message = error.get("message")
-            if (
-                isinstance(code, bool)
-                or not isinstance(code, int)
-                or not isinstance(message, str)
-            ):
-                raise GatewayProtocolError(method, "invalid JSON-RPC error")
-            raise GatewayRPCError(method, code, message, error.get("data"))
-        return response["result"]
-
-    @staticmethod
-    def _result_object(result: Any, method: str) -> dict[str, Any]:
-        if not isinstance(result, dict):
-            raise GatewayProtocolError(method, "result must be an object")
-        return result
-
-    def _late_session_context(
-        self,
-        request_id: str,
-        method: str,
-        params: dict[str, Any],
-    ) -> _LateSessionContext | None:
-        if method not in {"session.create", "session.resume"}:
-            return None
-        profile = params.get("profile")
-        if not isinstance(profile, str) or not profile:
-            return None
-        requested_stored_id: str | None = None
-        if method == "session.resume":
-            requested_stored_id = params.get("session_id")
-            if not isinstance(requested_stored_id, str) or not requested_stored_id:
-                return None
-        with self._cleanup_condition:
-            adoption_generation = self._adoption_generation
-        return _LateSessionContext(
-            request_id=request_id,
-            method=method,
-            profile=profile,
-            requested_stored_id=requested_stored_id,
-            adoption_generation=adoption_generation,
-        )
-
-    def _handle_late_session_response(
-        self,
-        context: _LateSessionContext,
-        tombstone_method: str,
-        response: dict[str, Any],
-    ) -> None:
-        if tombstone_method != context.method:
-            return
-        # session.resume may legitimately reuse a runtime that another request or
-        # device already owns. Its response has no core-authenticated "created"
-        # bit, so a timeout can never prove that the returned runtime is an orphan.
-        if context.method == "session.resume":
-            return
-        if (
-            response.get("jsonrpc") != "2.0"
-            or response.get("id") != context.request_id
-            or "method" in response
-            or ("result" in response) == ("error" in response)
-        ):
-            return
-        result = response.get("result")
-        if not isinstance(result, dict):
-            return
-        runtime_id = result.get("session_id")
-        if not isinstance(runtime_id, str) or not runtime_id:
-            return
-        info = result.get("info")
-        if not isinstance(info, dict):
-            return
-        profile_name = info.get("profile_name")
-        if profile_name != context.profile:
-            return
-        stored_id = result.get("stored_session_id")
-        if not isinstance(stored_id, str) or not stored_id:
-            return
-        running = result.get("running", False)
-        # A running runtime may already be serving another device. Cleanup is
-        # deliberately skipped even though that can leave a timed-out create
-        # behind; leaking an uncertain orphan is safer than killing active work.
-        if not isinstance(running, bool) or running:
-            return
-        self._schedule_late_cleanup(runtime_id, context.adoption_generation)
-
-    def _schedule_late_cleanup(
-        self, runtime_id: str, adoption_generation: int
-    ) -> None:
-        with self._cleanup_condition:
-            if (
-                self._cleanup_closed
-                or adoption_generation != self._adoption_generation
-                or runtime_id in self._cleanup_claimed
-                or runtime_id in self._cleanup_pending
-                or len(self._cleanup_claimed) >= self._max_cleanup_queue
-            ):
-                return
-            while (
-                len(self._cleanup_queue) >= self._max_cleanup_queue
-                and not self._cleanup_closed
-            ):
-                self._cleanup_condition.wait()
-            if (
-                self._cleanup_closed
-                or adoption_generation != self._adoption_generation
-                or runtime_id in self._cleanup_claimed
-                or runtime_id in self._cleanup_pending
-                or len(self._cleanup_claimed) >= self._max_cleanup_queue
-            ):
-                return
-            self._cleanup_pending.add(runtime_id)
-            self._cleanup_queue.append((runtime_id, adoption_generation))
-            self._cleanup_condition.notify_all()
-
-    def _adopt_runtime(self, runtime_id: str, method: str) -> None:
-        """Atomically adopt a runtime or reject one already claimed for cleanup."""
-
-        with self._cleanup_condition:
-            if self._cleanup_closed:
-                raise GatewayTransportClosed("Gateway adapter is shutting down")
-            if runtime_id in self._cleanup_claimed:
-                raise GatewayProtocolError(
-                    method, "runtime cleanup won the adoption race"
-                )
-            self._adoption_generation += 1
-            queued_runtime_ids = {
-                queued_runtime_id for queued_runtime_id, _generation in self._cleanup_queue
-            }
-            self._cleanup_queue.clear()
-            self._cleanup_pending.difference_update(queued_runtime_ids)
-            self._cleanup_condition.notify_all()
-
-    def _late_cleanup_worker(self) -> None:
-        while True:
-            with self._cleanup_condition:
-                while not self._cleanup_queue and not self._cleanup_closed:
-                    self._cleanup_condition.wait()
-                if self._cleanup_closed:
-                    return
-                runtime_id, adoption_generation = self._cleanup_queue.popleft()
-                if (
-                    adoption_generation != self._adoption_generation
-                    or runtime_id in self._cleanup_claimed
-                    or len(self._cleanup_claimed) >= self._max_cleanup_queue
-                ):
-                    self._cleanup_pending.discard(runtime_id)
-                    self._cleanup_condition.notify_all()
-                    continue
-                # Claimed IDs are terminal for this adapter's lifetime. A core
-                # dispatcher can remain blocked for an arbitrary duration, so
-                # expiring this proof would allow an ABA adoption of a runtime
-                # already handed to session.close. The hard capacity above
-                # bounds memory; once full, later orphans are leaked safely.
-                self._cleanup_claimed.add(runtime_id)
-                self._cleanup_active = runtime_id
-                self._cleanup_condition.notify_all()
-            try:
-                self._best_effort_close_late_session(runtime_id)
-            finally:
-                with self._cleanup_condition:
-                    self._cleanup_active = None
-                    self._cleanup_pending.discard(runtime_id)
-                    self._cleanup_condition.notify_all()
-
-    def _best_effort_close_late_session(self, runtime_id: str) -> None:
-        method = "session.close"
-        request_id = str(uuid.uuid4())
-        cleanup_transport = GroupGatewayTransport(
-            lambda _runtime_id, _event_type, _payload: None,
-            max_control_frames=1,
-            late_response_ttl=max(self._cleanup_timeout, 0.001),
-            max_late_responses=1,
-        )
-        waiter = cleanup_transport.register_waiter(request_id, method=method)
-        request = {
-            "jsonrpc": "2.0",
-            "id": request_id,
-            "method": method,
-            "params": {"session_id": runtime_id},
-        }
-        try:
-            inline_response = self._call_dispatcher(request, cleanup_transport)
-            if inline_response is not None:
-                if (
-                    not isinstance(inline_response, dict)
-                    or inline_response.get("jsonrpc") != "2.0"
-                    or inline_response.get("id") != request_id
-                    or "method" in inline_response
-                ):
-                    raise GatewayProtocolError(
-                        method, "cleanup dispatcher returned an invalid response"
-                    )
-                cleanup_transport.write(inline_response)
-            response = cleanup_transport.wait_for_response(
-                waiter,
-                timeout=self._cleanup_timeout,
-                method=method,
-            )
-            result = self._result_object(
-                self._parse_response(response, request_id, method), method
-            )
-            _response_bool(result, "closed", method)
-        except Exception:  # noqa: BLE001 - cleanup is deliberately best-effort
-            logger.warning(
-                "Best-effort close of a late YaoYao group session failed",
-                exc_info=True,
-            )
-        finally:
-            cleanup_transport.close()
-
-    @staticmethod
-    def _cwd(value: str) -> str:
-        if not isinstance(value, str):
-            raise GatewayValidationError("cwd must be a string")
-        if not value.strip():
-            return ""
-        path = Path(value)
-        if not path.is_absolute():
-            raise GatewayValidationError(
-                "cwd must be empty or an existing absolute directory"
-            )
-        try:
-            resolved = path.resolve(strict=True)
-            is_directory = resolved.is_dir()
-        except (OSError, RuntimeError, ValueError) as exc:
-            raise GatewayValidationError(
-                "cwd must be empty or an existing absolute directory"
-            ) from exc
-        if not is_directory:
-            raise GatewayValidationError(
-                "cwd must be empty or an existing absolute directory"
-            )
-        return value
-
-    def create_session(
-        self,
-        profile: str,
-        title: str,
-        cwd: str,
-        seed_messages: list[dict[str, Any]],
-        configuration: dict[str, Any] | None = None,
-    ) -> SessionIdentity:
-        method = "session.create"
-        profile = _nonempty_string(profile, "profile")
-        title = _nonempty_string(title, "title")
-        if not isinstance(seed_messages, list) or not all(
-            isinstance(message, dict) for message in seed_messages
-        ):
-            raise GatewayValidationError("seed_messages must be a list of objects")
-        parameters: dict[str, Any] = {
-            "profile": profile,
-            "title": title,
-            "cwd": self._cwd(cwd),
-            "messages": seed_messages,
-            "source": "ios_group",
-            "close_on_disconnect": False,
-        }
-        for key in ("model", "provider", "reasoning_effort", "fast"):
-            if configuration is not None and configuration.get(key) is not None:
-                parameters[key] = configuration[key]
-        result = self._result_object(
-            self.request(
-                method,
-                parameters,
-            ),
-            method,
-        )
-        runtime_id = _response_string(result, "session_id", method)
-        stored_id = _response_string(result, "stored_session_id", method)
-        running = _response_bool(result, "running", method, default=False)
-        info = result.get("info")
-        if not isinstance(info, dict):
-            raise GatewayProtocolError(method, "missing or invalid info.profile_name")
-        response_profile = info.get("profile_name")
-        if not isinstance(response_profile, str) or not response_profile:
-            raise GatewayProtocolError(method, "missing or invalid info.profile_name")
-        if response_profile != profile:
-            raise GatewayProtocolError(method, "profile does not match the request")
-        self._adopt_runtime(runtime_id, method)
-        return SessionIdentity(stored_id, runtime_id, running)
-
-    def resume_session(self, profile: str, stored_id: str) -> SessionIdentity:
-        method = "session.resume"
-        profile = _nonempty_string(profile, "profile")
-        stored_id = _nonempty_string(stored_id, "stored_id")
-        result = self._result_object(
-            self.request(
-                method,
-                {
-                    "profile": profile,
-                    "session_id": stored_id,
-                    "omit_messages": True,
-                    "source": "ios_group",
-                    "close_on_disconnect": False,
-                },
-            ),
-            method,
-        )
-        runtime_id = _response_string(result, "session_id", method)
-        session_key = result.get("session_key")
-        resumed = result.get("resumed")
-        if session_key is not None and (
-            not isinstance(session_key, str) or not session_key
-        ):
-            raise GatewayProtocolError(method, "missing or invalid session_key")
-        if resumed is not None and (not isinstance(resumed, str) or not resumed):
-            raise GatewayProtocolError(method, "missing or invalid resumed")
-        if session_key is not None and resumed is not None and session_key != resumed:
-            raise GatewayProtocolError(method, "ambiguous stored session identity")
-        current_stored_id = session_key or resumed
-        if current_stored_id is None:
-            raise GatewayProtocolError(method, "missing session_key or resumed")
-        running = _response_bool(result, "running", method)
-        info = result.get("info")
-        if not isinstance(info, dict):
-            raise GatewayProtocolError(method, "missing or invalid info.profile_name")
-        response_profile = info.get("profile_name")
-        if not isinstance(response_profile, str) or not response_profile:
-            raise GatewayProtocolError(method, "missing or invalid info.profile_name")
-        if response_profile != profile:
-            raise GatewayProtocolError(method, "profile does not match the request")
-        self._adopt_runtime(runtime_id, method)
-        return SessionIdentity(current_stored_id, runtime_id, running)
-
-    def submit_prompt(self, runtime_id: str, text: str) -> None:
-        method = "prompt.submit"
-        result = self._result_object(
-            self.request(
-                method,
-                {
-                    "session_id": _nonempty_string(runtime_id, "runtime_id"),
-                    "text": _nonempty_string(text, "text"),
-                },
-            ),
-            method,
-        )
-        if result.get("status") != "streaming":
-            raise GatewayProtocolError(method, "expected streaming status")
-
-    def interrupt_session(self, runtime_id: str) -> None:
-        method = "session.interrupt"
-        result = self._result_object(
-            self.request(
-                method, {"session_id": _nonempty_string(runtime_id, "runtime_id")}
-            ),
-            method,
-        )
-        if result.get("status") != "interrupted":
-            raise GatewayProtocolError(method, "expected interrupted status")
-
-    def interrupt(self, runtime_id: str) -> None:
-        self.interrupt_session(runtime_id)
-
-    def close_session(self, runtime_id: str) -> bool:
-        method = "session.close"
-        result = self._result_object(
-            self.request(
-                method, {"session_id": _nonempty_string(runtime_id, "runtime_id")}
-            ),
-            method,
-        )
-        return _response_bool(result, "closed", method)
-
-    def respond_approval(self, runtime_id: str, choice: str) -> int:
-        method = "approval.respond"
-        runtime_id = _nonempty_string(runtime_id, "runtime_id")
-        choice = _nonempty_string(choice, "choice")
-        if choice not in _APPROVAL_CHOICES:
-            raise GatewayValidationError(
-                "choice must be once, session, always, or deny"
-            )
-        result = self._result_object(
-            self.request(
-                method,
-                {"session_id": runtime_id, "choice": choice, "all": False},
-            ),
-            method,
-        )
-        resolved = result.get("resolved")
-        if isinstance(resolved, bool) or not isinstance(resolved, int) or resolved < 0:
-            raise GatewayProtocolError(method, "missing or invalid resolved count")
-        return resolved
-
-    def respond_clarification(self, request_id: str, answer: str) -> str:
-        method = "clarify.respond"
-        result = self._result_object(
-            self.request(
-                method,
-                {
-                    "request_id": _nonempty_string(request_id, "request_id"),
-                    "answer": _nonempty_string(answer, "answer"),
-                },
-            ),
-            method,
-        )
-        status = result.get("status")
-        if status not in {"ok", "expired"}:
-            raise GatewayProtocolError(method, "expected ok or expired status")
-        return status
-
-    def shutdown(self) -> None:
-        with self._dispatch_condition:
-            if self._lifecycle_state == "closed":
-                return
-            if self._lifecycle_state == "closing":
-                if threading.current_thread() in {
-                    self.transport._worker,
-                    self._cleanup_worker,
-                }:
-                    return
-                while self._lifecycle_state != "closed":
-                    self._dispatch_condition.wait()
-                return
-            self._lifecycle_state = "closing"
-
-        with self._cleanup_condition:
-            if not self._cleanup_closed:
-                self._cleanup_closed = True
-                self._cleanup_queue.clear()
-                if self._cleanup_active is None:
-                    self._cleanup_pending.clear()
-                else:
-                    self._cleanup_pending.intersection_update(
-                        {self._cleanup_active}
-                    )
-                self._cleanup_condition.notify_all()
-        self.transport.close()
-
-        with self._dispatch_condition:
-            while self._dispatch_inflight:
-                self._dispatch_condition.wait()
-        if threading.current_thread() is not self._cleanup_worker:
-            self._cleanup_worker.join()
-        with self._cleanup_condition:
-            self._cleanup_claimed.clear()
-            self._cleanup_active = None
-        with self._dispatch_condition:
-            self._lifecycle_state = "closed"
-            self._dispatch_condition.notify_all()
-
-    def close(self, runtime_id: str) -> bool:
-        """Close one core session; ``shutdown`` owns transport lifecycle."""
-
-        return self.close_session(runtime_id)
-
-
-# The shorter name is the stable design-level spelling used by the orchestrator.
-GroupTransport = GroupGatewayTransport
-
-
-__all__ = [
-    "GatewayDispatchError",
-    "GatewayError",
-    "GatewayProtocolError",
-    "GatewayRPCError",
-    "GatewayTimeoutError",
-    "GatewayTransportClosed",
-    "GatewayValidationError",
-    "GroupGatewayAdapter",
-    "GroupGatewayTransport",
-    "GroupTransport",
-    "MAX_CONTROL_PAYLOAD_BYTES",
-    "MAX_DELTA_BUFFER_BYTES",
-    "MAX_SAFE_JSON_INTEGER",
-    "MAX_TERMINAL_TEXT_BYTES",
-    "SessionIdentity",
-]

+ 0 - 290
hermes-plugins/yaoyao/dashboard/group_node_registry.py

@@ -1,290 +0,0 @@
-"""Encrypted registry for Hermes nodes delegated by the iOS pairing flow."""
-
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-import re
-import tempfile
-import threading
-import time
-from typing import Mapping
-from urllib.parse import urlsplit, urlunsplit
-import uuid
-
-try:
-    from .data_paths import ensure_durable_data_root
-except ImportError:  # Loaded by the Dashboard plugin loader as a top-level module.
-    from data_paths import ensure_durable_data_root
-
-
-class NodeRegistryError(RuntimeError):
-    pass
-
-
-class NodeNotFoundError(NodeRegistryError):
-    pass
-
-
-class PairedNodeRegistry:
-    def __init__(self, root: Path) -> None:
-        self.root = Path(root)
-        self.path = self.root / "paired-group-nodes.json"
-        self.key_path = self.root / "paired-group-nodes.key"
-        self._lock = threading.RLock()
-        self._fernet = self._load_fernet()
-
-    @classmethod
-    def from_environment(cls) -> "PairedNodeRegistry":
-        hermes_home = Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")
-        return cls(ensure_durable_data_root(hermes_home).data_root)
-
-    def register(self, command: Mapping[str, object]) -> dict[str, object]:
-        allowed = {
-            "nodeId", "name", "serverUrl", "fingerprint", "accessToken",
-            "profiles",
-        }
-        if not {"nodeId", "name", "serverUrl", "fingerprint", "accessToken"} <= set(command) or not set(command) <= allowed:
-            raise ValueError("Node registration fields are invalid")
-        node_id = self._node_id(command.get("nodeId"))
-        name = self._text(command.get("name"), "name", 100)
-        server_url = self._server_url(command.get("serverUrl"))
-        fingerprint = self._text(
-            command.get("fingerprint"), "fingerprint", 256
-        )
-        token = self._text(command.get("accessToken"), "accessToken", 4096)
-        profiles = self._profiles(command.get("profiles", []))
-        now = time.time()
-        with self._lock:
-            state = self._load()
-            existing = next(
-                (item for item in state if item.get("nodeId") == node_id), None
-            )
-            created_at = (
-                float(existing.get("createdAt", now))
-                if isinstance(existing, dict)
-                else now
-            )
-            record = {
-                "nodeId": node_id,
-                "name": name,
-                "serverUrl": server_url,
-                "fingerprint": fingerprint,
-                "accessToken": self._fernet.encrypt(token.encode()).decode(),
-                "profiles": profiles,
-                "createdAt": created_at,
-                "updatedAt": now,
-            }
-            state = [item for item in state if item.get("nodeId") != node_id]
-            state.append(record)
-            self._save(state)
-            return self._public(record)
-
-    def list(self) -> list[dict[str, object]]:
-        with self._lock:
-            return sorted(
-                (self._public(record) for record in self._load()),
-                key=lambda item: (-float(item["updatedAt"]), str(item["nodeId"])),
-            )
-
-    def get(self, node_id: str) -> dict[str, object]:
-        canonical = self._node_id(node_id)
-        with self._lock:
-            record = next(
-                (
-                    item for item in self._load()
-                    if item.get("nodeId") == canonical
-                ),
-                None,
-            )
-            if record is None:
-                raise NodeNotFoundError("Paired Hermes node was not found")
-            token = record.get("accessToken")
-            if not isinstance(token, str):
-                raise NodeRegistryError("Paired Hermes node credential is corrupt")
-            try:
-                access_token = self._fernet.decrypt(token.encode()).decode()
-            except Exception as error:
-                raise NodeRegistryError(
-                    "Paired Hermes node credential is unavailable"
-                ) from error
-            return {**self._public(record), "accessToken": access_token}
-
-    def revoke(self, node_id: str) -> bool:
-        canonical = self._node_id(node_id)
-        with self._lock:
-            state = self._load()
-            retained = [
-                item for item in state if item.get("nodeId") != canonical
-            ]
-            if len(retained) == len(state):
-                return False
-            self._save(retained)
-            return True
-
-    def _load_fernet(self):
-        try:
-            from cryptography.fernet import Fernet
-        except ImportError as error:
-            raise NodeRegistryError(
-                "Hermes runtime does not provide encrypted node storage"
-            ) from error
-        self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
-        try:
-            key = self.key_path.read_bytes()
-        except FileNotFoundError:
-            key = Fernet.generate_key()
-            try:
-                descriptor = os.open(
-                    self.key_path,
-                    os.O_WRONLY | os.O_CREAT | os.O_EXCL,
-                    0o600,
-                )
-                with os.fdopen(descriptor, "wb") as stream:
-                    stream.write(key)
-            except FileExistsError:
-                key = self.key_path.read_bytes()
-        return Fernet(key)
-
-    def _load(self) -> list[dict[str, object]]:
-        try:
-            value = json.loads(self.path.read_text(encoding="utf-8"))
-        except FileNotFoundError:
-            return []
-        except (OSError, ValueError, UnicodeDecodeError) as error:
-            raise NodeRegistryError("Paired Hermes node registry is corrupt") from error
-        if not isinstance(value, dict) or value.get("version") != 1:
-            raise NodeRegistryError("Paired Hermes node registry is corrupt")
-        nodes = value.get("nodes")
-        if not isinstance(nodes, list) or not all(
-            isinstance(item, dict) for item in nodes
-        ):
-            raise NodeRegistryError("Paired Hermes node registry is corrupt")
-        return nodes
-
-    def _save(self, nodes: list[dict[str, object]]) -> None:
-        self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
-        descriptor, temporary = tempfile.mkstemp(
-            prefix="paired-group-nodes.", suffix=".tmp", dir=self.root
-        )
-        try:
-            os.fchmod(descriptor, 0o600)
-            with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
-                json.dump(
-                    {"version": 1, "nodes": nodes},
-                    stream,
-                    ensure_ascii=False,
-                    sort_keys=True,
-                    separators=(",", ":"),
-                )
-                stream.write("\n")
-                stream.flush()
-                os.fsync(stream.fileno())
-            os.replace(temporary, self.path)
-        finally:
-            try:
-                os.unlink(temporary)
-            except FileNotFoundError:
-                pass
-
-    @staticmethod
-    def _node_id(value: object) -> str:
-        if not isinstance(value, str):
-            raise ValueError("nodeId must be a canonical UUID")
-        try:
-            canonical = str(uuid.UUID(value))
-        except ValueError as error:
-            raise ValueError("nodeId must be a canonical UUID") from error
-        if canonical != value:
-            raise ValueError("nodeId must be a canonical UUID")
-        return canonical
-
-    @staticmethod
-    def _text(value: object, field: str, maximum: int) -> str:
-        if not isinstance(value, str):
-            raise ValueError(f"{field} must be a string")
-        normalized = value.strip()
-        if not normalized or len(normalized) > maximum:
-            raise ValueError(f"{field} is invalid")
-        return normalized
-
-    @staticmethod
-    def _server_url(value: object) -> str:
-        if not isinstance(value, str):
-            raise ValueError("serverUrl must be a string")
-        parsed = urlsplit(value.strip())
-        if (
-            parsed.scheme not in {"http", "https"}
-            or not parsed.hostname
-            or parsed.username is not None
-            or parsed.password is not None
-            or parsed.query
-            or parsed.fragment
-        ):
-            raise ValueError("serverUrl must be an HTTP or HTTPS node URL")
-        path = parsed.path.rstrip("/")
-        if not path.startswith("/node/"):
-            raise ValueError("serverUrl must identify a paired node path")
-        return urlunsplit((parsed.scheme, parsed.netloc.lower(), path, "", ""))
-
-    @staticmethod
-    def _public(record: Mapping[str, object]) -> dict[str, object]:
-        return {
-            "nodeId": record["nodeId"],
-            "name": record["name"],
-            "serverUrl": record["serverUrl"],
-            "fingerprint": record["fingerprint"],
-            "createdAt": record["createdAt"],
-            "updatedAt": record["updatedAt"],
-            "profiles": record.get("profiles", []),
-        }
-
-    @classmethod
-    def _profiles(cls, value: object) -> list[dict[str, str]]:
-        if not isinstance(value, list) or len(value) > 100:
-            raise ValueError("profiles must be a list of at most 100 items")
-        result: list[dict[str, str]] = []
-        seen: set[str] = set()
-        for raw in value:
-            if not isinstance(raw, Mapping):
-                raise ValueError("profiles entries must be objects")
-            name = cls._text(raw.get("name"), "profiles.name", 100)
-            if name in seen:
-                raise ValueError("profiles names must be unique")
-            seen.add(name)
-            display_name = raw.get("displayName", "")
-            model = raw.get("model", "")
-            avatar = raw.get("avatar", "")
-            color = raw.get("color", "")
-            if not isinstance(display_name, str) or len(display_name) > 100:
-                raise ValueError("profiles.displayName is invalid")
-            if not isinstance(model, str) or len(model) > 4096:
-                raise ValueError("profiles.model is invalid")
-            if not isinstance(avatar, str) or len(avatar) > 2_800_000:
-                raise ValueError("profiles.avatar is invalid")
-            if avatar and not re.fullmatch(
-                r"data:image/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}",
-                avatar,
-                re.IGNORECASE,
-            ):
-                raise ValueError("profiles.avatar is invalid")
-            if not isinstance(color, str) or (
-                color and re.fullmatch(r"#[0-9A-Fa-f]{6}", color) is None
-            ):
-                raise ValueError("profiles.color is invalid")
-            result.append({
-                "name": name,
-                "displayName": display_name.strip(),
-                "model": model.strip(),
-                **({"avatar": avatar} if avatar else {}),
-                **({"color": color} if color else {}),
-            })
-        return result
-
-
-__all__ = [
-    "NodeNotFoundError",
-    "NodeRegistryError",
-    "PairedNodeRegistry",
-]

+ 0 - 341
hermes-plugins/yaoyao/dashboard/group_node_worker.py

@@ -1,341 +0,0 @@
-"""Authenticated remote-execution facade for a paired Hermes node.
-
-The public HTTP authentication boundary lives in the YaoYao Web node proxy.
-This module deliberately exposes only the same stable Gateway operations used
-by the native group orchestrator and keeps a bounded, cursor-based event journal
-so an owning Hermes can drive a remote Agent without holding an inbound socket.
-"""
-
-from __future__ import annotations
-
-from collections import deque
-import base64
-import copy
-import threading
-from typing import Any, Literal
-
-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-
-from .group_gateway import GroupGatewayAdapter, SessionIdentity
-
-
-MAX_NODE_EVENTS = 4096
-MAX_NODE_EVENT_PAGE = 256
-MAX_NODE_STRING = 4096
-
-
-class NodeWorkerModel(BaseModel):
-    model_config = ConfigDict(populate_by_name=True, extra="forbid")
-
-
-class NodeWorkerOpenRequest(NodeWorkerModel):
-    profile: str = Field(min_length=1, max_length=100)
-    title: str = Field(min_length=1, max_length=500)
-    cwd: str = Field(default="", max_length=MAX_NODE_STRING)
-    stored_session_id: str | None = Field(
-        default=None, alias="storedSessionId", max_length=MAX_NODE_STRING
-    )
-    model: str | None = Field(default=None, max_length=MAX_NODE_STRING)
-    provider: str | None = Field(default=None, max_length=MAX_NODE_STRING)
-    reasoning_effort: str | None = Field(
-        default=None, alias="reasoningEffort", max_length=32
-    )
-    fast_mode: bool | None = Field(default=None, alias="fastMode")
-
-    @field_validator(
-        "profile", "title", "stored_session_id", "model", "provider",
-        "reasoning_effort",
-    )
-    @classmethod
-    def normalize_strings(cls, value: str | None) -> str | None:
-        if value is None:
-            return None
-        normalized = value.strip()
-        if not normalized:
-            raise ValueError("string value must not be blank")
-        return normalized
-
-    @model_validator(mode="after")
-    def validate_model_pair(self) -> "NodeWorkerOpenRequest":
-        if (self.model is None) != (self.provider is None):
-            raise ValueError("model and provider must be set together")
-        return self
-
-
-class NodeWorkerPromptRequest(NodeWorkerModel):
-    text: str = Field(min_length=1, max_length=1_000_000)
-
-    @field_validator("text")
-    @classmethod
-    def normalize_text(cls, value: str) -> str:
-        if not value.strip():
-            raise ValueError("text must not be blank")
-        return value
-
-
-class NodeWorkerApprovalRequest(NodeWorkerModel):
-    choice: Literal["once", "session", "always", "deny"]
-
-
-class NodeWorkerClarificationRequest(NodeWorkerModel):
-    request_id: str = Field(alias="requestId", min_length=1, max_length=MAX_NODE_STRING)
-    answer: str = Field(min_length=1, max_length=1_000_000)
-
-
-class NodeWorkerError(RuntimeError):
-    """Raised when the worker lifecycle or cursor contract is invalid."""
-
-
-class NodeGatewayWorker:
-    """Own one local Gateway adapter and a bounded replayable event journal."""
-
-    def __init__(self, *, gateway: GroupGatewayAdapter | None = None) -> None:
-        self._condition = threading.Condition(threading.RLock())
-        self._cursor = 0
-        self._events: deque[dict[str, object]] = deque(maxlen=MAX_NODE_EVENTS)
-        self._runtime_clients: dict[str, str] = {}
-        self._clarification_clients: dict[str, str] = {}
-        self._closed = False
-        self._gateway = gateway or GroupGatewayAdapter(on_event=self._on_event)
-
-    def open_session(
-        self, request: NodeWorkerOpenRequest, client_id: str = "local"
-    ) -> dict[str, object]:
-        self._require_open()
-        configuration = {
-            "model": request.model,
-            "provider": request.provider,
-            "reasoning_effort": request.reasoning_effort,
-            "fast": request.fast_mode,
-        }
-        if request.stored_session_id is None:
-            identity = self._gateway.create_session(
-                request.profile,
-                request.title,
-                request.cwd,
-                [],
-                configuration,
-            )
-        else:
-            identity = self._gateway.resume_session(
-                request.profile, request.stored_session_id
-            )
-        with self._condition:
-            client = self._client_id(client_id)
-            self._runtime_clients[identity.runtime_id] = client
-            for event in self._events:
-                if event.get("runtimeSessionId") == identity.runtime_id:
-                    event["clientId"] = client
-                    if event.get("type") == "clarify.request":
-                        payload = event.get("payload")
-                        if isinstance(payload, dict):
-                            request_id = payload.get("request_id") or payload.get(
-                                "requestId"
-                            )
-                            if isinstance(request_id, str):
-                                self._clarification_clients[request_id] = client
-        return self._identity(identity)
-
-    def submit_prompt(
-        self,
-        runtime_id: str,
-        request: NodeWorkerPromptRequest,
-        client_id: str = "local",
-    ) -> None:
-        self._require_open()
-        self._gateway.submit_prompt(
-            self._owned_runtime(runtime_id, client_id), request.text
-        )
-
-    def interrupt(self, runtime_id: str, client_id: str = "local") -> None:
-        self._require_open()
-        self._gateway.interrupt(self._owned_runtime(runtime_id, client_id))
-
-    def close_session(self, runtime_id: str, client_id: str = "local") -> bool:
-        self._require_open()
-        return self._gateway.close(self._owned_runtime(runtime_id, client_id))
-
-    def respond_approval(
-        self,
-        runtime_id: str,
-        request: NodeWorkerApprovalRequest,
-        client_id: str = "local",
-    ) -> int:
-        self._require_open()
-        return self._gateway.respond_approval(
-            self._owned_runtime(runtime_id, client_id), request.choice
-        )
-
-    def respond_clarification(
-        self,
-        request: NodeWorkerClarificationRequest,
-        client_id: str = "local",
-    ) -> str:
-        self._require_open()
-        client = self._client_id(client_id)
-        with self._condition:
-            if self._clarification_clients.get(request.request_id) != client:
-                raise NodeWorkerError("Clarification does not belong to this client")
-        return self._gateway.respond_clarification(request.request_id, request.answer)
-
-    def attach_file(
-        self,
-        runtime_id: str,
-        *,
-        name: str,
-        mime_type: str,
-        content: bytes,
-        client_id: str = "local",
-    ) -> dict[str, object]:
-        self._require_open()
-        runtime = self._owned_runtime(runtime_id, client_id)
-        if not isinstance(name, str) or not name.strip() or len(name) > 240:
-            raise NodeWorkerError("Attachment name is invalid")
-        if not isinstance(mime_type, str) or not mime_type.strip() or len(mime_type) > 200:
-            raise NodeWorkerError("Attachment MIME type is invalid")
-        if not isinstance(content, bytes) or not content or len(content) > 25 * 1024 * 1024:
-            raise NodeWorkerError("Attachment content is invalid")
-        result = self._gateway.request(
-            "file.attach",
-            {
-                "session_id": runtime,
-                "name": name.strip(),
-                "data_url": (
-                    f"data:{mime_type.strip()};base64,"
-                    + base64.b64encode(content).decode("ascii")
-                ),
-            },
-        )
-        if not isinstance(result, dict):
-            raise NodeWorkerError("Gateway attachment response is invalid")
-        return result
-
-    def events(
-        self,
-        *,
-        after: int,
-        runtime_id: str | None,
-        limit: int,
-        client_id: str = "local",
-    ) -> dict[str, object]:
-        if isinstance(after, bool) or not isinstance(after, int) or after < 0:
-            raise NodeWorkerError("after must be a non-negative integer")
-        if isinstance(limit, bool) or not isinstance(limit, int):
-            raise NodeWorkerError("limit must be an integer")
-        bounded_limit = max(1, min(limit, MAX_NODE_EVENT_PAGE))
-        selected_runtime = (
-            None if runtime_id is None else self._runtime_id(runtime_id)
-        )
-        client = self._client_id(client_id)
-        with self._condition:
-            client_events = [
-                event for event in self._events
-                if event.get("clientId") == client
-            ]
-            oldest = (
-                int(client_events[0]["cursor"])
-                if client_events else self._cursor + 1
-            )
-            reset = bool(client_events) and after > 0 and after < oldest - 1
-            selected = [
-                copy.deepcopy(event)
-                for event in client_events
-                if int(event["cursor"]) > after
-                and (
-                    selected_runtime is None
-                    or event["runtimeSessionId"] == selected_runtime
-                )
-            ][:bounded_limit]
-            items = []
-            for event in selected:
-                event.pop("clientId", None)
-                items.append(event)
-            return {
-                "items": items,
-                "latestCursor": self._cursor,
-                "oldestCursor": oldest,
-                "reset": reset,
-            }
-
-    def shutdown(self) -> None:
-        with self._condition:
-            if self._closed:
-                return
-            self._closed = True
-        self._gateway.shutdown()
-
-    def _on_event(
-        self, runtime_id: str, event_type: str, payload: dict[str, Any]
-    ) -> None:
-        with self._condition:
-            if self._closed:
-                return
-            self._cursor += 1
-            self._events.append(
-                {
-                    "cursor": self._cursor,
-                    "runtimeSessionId": runtime_id,
-                    "type": event_type,
-                    "payload": copy.deepcopy(payload),
-                    "clientId": self._runtime_clients.get(runtime_id, "local"),
-                }
-            )
-            if event_type == "clarify.request":
-                request_id = payload.get("request_id") or payload.get("requestId")
-                if isinstance(request_id, str):
-                    self._clarification_clients[request_id] = (
-                        self._runtime_clients.get(runtime_id, "local")
-                    )
-            self._condition.notify_all()
-
-    def _require_open(self) -> None:
-        with self._condition:
-            if self._closed:
-                raise NodeWorkerError("Node worker is closed")
-
-    @staticmethod
-    def _runtime_id(value: str) -> str:
-        if not isinstance(value, str):
-            raise NodeWorkerError("runtimeSessionId must be a string")
-        normalized = value.strip()
-        if not normalized or len(normalized) > MAX_NODE_STRING:
-            raise NodeWorkerError("runtimeSessionId is invalid")
-        return normalized
-
-    @staticmethod
-    def _client_id(value: str) -> str:
-        if not isinstance(value, str):
-            raise NodeWorkerError("Node client identity is invalid")
-        normalized = value.strip().lower()
-        if not normalized or len(normalized) > 128:
-            raise NodeWorkerError("Node client identity is invalid")
-        return normalized
-
-    def _owned_runtime(self, runtime_id: str, client_id: str) -> str:
-        runtime = self._runtime_id(runtime_id)
-        client = self._client_id(client_id)
-        with self._condition:
-            if self._runtime_clients.get(runtime) != client:
-                raise NodeWorkerError("Runtime does not belong to this client")
-        return runtime
-
-    @staticmethod
-    def _identity(identity: SessionIdentity) -> dict[str, object]:
-        if not isinstance(identity, SessionIdentity):
-            raise NodeWorkerError("Gateway returned an invalid session identity")
-        return {
-            "storedSessionId": identity.stored_id,
-            "runtimeSessionId": identity.runtime_id,
-            "running": identity.running,
-        }
-
-
-__all__ = [
-    "MAX_NODE_EVENT_PAGE",
-    "NodeGatewayWorker",
-    "NodeWorkerApprovalRequest",
-    "NodeWorkerClarificationRequest",
-    "NodeWorkerError",
-    "NodeWorkerOpenRequest",
-    "NodeWorkerPromptRequest",
-]

+ 0 - 3776
hermes-plugins/yaoyao/dashboard/group_orchestrator.py

@@ -1,3776 +0,0 @@
-"""Async scheduler for durable YaoYao group Agent runs.
-
-The store is the concurrency authority.  This module only owns process-local
-Gateway generations and moves every blocking SQLite/Gateway call off the
-Dashboard event loop.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from contextlib import AsyncExitStack, asynccontextmanager
-from dataclasses import dataclass, field
-import json
-import logging
-import math
-import re
-import threading
-import uuid
-from typing import Any, Awaitable, Callable, Mapping, Protocol
-
-from .group_gateway import SessionIdentity
-from .group_remote_gateway import GroupGatewayRouter
-from .group_protocol import MAX_MESSAGE_BYTES, MAX_TOOL_STATE_BYTES
-
-
-logger = logging.getLogger(__name__)
-
-DEFAULT_EVENT_QUEUE_SIZE = 256
-DEFAULT_COMPLETION_TIMEOUT = 15 * 60.0
-STREAM_FLUSH_INTERVAL = 0.05
-_ERROR_TEXT_LIMIT = 4096
-_TOOL_VALUE_LIMIT = 16 * 1024
-_TOOL_TEXT_LIMIT = 4096
-_TOOL_FINDING_LIMIT = 32
-_TOOL_COUNT_LIMIT = 128
-_TOOL_TRUNCATION_ID = "__hermes_group_tool_state_truncated__"
-_TOOL_STATE_INTERNAL_LIMIT = min(MAX_TOOL_STATE_BYTES, 192 * 1024)
-_PERSISTED_EVENTS = frozenset(
-    {
-        "message.start",
-        "message.delta",
-        "message.complete",
-        "reasoning.delta",
-        "tool.start",
-        "tool.complete",
-        "tool.output_risk",
-        "approval.request",
-        "clarify.request",
-        "clarify.expire",
-        "session.info",
-        "error",
-    }
-)
-_TERMINAL_RUN_STATUSES = frozenset({"completed", "failed", "interrupted"})
-_APPROVAL_CHOICES = frozenset({"once", "session", "always", "deny"})
-_STORE_RETRY_DELAYS = (0.01, 0.02, 0.04)
-_CLAIM_RETRY_MAX_SECONDS = 1.0
-_WORK_DISABLED_RETRY_SECONDS = 1.0
-_NO_REPLY_TOKEN = "[[YAOYAO_NO_REPLY_V1]]"
-_NO_REPLY_RESERVED_PATTERN = re.compile(r"\[\[YAOYAO_[A-Z0-9_]*(?:\]\])?")
-_HOST_FALLBACK_REPLY = (
-    "我还不能确定你希望我处理什么,请补充具体目标、范围,或明确需要我协调的 Agent。"
-)
-
-
-def _is_no_reply_content(value: object) -> bool:
-    return isinstance(value, str) and value.strip() == _NO_REPLY_TOKEN
-
-
-def _sanitize_no_reply_text(value: str) -> str:
-    return _NO_REPLY_RESERVED_PATTERN.sub("", value)
-
-
-def _log_failure_type(message: str, error: BaseException) -> None:
-    """Log stable context without persisting Gateway or Store exception text."""
-
-    logger.error("%s [errorType=%s]", message, type(error).__name__)
-
-
-class GroupOrchestratorError(RuntimeError):
-    """Raised for an invalid scheduler lifecycle or local runtime collision."""
-
-
-class _Store(Protocol):
-    def initialize(self) -> None: ...
-
-    def recover_after_restart(self) -> list[str]: ...
-
-    def claim_next_runnable_run(self) -> dict[str, object] | None: ...
-
-    def read_run_projection(self, run_id: str) -> dict[str, object]: ...
-
-    def prepare_run_session_configuration(
-        self, run_id: str, configuration: Mapping[str, object]
-    ) -> bool: ...
-
-    def bind_run_runtime(
-        self, run_id: str, runtime_session_id: str
-    ) -> dict[str, object]: ...
-
-    def commit_prompt_submission(
-        self, run_id: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-    def upsert_agent_message(
-        self, run_id: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-    def settle_run(self, run_id: str, **kwargs: object) -> dict[str, object]: ...
-
-    def transition_run(
-        self, run_id: str, status: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-    def get_run(self, run_id: str) -> dict[str, object]: ...
-
-    def get_message(self, message_id: str) -> dict[str, object]: ...
-
-    def get_room(self, room_id: str) -> dict[str, object]: ...
-
-    def get_interaction(self, interaction_id: str) -> dict[str, object]: ...
-
-    def list_pending_cascades(self, **kwargs: object) -> dict[str, object]: ...
-
-    def complete_cascade(self, source_run_id: str) -> dict[str, object]: ...
-
-    def interrupt_agent_with_runtime_targets(
-        self, room_id: str, agent_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def archive_room_with_runtime_targets(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def restore_room(self, room_id: str, command: Mapping[str, object]) -> dict[str, object]: ...
-
-    def archive_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def restore_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def create_room(self, command: Mapping[str, object]) -> dict[str, object]: ...
-
-    def update_room(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def update_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def mark_topic_read(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def add_agent(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]: ...
-
-    def update_agent_with_runtime_targets(
-        self,
-        room_id: str,
-        agent_id: str,
-        command: Mapping[str, object],
-    ) -> dict[str, object]: ...
-
-    def delete_agent_with_runtime_targets(
-        self,
-        room_id: str,
-        agent_id: str,
-        command: Mapping[str, object],
-    ) -> dict[str, object]: ...
-
-    def create_human_message(
-        self,
-        room_id: str,
-        *,
-        request_id: str,
-        client_message_id: str,
-        content: str,
-        mention_agent_ids: list[str],
-        topic_id: str | None = None,
-    ) -> dict[str, object]: ...
-
-    def create_gateway_interaction(
-        self, run_id: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-    def expire_interaction(self, interaction_id: str) -> dict[str, object]: ...
-
-    def begin_interaction_response(
-        self, room_id: str, interaction_id: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-    def finish_interaction_response(
-        self, request_id: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-    def fail_interaction_response(
-        self, request_id: str, **kwargs: object
-    ) -> dict[str, object]: ...
-
-
-class _Gateway(Protocol):
-    transport: Any
-
-    def create_session(
-        self,
-        profile: str,
-        title: str,
-        cwd: str,
-        seed_messages: list[dict[str, Any]],
-        configuration: dict[str, Any] | None = None,
-    ) -> SessionIdentity: ...
-
-    def resume_session(self, profile: str, stored_id: str) -> SessionIdentity: ...
-
-    def submit_prompt(self, runtime_id: str, text: str) -> None: ...
-
-    def interrupt(self, runtime_id: str) -> None: ...
-
-    def close(self, runtime_id: str) -> bool: ...
-
-    def respond_approval(self, runtime_id: str, choice: str) -> int: ...
-
-    def respond_clarification(self, request_id: str, answer: str) -> str: ...
-
-    def shutdown(self) -> None: ...
-
-
-GatewayFactory = Callable[[Callable[[str, str, dict[str, object]], None]], _Gateway]
-
-
-@dataclass(frozen=True)
-class _GatewayEvent:
-    runtime_id: str
-    generation: int
-    event_type: str
-    payload: dict[str, object]
-
-
-@dataclass
-class _RuntimeState:
-    run_id: str
-    room_id: str
-    topic_id: str
-    agent_id: str
-    runtime_id: str
-    generation: int
-    expected_stored_id: str | None
-    session_stored_id: str
-    expected_context_seq: int
-    through_seq: int
-    profile: str = ""
-    reply_mode: str = "mentioned"
-    required_reply: bool = False
-    automatic_published: bool = False
-    had_visible_interaction: bool = False
-    prompt_ready: asyncio.Event = field(default_factory=asyncio.Event)
-    finished: asyncio.Event = field(default_factory=asyncio.Event)
-    terminal_info_received: asyncio.Event = field(default_factory=asyncio.Event)
-    finalize_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
-    mutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
-    pending_events: asyncio.Queue[_GatewayEvent | None] = field(
-        default_factory=lambda: asyncio.Queue(maxsize=64)
-    )
-    event_task: asyncio.Task[None] | None = None
-    grace_task: asyncio.Task[None] | None = None
-    inflight_calls: set[asyncio.Task[object]] = field(default_factory=set)
-    mutation_tasks: set[asyncio.Task[dict[str, object]]] = field(default_factory=set)
-    content: str = ""
-    reasoning: str = ""
-    tool_state: list[dict[str, object]] = field(default_factory=list)
-    tool_indexes: dict[str, int] = field(default_factory=dict)
-    clarification_ids: dict[str, str] = field(default_factory=dict)
-    pending_interaction_ids: set[str] = field(default_factory=set)
-    stream_dirty: bool = False
-    last_stream_flush: float = 0.0
-    approval_ordinal: int = 0
-    complete_seen: bool = False
-    complete_index: int = 0
-    event_index: int = 0
-    terminal_status: str | None = None
-    terminal_error: str = ""
-    actual_model: str | None = None
-    actual_provider: str | None = None
-    actual_reasoning_effort: str | None = None
-    actual_fast_mode: bool | None = None
-    settle_error: BaseException | None = None
-    prompt_committed: bool = False
-    overflowed: bool = False
-    finalizing: bool = False
-
-
-@dataclass
-class _AgentLockState:
-    lock: asyncio.Lock = field(default_factory=asyncio.Lock)
-    users: int = 0
-
-
-def _required_mapping(value: object, field_name: str) -> Mapping[str, object]:
-    if not isinstance(value, Mapping):
-        raise GroupOrchestratorError(f"{field_name} must be an object")
-    return value
-
-
-def _required_string(value: object, field_name: str) -> str:
-    if not isinstance(value, str) or not value:
-        raise GroupOrchestratorError(f"{field_name} must be a non-empty string")
-    return value
-
-
-def _required_string_allowing_empty(value: object, field_name: str) -> str:
-    if not isinstance(value, str):
-        raise GroupOrchestratorError(f"{field_name} must be a string")
-    return value
-
-
-def _optional_string(value: object, field_name: str) -> str | None:
-    if value is None:
-        return None
-    return _required_string(value, field_name)
-
-
-def _required_nonnegative_int(value: object, field_name: str) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or value < 0:
-        raise GroupOrchestratorError(f"{field_name} must be a non-negative integer")
-    return value
-
-
-def _required_bool(value: object, field_name: str) -> bool:
-    if not isinstance(value, bool):
-        raise GroupOrchestratorError(f"{field_name} must be a boolean")
-    return value
-
-
-def _strict_json_copy(value: object, field_name: str) -> object:
-    try:
-        encoded = json.dumps(
-            value,
-            ensure_ascii=False,
-            sort_keys=True,
-            separators=(",", ":"),
-            allow_nan=False,
-        )
-        encoded.encode("utf-8")
-        return json.loads(encoded)
-    except (TypeError, ValueError, UnicodeEncodeError, json.JSONDecodeError) as error:
-        raise GroupOrchestratorError(f"{field_name} must be strict JSON") from error
-
-
-def build_run_prompt(
-    projection: Mapping[str, object],
-    room_agents: list[Mapping[str, object]] | None = None,
-) -> str:
-    """Build a deterministic prompt from the Store's bounded projection."""
-
-    run = _required_mapping(projection.get("run"), "projection.run")
-    room = _required_mapping(projection.get("room"), "projection.room")
-    agent = _required_mapping(projection.get("agent"), "projection.agent")
-    messages = projection.get("messages")
-    if not isinstance(messages, list) or not all(
-        isinstance(message, Mapping) for message in messages
-    ):
-        raise GroupOrchestratorError("projection.messages must be a list of objects")
-    envelope = {
-        "agent": {
-            "displayName": _required_string(
-                agent.get("displayName"), "projection.agent.displayName"
-            ),
-            "id": _required_string(agent.get("id"), "projection.agent.id"),
-            "description": _required_string_allowing_empty(
-                agent.get("description", ""), "projection.agent.description"
-            ),
-            "isHost": _required_bool(
-                agent.get("isHost", False), "projection.agent.isHost"
-            ),
-        },
-        "messages": _strict_json_copy(messages, "projection.messages"),
-        "omittedSummary": _strict_json_copy(
-            projection.get("omittedSummary"), "projection.omittedSummary"
-        ),
-        "room": {
-            "id": _required_string(room.get("id"), "projection.room.id"),
-            "name": _required_string(room.get("name"), "projection.room.name"),
-            "instructions": _required_string_allowing_empty(
-                room.get("instructions", ""), "projection.room.instructions"
-            ),
-            "maxReplyRounds": room.get("maxReplyRounds", 3),
-            "orchestrationMode": _required_string(
-                room.get("orchestrationMode", "free"),
-                "projection.room.orchestrationMode",
-            ),
-        },
-        "run": {
-            "id": _required_string(run.get("id"), "projection.run.id"),
-            "topicId": _required_string(
-                run.get("topicId"), "projection.run.topicId"
-            ),
-            "rootMessageId": _required_string(
-                run.get("rootMessageId"), "projection.run.rootMessageId"
-            ),
-            "triggerMessageId": _required_string(
-                run.get("triggerMessageId"), "projection.run.triggerMessageId"
-            ),
-            "replyMode": _required_string(
-                run.get("replyMode", "mentioned"), "projection.run.replyMode"
-            ),
-            "requiredReply": _required_bool(
-                run.get("requiredReply", False), "projection.run.requiredReply"
-            ),
-        },
-        "throughSeq": _required_nonnegative_int(
-            projection.get("throughSeq"), "projection.throughSeq"
-        ),
-        "version": 1,
-    }
-    members: list[dict[str, str]] = []
-    for candidate in room_agents or []:
-        if candidate.get("enabled") is not True:
-            continue
-        members.append(
-            {
-                "displayName": _required_string(
-                    candidate.get("displayName"), "roomAgent.displayName"
-                ),
-                "id": _required_string(candidate.get("id"), "roomAgent.id"),
-            }
-        )
-    members.sort(key=lambda item: (item["displayName"].casefold(), item["id"]))
-    envelope["roomAgents"] = members
-    encoded = json.dumps(
-        envelope,
-        ensure_ascii=False,
-        sort_keys=True,
-        separators=(",", ":"),
-        allow_nan=False,
-    )
-    automatic_rule = ""
-    host_flow = envelope["room"]["orchestrationMode"] == "host"
-    if envelope["run"]["requiredReply"] and host_flow:
-        automatic_rule = (
-            "你持有本话题当前唯一发言令牌,必须公开处理。请根据最新上下文动态决定下一步:"
-            "有依赖关系时只 @下一位成员;任务相互独立时可以同时使用多个精确 @显示名 或 @all,"
-            "系统会并列执行并在整批结束后统一交还给你复核;"
-            "若任务已经完成,直接给出最终答复且不要 @任何成员;也可以发起澄清请求。"
-            "禁止保持静默,禁止输出任何 YAOYAO_NO_REPLY 标记。"
-        )
-    elif envelope["run"]["requiredReply"]:
-        automatic_rule = (
-            "你是本房间唯一管理员。该用户消息没有有效 @,你必须公开处理;"
-            "禁止保持静默,禁止输出任何 YAOYAO_NO_REPLY 标记。必须三选一:"
-            "直接回答;使用成员列表中的精确 @显示名 转派;或发起澄清请求。"
-        )
-    elif envelope["run"]["replyMode"] == "automatic":
-        automatic_rule = (
-            f"若触发内容与自己的职责无关,禁止调用工具、禁止@成员,且完整答复只能是"
-            f"{_NO_REPLY_TOKEN};正常答复绝不能包含该标记。"
-        )
-    elif host_flow and not envelope["agent"]["isHost"]:
-        automatic_rule = (
-            "你正在执行管理员委派的当前步骤。只回答本步骤,不要 @任何成员;"
-            "完成后系统会把结果交还管理员复核并决定下一步。"
-        )
-    collaboration_rule = (
-        "管理员协调中只有管理员可以调度成员;成员可以按依赖串行,也可以成批并列执行。"
-        if host_flow
-        else "仅在确实需要成员协作时,使用成员列表中的精确 @显示名 或 @all 发起下一轮。"
-    )
-    instructions_rule = (
-        "GROUP_CONTEXT_JSON.room.instructions 是本房间的长期说明、协作规则和形式准则;"
-        "必须在本次答复和工具使用中遵守。\n"
-        if envelope["room"]["instructions"]
-        else ""
-    )
-    return (
-        "你正在 Hermes 多设备群聊中回复。只输出要发送到公共房间的答复;"
-        f"{collaboration_rule}\n"
-        f"{instructions_rule}"
-        f"{automatic_rule}\n"
-        f"runId={envelope['run']['id']} roomId={envelope['room']['id']} "
-        f"agentId={envelope['agent']['id']}\n"
-        f"GROUP_CONTEXT_JSON={encoded}"
-    )
-
-
-class GroupOrchestrator:
-    """Drive Store-claimed runs through one process-local Gateway adapter."""
-
-    def __init__(
-        self,
-        store: _Store,
-        *,
-        gateway_factory: GatewayFactory | None = None,
-        work_enabled: Callable[[], bool] | None = None,
-        event_queue_size: int = DEFAULT_EVENT_QUEUE_SIZE,
-        completion_timeout: float = DEFAULT_COMPLETION_TIMEOUT,
-    ) -> None:
-        if (
-            isinstance(event_queue_size, bool)
-            or not isinstance(event_queue_size, int)
-            or event_queue_size < 1
-        ):
-            raise ValueError("event_queue_size must be a positive integer")
-        if (
-            isinstance(completion_timeout, bool)
-            or not isinstance(completion_timeout, (int, float))
-            or not math.isfinite(completion_timeout)
-            or completion_timeout <= 0
-        ):
-            raise ValueError("completion_timeout must be positive")
-        self.store = store
-        self._gateway_factory: GatewayFactory = (
-            gateway_factory
-            if gateway_factory is not None
-            else lambda callback: GroupGatewayRouter(callback)
-        )
-        if work_enabled is not None and not callable(work_enabled):
-            raise ValueError("work_enabled must be callable")
-        self._work_enabled = work_enabled if work_enabled is not None else lambda: True
-        self._event_queue_size = event_queue_size
-        self._completion_timeout = float(completion_timeout)
-        self._loop: asyncio.AbstractEventLoop | None = None
-        self._loop_thread_id: int | None = None
-        self._gateway: _Gateway | None = None
-        self._event_queue: asyncio.Queue[_GatewayEvent | None] | None = None
-        self._event_task: asyncio.Task[None] | None = None
-        self._scheduler_task: asyncio.Task[None] | None = None
-        self._run_tasks: set[asyncio.Task[None]] = set()
-        self._control_tasks: set[asyncio.Task[dict[str, object]]] = set()
-        self._wake_event: asyncio.Event | None = None
-        self._shutdown_event: asyncio.Event | None = None
-        self._shutdown_complete: asyncio.Event | None = None
-        self._shutdown_error: BaseException | None = None
-        self._durable_failures: list[GroupOrchestratorError] = []
-        self._run_failures: list[BaseException] = []
-        self._failure_lock = threading.Lock()
-        self._lifecycle_lock: asyncio.Lock | None = None
-        self._started = False
-        self._closing = False
-        self._scheduler_busy = False
-        self._mapping_lock = threading.RLock()
-        self._runtime_states: dict[str, tuple[int, _RuntimeState]] = {}
-        self._next_generation = 0
-        self._agent_locks: dict[str, _AgentLockState] = {}
-        self._submission_locks: dict[str, _AgentLockState] = {}
-        self._room_locks: dict[str, _AgentLockState] = {}
-
-    @property
-    def event_queue_capacity(self) -> int:
-        return self._event_queue_size
-
-    @property
-    def active_run_count(self) -> int:
-        return len(self._run_tasks)
-
-    async def start(self) -> None:
-        """Initialize/recover durable state before exposing any scheduler work."""
-
-        if self._lifecycle_lock is None:
-            self._lifecycle_lock = asyncio.Lock()
-        async with self._lifecycle_lock:
-            if self._started:
-                return
-            if self._closing:
-                raise GroupOrchestratorError("Orchestrator is shutting down")
-            self._loop = asyncio.get_running_loop()
-            self._loop_thread_id = threading.get_ident()
-            try:
-                await self._run_owned_start_worker(
-                    self.store.initialize,
-                    task_name="yaoyao-group-store-initialize",
-                )
-                await self._run_owned_start_worker(
-                    self.store.recover_after_restart,
-                    task_name="yaoyao-group-store-recover",
-                )
-                self._event_queue = asyncio.Queue(maxsize=self._event_queue_size)
-                self._wake_event = asyncio.Event()
-                self._shutdown_event = asyncio.Event()
-                self._shutdown_complete = asyncio.Event()
-                self._shutdown_error = None
-                self._durable_failures = []
-                self._run_failures = []
-                await self._run_owned_start_worker(
-                    self._gateway_factory,
-                    self._gateway_event_callback,
-                    task_name="yaoyao-group-gateway-create",
-                    adopt=lambda gateway: setattr(self, "_gateway", gateway),
-                )
-                self._event_task = asyncio.create_task(
-                    self._consume_events(), name="yaoyao-group-events"
-                )
-                await asyncio.sleep(0)
-                self._scheduler_task = asyncio.create_task(
-                    self._scheduler(), name="yaoyao-group-scheduler"
-                )
-                await asyncio.sleep(0)
-                self._started = True
-                self.wake()
-            except BaseException:
-                await self._rollback_failed_start()
-                raise
-
-    async def _run_owned_start_worker(
-        self,
-        callback: Callable[..., object],
-        *args: object,
-        task_name: str,
-        adopt: Callable[[object], None] | None = None,
-    ) -> object:
-        """Wait out cancellation so a startup worker cannot outlive ownership."""
-
-        worker = asyncio.get_running_loop().create_task(
-            asyncio.to_thread(callback, *args), name=task_name
-        )
-        cancellation: asyncio.CancelledError | None = None
-        while not worker.done():
-            try:
-                await asyncio.shield(worker)
-            except asyncio.CancelledError as error:
-                if cancellation is None:
-                    cancellation = error
-        try:
-            result = worker.result()
-        except BaseException:
-            if cancellation is not None:
-                raise cancellation
-            raise
-        if adopt is not None:
-            adopt(result)
-        if cancellation is not None:
-            raise cancellation
-        return result
-
-    async def _rollback_failed_start(self) -> None:
-        """Reverse a partial start without invoking normal settlement paths."""
-
-        for task in (self._scheduler_task, self._event_task):
-            if task is not None and not task.done():
-                task.cancel()
-        tasks = tuple(
-            task
-            for task in (self._scheduler_task, self._event_task)
-            if task is not None
-        )
-        if tasks:
-            await asyncio.gather(*tasks, return_exceptions=True)
-        gateway = self._gateway
-        if gateway is not None:
-            drain: Callable[[float | None], object] | None = None
-            try:
-                transport = getattr(gateway, "transport", None)
-                candidate = getattr(transport, "drain", None)
-                if callable(candidate):
-                    drain = candidate
-            except BaseException as error:  # noqa: BLE001 - shutdown still runs
-                _log_failure_type("Failed to inspect a partial Gateway startup", error)
-            if callable(drain):
-                try:
-                    await self._run_owned_start_worker(
-                        drain,
-                        None,
-                        task_name="yaoyao-group-gateway-rollback-drain",
-                    )
-                except BaseException as error:  # noqa: BLE001 - keep primary
-                    _log_failure_type(
-                        "Failed to drain a partial Gateway startup", error
-                    )
-            try:
-                await self._run_owned_start_worker(
-                    gateway.shutdown,
-                    task_name="yaoyao-group-gateway-rollback-shutdown",
-                )
-            except BaseException as error:  # noqa: BLE001 - preserve primary
-                _log_failure_type(
-                    "Failed to roll back YaoYao group Gateway startup", error
-                )
-        self._started = False
-        self._gateway = None
-        self._event_task = None
-        self._scheduler_task = None
-        self._event_queue = None
-        self._wake_event = None
-        self._shutdown_event = None
-        self._shutdown_complete = None
-        self._loop = None
-        self._loop_thread_id = None
-
-    def wake(self) -> None:
-        """Idempotently signal that queued durable work may now be runnable."""
-
-        loop = self._loop
-        wake_event = self._wake_event
-        if loop is None or wake_event is None or self._closing:
-            return
-        if threading.get_ident() == self._loop_thread_id:
-            wake_event.set()
-            return
-        try:
-            loop.call_soon_threadsafe(wake_event.set)
-        except RuntimeError:
-            return
-
-    async def drain_once(self, *, timeout: float = 5.0) -> None:
-        """Wake the scheduler and wait until its current durable work is idle."""
-
-        if not self._started:
-            raise GroupOrchestratorError("Orchestrator is not started")
-        if timeout <= 0:
-            raise ValueError("timeout must be positive")
-        self.wake()
-
-        async def wait_idle() -> None:
-            while True:
-                wake_event = self._wake_event
-                event_queue = self._event_queue
-                if (
-                    wake_event is not None
-                    and event_queue is not None
-                    and not wake_event.is_set()
-                    and not self._scheduler_busy
-                    and not self._run_tasks
-                    and event_queue.empty()
-                ):
-                    return
-                await asyncio.sleep(0.001)
-
-        await asyncio.wait_for(wait_idle(), timeout=timeout)
-
-    async def _tracked_control(
-        self,
-        operation: Callable[[], Awaitable[dict[str, object]]],
-        *,
-        task_name: str,
-        failure_message: str,
-    ) -> dict[str, object]:
-        """Shield one accepted mutation and expose it to orderly shutdown."""
-
-        if not self._started or self._closing:
-            raise GroupOrchestratorError("Orchestrator is not accepting controls")
-        task = asyncio.create_task(operation(), name=task_name)
-        self._control_tasks.add(task)
-
-        def finished(done: asyncio.Task[dict[str, object]]) -> None:
-            self._control_tasks.discard(done)
-            if done.cancelled():
-                return
-            try:
-                error = done.exception()
-            except asyncio.CancelledError:
-                return
-            if error is not None:
-                _log_failure_type(failure_message, error)
-
-        task.add_done_callback(finished)
-        return await asyncio.shield(task)
-
-    @staticmethod
-    def _public_command(value: Mapping[str, object]) -> dict[str, object]:
-        command = _strict_json_copy(value, "command")
-        if not isinstance(command, dict):
-            raise GroupOrchestratorError("command must be an object")
-        _required_string(command.get("requestId"), "command.requestId")
-        return command
-
-    async def create_room(self, *, command: Mapping[str, object]) -> dict[str, object]:
-        safe_command = self._public_command(command)
-        request_id = str(safe_command["requestId"])
-        return await self._tracked_control(
-            lambda: self._create_room(safe_command),
-            task_name=f"yaoyao-group-create-room-{request_id}",
-            failure_message="YaoYao group room creation failed",
-        )
-
-    async def _create_room(self, command: Mapping[str, object]) -> dict[str, object]:
-        result = await asyncio.to_thread(self.store.create_room, command)
-        if not isinstance(result, Mapping):
-            raise GroupOrchestratorError("Created room is invalid")
-        self.wake()
-        return dict(result)
-
-    async def update_room(
-        self, *, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        safe_command = self._public_command(command)
-        request_id = str(safe_command["requestId"])
-        return await self._tracked_control(
-            lambda: self._update_room(room_id, safe_command),
-            task_name=f"yaoyao-group-update-room-{request_id}",
-            failure_message="YaoYao group room update failed",
-        )
-
-    async def _update_room(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            result = await asyncio.to_thread(self.store.update_room, room_id, command)
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError("Updated room is invalid")
-            self.wake()
-            return dict(result)
-
-    async def update_topic(
-        self, *, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(topic_id, "topicId")
-        safe_command = self._public_command(command)
-        request_id = str(safe_command["requestId"])
-        return await self._tracked_control(
-            lambda: self._update_topic(room_id, topic_id, safe_command),
-            task_name=f"yaoyao-group-update-topic-{request_id}",
-            failure_message="YaoYao group topic update failed",
-        )
-
-    async def _update_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            result = await asyncio.to_thread(
-                self.store.update_topic, room_id, topic_id, command
-            )
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError("Updated topic is invalid")
-            self.wake()
-            return dict(result)
-
-    async def archive_topic(
-        self, *, room_id: str, topic_id: str, request_id: str
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(topic_id, "topicId")
-        _required_string(request_id, "requestId")
-        return await self._tracked_control(
-            lambda: self._archive_topic(room_id, topic_id, request_id),
-            task_name=f"yaoyao-group-archive-topic-{request_id}",
-            failure_message="YaoYao group topic archive failed",
-        )
-
-    async def _archive_topic(
-        self, room_id: str, topic_id: str, request_id: str
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            with self._mapping_lock:
-                states = sorted(
-                    (state for _generation, state in self._runtime_states.values()
-                     if state.room_id == room_id and state.topic_id == topic_id),
-                    key=lambda state: (state.agent_id, state.runtime_id, state.generation),
-                )
-            async with AsyncExitStack() as stack:
-                for state in states:
-                    await stack.enter_async_context(self._submission_serial(state.agent_id))
-                    await stack.enter_async_context(state.mutation_lock)
-                current_states = self._current_owned_states(states)
-                envelope = await self._run_states_blocking(
-                    current_states, self.store.archive_topic, room_id, topic_id,
-                    {"requestId": request_id},
-                )
-                if not isinstance(envelope, Mapping):
-                    raise GroupOrchestratorError("Archived topic is invalid")
-                result = dict(envelope)
-                if result.get("id") != topic_id or result.get("archived") is not True:
-                    raise GroupOrchestratorError("Archived topic identity changed")
-                self.wake()
-                cleanup_errors = await self._cleanup_lifecycle_targets_locked(
-                    current_states, tuple(), room_id=room_id, topic_id=topic_id,
-                )
-                if cleanup_errors:
-                    raise GroupOrchestratorError(
-                        "Topic was archived durably, but Gateway cleanup failed: "
-                        + "; ".join(cleanup_errors)
-                    )
-                return result
-
-    async def restore_topic(
-        self, *, room_id: str, topic_id: str, request_id: str
-    ) -> dict[str, object]:
-        return await self._topic_lifecycle(
-            room_id, topic_id, request_id, self.store.restore_topic, "restore"
-        )
-
-    async def restore_room(
-        self, *, room_id: str, request_id: str
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(request_id, "requestId")
-        async with self._room_serial(room_id):
-            result = await asyncio.to_thread(
-                self.store.restore_room, room_id, {"requestId": request_id}
-            )
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError("Restored room is invalid")
-            self.wake()
-            return dict(result)
-
-    async def _topic_lifecycle(
-        self, room_id: str, topic_id: str, request_id: str,
-        function: Callable[..., object], label: str,
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(topic_id, "topicId")
-        _required_string(request_id, "requestId")
-        async with self._room_serial(room_id):
-            result = await asyncio.to_thread(
-                function, room_id, topic_id, {"requestId": request_id}
-            )
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError(f"{label.title()}d topic is invalid")
-            self.wake()
-            return dict(result)
-
-    async def mark_topic_read(
-        self, *, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(topic_id, "topicId")
-        safe_command = self._public_command(command)
-        request_id = str(safe_command["requestId"])
-        return await self._tracked_control(
-            lambda: self._mark_topic_read(room_id, topic_id, safe_command),
-            task_name=f"yaoyao-group-mark-topic-read-{request_id}",
-            failure_message="YaoYao group topic read update failed",
-        )
-
-    async def _mark_topic_read(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            result = await asyncio.to_thread(
-                self.store.mark_topic_read, room_id, topic_id, command
-            )
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError("Topic read response is invalid")
-            self.wake()
-            return dict(result)
-
-    async def add_agent(
-        self, *, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        safe_command = self._public_command(command)
-        request_id = str(safe_command["requestId"])
-        return await self._tracked_control(
-            lambda: self._add_agent(room_id, safe_command),
-            task_name=f"yaoyao-group-add-agent-{request_id}",
-            failure_message="YaoYao group Agent creation failed",
-        )
-
-    async def _add_agent(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            result = await asyncio.to_thread(self.store.add_agent, room_id, command)
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError("Created Agent is invalid")
-            self.wake()
-            return dict(result)
-
-    async def update_agent(
-        self,
-        *,
-        room_id: str,
-        agent_id: str,
-        command: Mapping[str, object],
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(agent_id, "agentId")
-        safe_command = self._public_command(command)
-        request_id = str(safe_command["requestId"])
-        return await self._tracked_control(
-            lambda: self._mutate_agent(
-                room_id=room_id,
-                agent_id=agent_id,
-                command=safe_command,
-                operation="update",
-            ),
-            task_name=f"yaoyao-group-update-agent-{request_id}",
-            failure_message="YaoYao group Agent update failed",
-        )
-
-    async def delete_agent(
-        self,
-        *,
-        room_id: str,
-        agent_id: str,
-        request_id: str,
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(agent_id, "agentId")
-        _required_string(request_id, "requestId")
-        return await self._tracked_control(
-            lambda: self._mutate_agent(
-                room_id=room_id,
-                agent_id=agent_id,
-                command={"requestId": request_id},
-                operation="delete",
-            ),
-            task_name=f"yaoyao-group-delete-agent-{request_id}",
-            failure_message="YaoYao group Agent deletion failed",
-        )
-
-    async def _mutate_agent(
-        self,
-        *,
-        room_id: str,
-        agent_id: str,
-        command: Mapping[str, object],
-        operation: str,
-    ) -> dict[str, object]:
-        if operation == "update":
-            store_method = self.store.update_agent_with_runtime_targets
-        elif operation == "delete":
-            store_method = self.store.delete_agent_with_runtime_targets
-        else:
-            raise GroupOrchestratorError("Unknown Agent mutation")
-        async with self._room_serial(room_id):
-            async with AsyncExitStack() as stack:
-                await stack.enter_async_context(self._submission_serial(agent_id))
-                with self._mapping_lock:
-                    states = sorted(
-                        (
-                            state
-                            for _generation, state in self._runtime_states.values()
-                            if state.room_id == room_id and state.agent_id == agent_id
-                        ),
-                        key=lambda state: (state.runtime_id, state.generation),
-                    )
-                for state in states:
-                    await stack.enter_async_context(state.mutation_lock)
-                current_states = self._current_owned_states(states)
-                envelope = await self._run_states_blocking(
-                    current_states,
-                    store_method,
-                    room_id,
-                    agent_id,
-                    command,
-                )
-                result, runtime_ids = self._validated_lifecycle_envelope(
-                    envelope, f"agent.{operation}"
-                )
-                if result.get("id") != agent_id or result.get("roomId") != room_id:
-                    raise GroupOrchestratorError("Mutated Agent identity changed")
-                if operation == "update":
-                    requested_enabled = command.get("enabled")
-                    if "enabled" in command and (
-                        not isinstance(requested_enabled, bool)
-                        or result.get("enabled") is not requested_enabled
-                    ):
-                        raise GroupOrchestratorError(
-                            "Updated Agent enabled state changed"
-                        )
-                    if requested_enabled is not False and runtime_ids:
-                        raise GroupOrchestratorError(
-                            "Non-disabling Agent update returned runtime targets"
-                        )
-                self.wake()
-                cleanup_errors = await self._cleanup_lifecycle_targets_locked(
-                    current_states,
-                    runtime_ids,
-                    room_id=room_id,
-                    agent_id=agent_id,
-                )
-                if cleanup_errors:
-                    raise GroupOrchestratorError(
-                        "Agent changed durably, but Gateway cleanup failed: "
-                        + "; ".join(cleanup_errors)
-                    )
-                return result
-
-    async def send_message(
-        self,
-        *,
-        room_id: str,
-        request_id: str,
-        client_message_id: str,
-        content: str,
-        mention_agent_ids: list[str],
-        topic_id: str | None = None,
-    ) -> dict[str, object]:
-        _required_string(room_id, "roomId")
-        _required_string(request_id, "requestId")
-        _required_string(client_message_id, "clientMessageId")
-        if not isinstance(content, str):
-            raise GroupOrchestratorError("content must be a string")
-        if not isinstance(mention_agent_ids, list):
-            raise GroupOrchestratorError("mentionAgentIds must be a list")
-        if topic_id is not None:
-            _required_string(topic_id, "topicId")
-        safe_mentions = [
-            _required_string(item, "mentionAgentIds") for item in mention_agent_ids
-        ]
-        return await self._tracked_control(
-            lambda: self._send_message(
-                room_id=room_id,
-                request_id=request_id,
-                client_message_id=client_message_id,
-                content=content,
-                mention_agent_ids=safe_mentions,
-                topic_id=topic_id,
-            ),
-            task_name=f"yaoyao-group-send-{request_id}",
-            failure_message="YaoYao group message submission failed",
-        )
-
-    async def _send_message(
-        self,
-        *,
-        room_id: str,
-        request_id: str,
-        client_message_id: str,
-        content: str,
-        mention_agent_ids: list[str],
-        topic_id: str | None,
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            async with AsyncExitStack() as stack:
-                for agent_id in sorted(set(mention_agent_ids)):
-                    await stack.enter_async_context(self._submission_serial(agent_id))
-                result = await asyncio.to_thread(
-                    self.store.create_human_message,
-                    room_id,
-                    request_id=request_id,
-                    client_message_id=client_message_id,
-                    content=content,
-                    mention_agent_ids=mention_agent_ids,
-                    topic_id=topic_id,
-                )
-                if not isinstance(result, Mapping):
-                    raise GroupOrchestratorError("Created message is invalid")
-            self.wake()
-            return dict(result)
-
-    async def interrupt_agent(
-        self,
-        *,
-        room_id: str,
-        agent_id: str,
-        request_id: str,
-    ) -> dict[str, object]:
-        """Durably interrupt one Agent, then clean only owned Gateway generations."""
-
-        _required_string(room_id, "roomId")
-        _required_string(agent_id, "agentId")
-        _required_string(request_id, "requestId")
-        if not self._started or self._closing:
-            raise GroupOrchestratorError("Orchestrator is not accepting controls")
-        task = asyncio.create_task(
-            self._interrupt_agent(
-                room_id=room_id,
-                agent_id=agent_id,
-                request_id=request_id,
-            ),
-            name=f"yaoyao-group-interrupt-{request_id}",
-        )
-        self._control_tasks.add(task)
-
-        def finished(done: asyncio.Task[dict[str, object]]) -> None:
-            self._control_tasks.discard(done)
-            if done.cancelled():
-                return
-            try:
-                error = done.exception()
-            except asyncio.CancelledError:
-                return
-            if error is not None:
-                _log_failure_type("YaoYao group Agent interrupt failed", error)
-
-        task.add_done_callback(finished)
-        return await asyncio.shield(task)
-
-    async def archive_room(
-        self,
-        *,
-        room_id: str,
-        request_id: str,
-    ) -> dict[str, object]:
-        """Archive one room durably before cleaning its owned runtimes."""
-
-        _required_string(room_id, "roomId")
-        _required_string(request_id, "requestId")
-        return await self._tracked_control(
-            lambda: self._archive_room(room_id=room_id, request_id=request_id),
-            task_name=f"yaoyao-group-archive-{request_id}",
-            failure_message="YaoYao group room archive failed",
-        )
-
-    async def _archive_room(
-        self,
-        *,
-        room_id: str,
-        request_id: str,
-    ) -> dict[str, object]:
-        async with self._room_serial(room_id):
-            room = await asyncio.to_thread(
-                self.store.get_room, room_id, include_archived=True
-            )
-            agents = room.get("agents") if isinstance(room, Mapping) else None
-            if not isinstance(agents, list):
-                raise GroupOrchestratorError("room.agents must be a list")
-            agent_ids = sorted(
-                {
-                    _required_string(
-                        agent.get("id") if isinstance(agent, Mapping) else None,
-                        "room.agent.id",
-                    )
-                    for agent in agents
-                }
-            )
-            async with AsyncExitStack() as stack:
-                for agent_id in agent_ids:
-                    await stack.enter_async_context(self._submission_serial(agent_id))
-                with self._mapping_lock:
-                    states = sorted(
-                        (
-                            state
-                            for _generation, state in self._runtime_states.values()
-                            if state.room_id == room_id
-                        ),
-                        key=lambda state: (
-                            state.agent_id,
-                            state.runtime_id,
-                            state.generation,
-                        ),
-                    )
-                for state in states:
-                    await stack.enter_async_context(state.mutation_lock)
-                current_states = self._current_owned_states(states)
-                envelope = await self._run_states_blocking(
-                    current_states,
-                    self.store.archive_room_with_runtime_targets,
-                    room_id,
-                    {"requestId": request_id},
-                )
-                result, runtime_ids = self._validated_lifecycle_envelope(
-                    envelope, "archive"
-                )
-                if result.get("id") != room_id or result.get("archived") is not True:
-                    raise GroupOrchestratorError("Archived room identity changed")
-                self.wake()
-                cleanup_errors = await self._cleanup_lifecycle_targets_locked(
-                    current_states,
-                    runtime_ids,
-                    room_id=room_id,
-                )
-                if cleanup_errors:
-                    raise GroupOrchestratorError(
-                        "Room was archived durably, but Gateway cleanup failed: "
-                        + "; ".join(cleanup_errors)
-                    )
-                return result
-
-    def _current_owned_states(self, states: list[_RuntimeState]) -> list[_RuntimeState]:
-        current_states: list[_RuntimeState] = []
-        with self._mapping_lock:
-            for state in states:
-                if self._runtime_states.get(state.runtime_id) == (
-                    state.generation,
-                    state,
-                ):
-                    current_states.append(state)
-        return current_states
-
-    @staticmethod
-    def _validated_lifecycle_envelope(
-        value: object, field_name: str
-    ) -> tuple[dict[str, object], tuple[str, ...]]:
-        envelope = _required_mapping(value, field_name)
-        result = _required_mapping(envelope.get("result"), f"{field_name}.result")
-        raw_runtime_ids = envelope.get("runtimeSessionIds")
-        if not isinstance(raw_runtime_ids, list) or len(raw_runtime_ids) > 8:
-            raise GroupOrchestratorError(
-                f"{field_name}.runtimeSessionIds must be a bounded list"
-            )
-        runtime_ids = tuple(
-            _required_string(item, f"{field_name}.runtimeSessionIds")
-            for item in raw_runtime_ids
-        )
-        if len(set(runtime_ids)) != len(runtime_ids):
-            raise GroupOrchestratorError(
-                f"{field_name}.runtimeSessionIds contains duplicates"
-            )
-        return dict(result), runtime_ids
-
-    async def _cleanup_lifecycle_targets_locked(
-        self,
-        states: list[_RuntimeState],
-        runtime_ids: tuple[str, ...],
-        *,
-        room_id: str,
-        agent_id: str | None = None,
-        topic_id: str | None = None,
-    ) -> list[str]:
-        owned = {
-            state.runtime_id: state
-            for state in states
-            if state.room_id == room_id
-            and (agent_id is None or state.agent_id == agent_id)
-            and (topic_id is None or state.topic_id == topic_id)
-        }
-        cleanup_errors: list[str] = []
-        replay_runtime_ids = set(runtime_ids)
-        ordered_runtime_ids = list(runtime_ids)
-        ordered_runtime_ids.extend(
-            runtime_id
-            for runtime_id in sorted(owned)
-            if runtime_id not in replay_runtime_ids
-        )
-        for runtime_id in ordered_runtime_ids:
-            state = owned.get(runtime_id)
-            if state is None:
-                continue
-            with self._mapping_lock:
-                current = self._runtime_states.get(runtime_id)
-            if current != (state.generation, state):
-                continue
-            try:
-                durable_run = await self._run_state_blocking(
-                    state, self.store.get_run, state.run_id
-                )
-            except Exception:  # noqa: BLE001 - never clean an unverified owner
-                cleanup_errors.append(f"verify {runtime_id}")
-                continue
-            if (
-                not isinstance(durable_run, Mapping)
-                or durable_run.get("status") not in _TERMINAL_RUN_STATUSES
-                or durable_run.get("runtimeSessionId") is not None
-            ):
-                # The idempotency replay may name a runtime id that has since
-                # been reused by a newer generation.  Never clean that owner.
-                continue
-            error = await self._close_durably_interrupted_state_locked(state)
-            if error:
-                cleanup_errors.append(error)
-        return cleanup_errors
-
-    async def _interrupt_agent(
-        self,
-        *,
-        room_id: str,
-        agent_id: str,
-        request_id: str,
-    ) -> dict[str, object]:
-        async with self._submission_serial(agent_id):
-            with self._mapping_lock:
-                states = sorted(
-                    (
-                        state
-                        for _generation, state in self._runtime_states.values()
-                        if state.room_id == room_id and state.agent_id == agent_id
-                    ),
-                    key=lambda state: (state.runtime_id, state.generation),
-                )
-            async with AsyncExitStack() as stack:
-                for state in states:
-                    await stack.enter_async_context(state.mutation_lock)
-                current_states: list[_RuntimeState] = []
-                with self._mapping_lock:
-                    for state in states:
-                        if self._runtime_states.get(state.runtime_id) == (
-                            state.generation,
-                            state,
-                        ):
-                            current_states.append(state)
-                if any(
-                    state.finalizing and state.settle_error is not None
-                    for state in current_states
-                ):
-                    raise GroupOrchestratorError("Agent runtime is already finalizing")
-                envelope = await self._run_states_blocking(
-                    current_states,
-                    self.store.interrupt_agent_with_runtime_targets,
-                    room_id,
-                    agent_id,
-                    {"requestId": request_id},
-                )
-                result, run_ids, runtime_ids = self._validated_interrupt_envelope(
-                    envelope,
-                    room_id=room_id,
-                    agent_id=agent_id,
-                )
-                cleanup_errors: list[str] = []
-                for runtime_id in runtime_ids:
-                    with self._mapping_lock:
-                        current = self._runtime_states.get(runtime_id)
-                    if current is None:
-                        continue
-                    generation, state = current
-                    if (
-                        state not in current_states
-                        or generation != state.generation
-                        or state.room_id != room_id
-                        or state.agent_id != agent_id
-                        or state.run_id not in run_ids
-                    ):
-                        # A replayed target must never affect a reused runtime id.
-                        continue
-                    error = await self._close_durably_interrupted_state_locked(state)
-                    if error:
-                        cleanup_errors.append(error)
-                if cleanup_errors:
-                    raise GroupOrchestratorError(
-                        "Agent was interrupted durably, but Gateway cleanup failed: "
-                        + "; ".join(cleanup_errors)
-                    )
-                return result
-
-    @staticmethod
-    def _validated_interrupt_envelope(
-        value: object,
-        *,
-        room_id: str,
-        agent_id: str,
-    ) -> tuple[dict[str, object], set[str], tuple[str, ...]]:
-        envelope = _required_mapping(value, "interrupt")
-        result_value = _required_mapping(envelope.get("result"), "interrupt.result")
-        if (
-            result_value.get("roomId") != room_id
-            or result_value.get("agentId") != agent_id
-        ):
-            raise GroupOrchestratorError("Interrupt scope changed")
-
-        def string_list(raw: object, field_name: str) -> tuple[str, ...]:
-            if not isinstance(raw, list) or len(raw) > 8:
-                raise GroupOrchestratorError(f"{field_name} must be a bounded list")
-            values = tuple(_required_string(item, field_name) for item in raw)
-            if len(set(values)) != len(values):
-                raise GroupOrchestratorError(f"{field_name} contains duplicates")
-            return values
-
-        run_ids = string_list(
-            result_value.get("interruptedRunIds"),
-            "interrupt.result.interruptedRunIds",
-        )
-        runtime_ids = string_list(
-            envelope.get("runtimeSessionIds"),
-            "interrupt.runtimeSessionIds",
-        )
-        return dict(result_value), set(run_ids), runtime_ids
-
-    async def _close_durably_interrupted_state_locked(
-        self, state: _RuntimeState
-    ) -> str | None:
-        async with state.finalize_lock:
-            with self._mapping_lock:
-                current = self._runtime_states.get(state.runtime_id)
-            if current != (state.generation, state):
-                return None
-            state.finalizing = True
-            failures: list[str] = []
-            gateway = self._required_gateway()
-            try:
-                await self._run_state_blocking(
-                    state, gateway.interrupt, state.runtime_id
-                )
-            except Exception:  # noqa: BLE001 - close is still required
-                failures.append(f"interrupt {state.runtime_id}")
-            closed = False
-            try:
-                closed = (
-                    await self._run_state_blocking(
-                        state, gateway.close, state.runtime_id
-                    )
-                    is True
-                )
-                if not closed:
-                    failures.append(f"close {state.runtime_id}")
-            except Exception:  # noqa: BLE001 - durable state already won
-                failures.append(f"close {state.runtime_id}")
-            if closed:
-                self._remove_runtime(state)
-            state.settle_error = None
-            state.finished.set()
-            state.terminal_info_received.set()
-            state.pending_interaction_ids.clear()
-            current_task = asyncio.current_task()
-            for helper in (state.event_task, state.grace_task):
-                if helper is None or helper is current_task:
-                    continue
-                if not helper.done():
-                    helper.cancel()
-                await asyncio.gather(helper, return_exceptions=True)
-            return ", ".join(failures) or None
-
-    async def respond_approval(
-        self,
-        *,
-        room_id: str,
-        interaction_id: str,
-        request_id: str,
-        choice: str,
-        permanent: bool,
-    ) -> dict[str, object]:
-        if not self._started or self._closing:
-            raise GroupOrchestratorError("Orchestrator is not accepting controls")
-        if choice not in _APPROVAL_CHOICES:
-            raise ValueError("choice must be once, session, always, or deny")
-        if not isinstance(permanent, bool) or ((choice == "always") != permanent):
-            raise ValueError("permanent must be true exactly for choice=always")
-        replay = await self._terminal_interaction_replay(
-            room_id=room_id,
-            interaction_id=interaction_id,
-            request_id=request_id,
-            kind="approval",
-            response={"choice": choice, "permanent": permanent},
-        )
-        if replay is not None:
-            return replay
-        state, interaction = await self._interaction_runtime(
-            room_id, interaction_id, "approval"
-        )
-        task = asyncio.create_task(
-            self._respond_approval_for_runtime(
-                state=state,
-                interaction=interaction,
-                room_id=room_id,
-                interaction_id=interaction_id,
-                request_id=request_id,
-                choice=choice,
-                permanent=permanent,
-            ),
-            name=f"yaoyao-group-approval-{request_id}",
-        )
-        self._track_mutation_task(state, task)
-        return await asyncio.shield(task)
-
-    async def _respond_approval_for_runtime(
-        self,
-        *,
-        state: _RuntimeState,
-        interaction: Mapping[str, object],
-        room_id: str,
-        interaction_id: str,
-        request_id: str,
-        choice: str,
-        permanent: bool,
-    ) -> dict[str, object]:
-        async with state.mutation_lock:
-            self._require_current_runtime(state)
-            claim = await self._run_state_blocking(
-                state,
-                self.store.begin_interaction_response,
-                room_id,
-                interaction_id,
-                request_id=request_id,
-                kind="approval",
-                response={"choice": choice, "permanent": permanent},
-            )
-            if not isinstance(claim, Mapping):
-                raise GroupOrchestratorError("Approval claim is invalid")
-            if claim.get("state") in {"replay", "failed"}:
-                response = claim.get("response")
-                return dict(response) if isinstance(response, Mapping) else dict(claim)
-            payload = interaction.get("payload")
-            choices = payload.get("choices") if isinstance(payload, Mapping) else None
-            if (
-                not isinstance(choices, list)
-                or choice not in choices
-                or not all(item in _APPROVAL_CHOICES for item in choices)
-            ):
-                await self._run_state_blocking(
-                    state,
-                    self.store.fail_interaction_response,
-                    request_id,
-                    reason="Approval choice is not allowed by the pending card",
-                    uncertain=False,
-                )
-                raise ValueError("choice is not allowed by the pending approval")
-            try:
-                resolved = await self._run_state_blocking(
-                    state,
-                    self._required_gateway().respond_approval,
-                    state.runtime_id,
-                    choice,
-                )
-            except Exception:
-                await self._fail_unknown_interaction_response_locked(
-                    state, request_id, "Gateway approval outcome is unknown"
-                )
-                raise GroupOrchestratorError("Gateway approval outcome is unknown")
-            if (
-                isinstance(resolved, bool)
-                or not isinstance(resolved, int)
-                or resolved not in {0, 1}
-            ):
-                await self._fail_unknown_interaction_response_locked(
-                    state, request_id, "Gateway approval result is invalid"
-                )
-                raise GroupOrchestratorError("Gateway approval result is invalid")
-            public = {
-                "accepted": resolved == 1,
-                "interactionId": interaction_id,
-            }
-            try:
-                result = await self._store_retry(
-                    state,
-                    self.store.finish_interaction_response,
-                    request_id,
-                    response=public,
-                    interaction_status=("resolved" if resolved == 1 else "cancelled"),
-                )
-            except Exception:
-                await self._finalize_state_locked(
-                    state,
-                    outcome="failed",
-                    error="Durable approval response could not be completed",
-                    interrupt=True,
-                )
-                raise
-            state.pending_interaction_ids.discard(interaction_id)
-            return dict(result)
-
-    async def respond_clarification(
-        self,
-        *,
-        room_id: str,
-        interaction_id: str,
-        request_id: str,
-        response: str,
-    ) -> dict[str, object]:
-        if not self._started or self._closing:
-            raise GroupOrchestratorError("Orchestrator is not accepting controls")
-        if not isinstance(response, str) or not response.strip():
-            raise ValueError("response must not be blank")
-        self._bounded_text(response, "clarification response")
-        replay = await self._terminal_interaction_replay(
-            room_id=room_id,
-            interaction_id=interaction_id,
-            request_id=request_id,
-            kind="clarification",
-            response={"response": response},
-        )
-        if replay is not None:
-            return replay
-        state, interaction = await self._interaction_runtime(
-            room_id, interaction_id, "clarification"
-        )
-        task = asyncio.create_task(
-            self._respond_clarification_for_runtime(
-                state=state,
-                interaction=interaction,
-                room_id=room_id,
-                interaction_id=interaction_id,
-                request_id=request_id,
-                response=response,
-            ),
-            name=f"yaoyao-group-clarification-{request_id}",
-        )
-        self._track_mutation_task(state, task)
-        return await asyncio.shield(task)
-
-    @staticmethod
-    def _track_mutation_task(
-        state: _RuntimeState, task: asyncio.Task[dict[str, object]]
-    ) -> None:
-        state.mutation_tasks.add(task)
-
-        def finished(done: asyncio.Task[dict[str, object]]) -> None:
-            state.mutation_tasks.discard(done)
-            if done.cancelled():
-                return
-            try:
-                done.exception()
-            except asyncio.CancelledError:
-                return
-
-        task.add_done_callback(finished)
-
-    async def _respond_clarification_for_runtime(
-        self,
-        *,
-        state: _RuntimeState,
-        interaction: Mapping[str, object],
-        room_id: str,
-        interaction_id: str,
-        request_id: str,
-        response: str,
-    ) -> dict[str, object]:
-        async with state.mutation_lock:
-            self._require_current_runtime(state)
-            claim = await self._run_state_blocking(
-                state,
-                self.store.begin_interaction_response,
-                room_id,
-                interaction_id,
-                request_id=request_id,
-                kind="clarification",
-                response={"response": response},
-            )
-            if not isinstance(claim, Mapping):
-                raise GroupOrchestratorError("Clarification claim is invalid")
-            if claim.get("state") in {"replay", "failed"}:
-                replay = claim.get("response")
-                return dict(replay) if isinstance(replay, Mapping) else dict(claim)
-            payload = interaction.get("payload")
-            gateway_request_id = (
-                payload.get("gatewayRequestId")
-                if isinstance(payload, Mapping)
-                else None
-            )
-            gateway_request_id = _required_string(
-                gateway_request_id, "interaction.payload.gatewayRequestId"
-            )
-            try:
-                status = await self._run_state_blocking(
-                    state,
-                    self._required_gateway().respond_clarification,
-                    gateway_request_id,
-                    response,
-                )
-            except Exception:
-                await self._fail_unknown_interaction_response_locked(
-                    state, request_id, "Gateway clarification outcome is unknown"
-                )
-                raise GroupOrchestratorError("Gateway clarification outcome is unknown")
-            if status not in {"ok", "expired"}:
-                await self._fail_unknown_interaction_response_locked(
-                    state, request_id, "Gateway clarification result is invalid"
-                )
-                raise GroupOrchestratorError("Gateway clarification result is invalid")
-            public = {
-                "accepted": status == "ok",
-                "interactionId": interaction_id,
-            }
-            try:
-                result = await self._store_retry(
-                    state,
-                    self.store.finish_interaction_response,
-                    request_id,
-                    response=public,
-                    interaction_status=("resolved" if status == "ok" else "cancelled"),
-                )
-            except Exception:
-                await self._finalize_state_locked(
-                    state,
-                    outcome="failed",
-                    error="Durable clarification response could not be completed",
-                    interrupt=True,
-                )
-                raise
-            state.pending_interaction_ids.discard(interaction_id)
-            return dict(result)
-
-    async def _terminal_interaction_replay(
-        self,
-        *,
-        room_id: str,
-        interaction_id: str,
-        request_id: str,
-        kind: str,
-        response: Mapping[str, object],
-    ) -> dict[str, object] | None:
-        interaction = await asyncio.to_thread(
-            self.store.get_interaction, interaction_id
-        )
-        if (
-            not isinstance(interaction, Mapping)
-            or interaction.get("roomId") != room_id
-            or interaction.get("kind") != kind
-        ):
-            raise GroupOrchestratorError("Interaction is not in this room")
-        if interaction.get("status") == "pending":
-            return None
-        result = await asyncio.to_thread(
-            self.store.begin_interaction_response,
-            room_id,
-            interaction_id,
-            request_id=request_id,
-            kind=kind,
-            response=response,
-        )
-        if not isinstance(result, Mapping):
-            raise GroupOrchestratorError("Interaction replay is invalid")
-        replay = result.get("response")
-        if result.get("state") == "replay" and isinstance(replay, Mapping):
-            return dict(replay)
-        if result.get("state") == "failed":
-            return dict(result)
-        raise GroupOrchestratorError("Interaction is already terminal")
-
-    async def _interaction_runtime(
-        self, room_id: str, interaction_id: str, kind: str
-    ) -> tuple[_RuntimeState, Mapping[str, object]]:
-        interaction = await asyncio.to_thread(
-            self.store.get_interaction, interaction_id
-        )
-        if (
-            not isinstance(interaction, Mapping)
-            or interaction.get("roomId") != room_id
-            or interaction.get("kind") != kind
-            or interaction.get("status") != "pending"
-        ):
-            raise GroupOrchestratorError("Interaction is not pending in this room")
-        run_id = _required_string(interaction.get("runId"), "interaction.runId")
-        run = await asyncio.to_thread(self.store.get_run, run_id)
-        runtime_id = _required_string(
-            run.get("runtimeSessionId") if isinstance(run, Mapping) else None,
-            "run.runtimeSessionId",
-        )
-        with self._mapping_lock:
-            current = self._runtime_states.get(runtime_id)
-        if current is None or current[1].run_id != run_id:
-            raise GroupOrchestratorError("Interaction runtime is not active")
-        return current[1], interaction
-
-    def _require_current_runtime(self, state: _RuntimeState) -> None:
-        with self._mapping_lock:
-            current = self._runtime_states.get(state.runtime_id)
-        if (
-            current != (state.generation, state)
-            or state.finished.is_set()
-            or state.finalizing
-        ):
-            raise GroupOrchestratorError("Interaction runtime generation changed")
-
-    async def _fail_unknown_interaction_response_locked(
-        self, state: _RuntimeState, request_id: str, reason: str
-    ) -> None:
-        try:
-            await self._store_retry(
-                state,
-                self.store.fail_interaction_response,
-                request_id,
-                reason=reason,
-                uncertain=True,
-            )
-        except Exception:
-            logger.error("Failed to persist unknown interaction outcome")
-        await self._finalize_state_locked(
-            state, outcome="failed", error=reason, interrupt=True
-        )
-
-    async def shutdown(self) -> None:
-        """Stop claims, settle every owned runtime, drain, then close Gateway."""
-
-        if self._lifecycle_lock is None:
-            self._lifecycle_lock = asyncio.Lock()
-        wait_for_owner: asyncio.Event | None = None
-        completed_shutdown = False
-        async with self._lifecycle_lock:
-            if not self._started:
-                self._closing = True
-                completed_shutdown = bool(
-                    self._shutdown_complete is not None
-                    and self._shutdown_complete.is_set()
-                )
-                if not completed_shutdown:
-                    return
-                scheduler = None
-            elif self._closing:
-                wait_for_owner = self._shutdown_complete
-                scheduler = None
-            else:
-                self._closing = True
-                if self._shutdown_event is not None:
-                    self._shutdown_event.set()
-                if self._wake_event is not None:
-                    self._wake_event.set()
-                scheduler = self._scheduler_task
-        if completed_shutdown:
-            if self._shutdown_error is not None:
-                raise self._shutdown_error
-            return
-        if wait_for_owner is not None:
-            await wait_for_owner.wait()
-            if self._shutdown_error is not None:
-                raise self._shutdown_error
-            return
-
-        first_error: BaseException | None = None
-
-        def remember(error: BaseException) -> None:
-            nonlocal first_error
-            if first_error is None:
-                first_error = error
-
-        if scheduler is not None:
-            try:
-                await scheduler
-            except BaseException as error:  # noqa: BLE001 - cleanup continues
-                remember(error)
-
-        while self._run_tasks:
-            tasks = tuple(self._run_tasks)
-            try:
-                results = await asyncio.gather(*tasks, return_exceptions=True)
-            except BaseException as error:  # noqa: BLE001 - cleanup continues
-                remember(error)
-            else:
-                self._remember_task_results(results, remember)
-
-        while self._control_tasks:
-            tasks = tuple(self._control_tasks)
-            try:
-                results = await asyncio.gather(*tasks, return_exceptions=True)
-            except BaseException as error:  # noqa: BLE001 - cleanup continues
-                remember(error)
-            else:
-                self._remember_task_results(results, remember)
-
-        with self._failure_lock:
-            run_failures = tuple(self._run_failures)
-            durable_failures = tuple(self._durable_failures)
-        for error in (*run_failures, *durable_failures):
-            remember(error)
-
-        with self._mapping_lock:
-            remaining_states = [
-                state for _generation, state in self._runtime_states.values()
-            ]
-        for state in remaining_states:
-            if state.settle_error is not None:
-                remember(state.settle_error)
-            current_task = asyncio.current_task()
-            for helper in (state.event_task, state.grace_task):
-                if helper is None or helper is current_task:
-                    continue
-                if not helper.done():
-                    helper.cancel()
-                try:
-                    results = await asyncio.gather(helper, return_exceptions=True)
-                except BaseException as error:  # noqa: BLE001 - cleanup continues
-                    remember(error)
-                else:
-                    self._remember_task_results(results, remember)
-            pending_calls = tuple(state.inflight_calls)
-            if pending_calls:
-                try:
-                    results = await asyncio.gather(
-                        *pending_calls, return_exceptions=True
-                    )
-                except BaseException as error:  # noqa: BLE001 - cleanup continues
-                    remember(error)
-                else:
-                    self._remember_task_results(results, remember)
-            self._remove_runtime(state)
-            try:
-                await asyncio.to_thread(
-                    self._required_gateway().close, state.runtime_id
-                )
-            except BaseException as error:  # noqa: BLE001 - cleanup continues
-                remember(error)
-            state.finished.set()
-
-        gateway = self._gateway
-        if gateway is not None:
-            drain: Callable[[float | None], object] | None = None
-            try:
-                transport = getattr(gateway, "transport", None)
-                candidate = getattr(transport, "drain", None)
-                if callable(candidate):
-                    drain = candidate
-            except BaseException as error:  # noqa: BLE001 - shutdown still runs
-                remember(error)
-            if drain is not None:
-                try:
-                    await asyncio.to_thread(drain, None)
-                except BaseException as error:  # noqa: BLE001 - cleanup continues
-                    remember(error)
-            try:
-                await asyncio.to_thread(gateway.shutdown)
-            except BaseException as error:  # noqa: BLE001 - cleanup continues
-                remember(error)
-
-        try:
-            event_queue = self._event_queue
-            event_task = self._event_task
-            if event_queue is not None:
-                try:
-                    await event_queue.join()
-                    await event_queue.put(None)
-                except BaseException as error:  # noqa: BLE001 - completion must signal
-                    remember(error)
-            if event_task is not None:
-                try:
-                    await event_task
-                except BaseException as error:  # noqa: BLE001 - completion must signal
-                    remember(error)
-        finally:
-            async with self._lifecycle_lock:
-                self._started = False
-                self._gateway = None
-                self._scheduler_task = None
-                self._event_task = None
-                self._shutdown_error = first_error
-                if self._shutdown_complete is not None:
-                    self._shutdown_complete.set()
-        if first_error is not None:
-            raise first_error
-
-    @staticmethod
-    def _remember_task_results(
-        results: list[object], remember: Callable[[BaseException], None]
-    ) -> None:
-        for result in results:
-            if isinstance(result, BaseException) and not isinstance(
-                result, asyncio.CancelledError
-            ):
-                remember(result)
-
-    async def _scheduler(self) -> None:
-        wake_event = self._wake_event
-        shutdown_event = self._shutdown_event
-        if wake_event is None or shutdown_event is None:
-            raise GroupOrchestratorError("Scheduler started without lifecycle state")
-        claim_failure_count = 0
-        while True:
-            await wake_event.wait()
-            wake_event.clear()
-            if shutdown_event.is_set():
-                return
-            self._scheduler_busy = True
-            try:
-                if not await self._work_is_enabled():
-                    if await self._wait_for_disabled_work(shutdown_event, wake_event):
-                        return
-                    continue
-                try:
-                    more_cascades = await self._drain_pending_cascades()
-                except Exception:  # noqa: BLE001 - durable ledger remains pending
-                    claim_failure_count += 1
-                    delay = min(
-                        _STORE_RETRY_DELAYS[0]
-                        * (2 ** min(claim_failure_count - 1, 10)),
-                        _CLAIM_RETRY_MAX_SECONDS,
-                    )
-                    logger.error("Pending YaoYao group cascade temporarily failed")
-                    try:
-                        await asyncio.wait_for(shutdown_event.wait(), timeout=delay)
-                    except asyncio.TimeoutError:
-                        wake_event.set()
-                        continue
-                    return
-                if more_cascades:
-                    wake_event.set()
-                    continue
-                while not shutdown_event.is_set():
-                    if not await self._work_is_enabled():
-                        if await self._wait_for_disabled_work(
-                            shutdown_event, wake_event
-                        ):
-                            return
-                        break
-                    try:
-                        claimed = await asyncio.to_thread(
-                            self.store.claim_next_runnable_run
-                        )
-                    except Exception:  # noqa: BLE001 - keep scheduler alive
-                        claim_failure_count += 1
-                        delay = min(
-                            _STORE_RETRY_DELAYS[0]
-                            * (2 ** min(claim_failure_count - 1, 10)),
-                            _CLAIM_RETRY_MAX_SECONDS,
-                        )
-                        logger.error("YaoYao group run claim temporarily failed")
-                        try:
-                            await asyncio.wait_for(shutdown_event.wait(), timeout=delay)
-                        except asyncio.TimeoutError:
-                            continue
-                        return
-                    claim_failure_count = 0
-                    if claimed is None:
-                        break
-                    task = asyncio.create_task(
-                        self._run_claimed(claimed),
-                        name=f"yaoyao-group-run-{claimed.get('id', 'invalid')}",
-                    )
-                    self._run_tasks.add(task)
-                    task.add_done_callback(self._run_finished)
-            finally:
-                self._scheduler_busy = False
-
-    async def _work_is_enabled(self) -> bool:
-        try:
-            return await asyncio.to_thread(self._work_enabled) is True
-        except Exception as error:  # noqa: BLE001 - fail closed on config errors
-            _log_failure_type("YaoYao group work gate temporarily failed", error)
-            return False
-
-    @staticmethod
-    async def _wait_for_disabled_work(
-        shutdown_event: asyncio.Event,
-        wake_event: asyncio.Event,
-    ) -> bool:
-        try:
-            await asyncio.wait_for(
-                shutdown_event.wait(), timeout=_WORK_DISABLED_RETRY_SECONDS
-            )
-        except asyncio.TimeoutError:
-            wake_event.set()
-            return False
-        return True
-
-    async def _drain_pending_cascades(self) -> bool:
-        page = await asyncio.to_thread(self.store.list_pending_cascades, limit=32)
-        if not isinstance(page, Mapping):
-            raise GroupOrchestratorError("Pending cascade page is invalid")
-        items = page.get("items")
-        if not isinstance(items, list) or not all(
-            isinstance(item, Mapping) for item in items
-        ):
-            raise GroupOrchestratorError("Pending cascade items are invalid")
-        created = False
-        for item in items:
-            source_run_id = _required_string(
-                item.get("sourceRunId"), "cascade.sourceRunId"
-            )
-            result = await asyncio.to_thread(self.store.complete_cascade, source_run_id)
-            if not isinstance(result, Mapping):
-                raise GroupOrchestratorError("Cascade completion is invalid")
-            run_count = result.get("runCount")
-            if isinstance(run_count, bool) or not isinstance(run_count, int):
-                raise GroupOrchestratorError("Cascade run count is invalid")
-            created = created or run_count > 0
-        if created:
-            self.wake()
-        return page.get("nextCursor") is not None
-
-    def _run_finished(self, task: asyncio.Task[None]) -> None:
-        self._run_tasks.discard(task)
-        try:
-            error = task.exception()
-        except asyncio.CancelledError:
-            error = None
-        if error is not None:
-            with self._failure_lock:
-                self._run_failures.append(error)
-            _log_failure_type("YaoYao group run task failed", error)
-        self.wake()
-
-    async def _run_claimed(self, claimed: Mapping[str, object]) -> None:
-        run_id_value = claimed.get("id")
-        if not isinstance(run_id_value, str) or not run_id_value:
-            logger.error("Claimed YaoYao group run has no usable identity")
-            return
-        run_id = run_id_value
-        try:
-            claimed_agent_id = _required_string(claimed.get("agentId"), "run.agentId")
-            async with self._agent_serial(claimed_agent_id):
-                try:
-                    await self._run_claimed_for_agent(claimed, run_id)
-                except Exception:  # noqa: BLE001 - never strand a durable claim
-                    logger.exception("YaoYao group claimed run preparation failed")
-                    await self._fail_claim_without_projection(run_id)
-        except Exception:  # noqa: BLE001 - malformed claim still has run ID
-            logger.exception("YaoYao group claimed run identity is invalid")
-            await self._fail_claim_without_projection(run_id)
-
-    @asynccontextmanager
-    async def _agent_serial(self, agent_id: str):
-        async with self._keyed_serial(self._agent_locks, agent_id):
-            yield
-
-    @asynccontextmanager
-    async def _submission_serial(self, agent_id: str):
-        async with self._keyed_serial(self._submission_locks, agent_id):
-            yield
-
-    @asynccontextmanager
-    async def _room_serial(self, room_id: str):
-        async with self._keyed_serial(self._room_locks, room_id):
-            yield
-
-    @staticmethod
-    @asynccontextmanager
-    async def _keyed_serial(locks: dict[str, _AgentLockState], key: str):
-        entry = locks.get(key)
-        if entry is None:
-            entry = _AgentLockState()
-            locks[key] = entry
-        entry.users += 1
-        try:
-            async with entry.lock:
-                yield
-        finally:
-            entry.users -= 1
-            if entry.users == 0 and locks.get(key) is entry:
-                locks.pop(key, None)
-
-    async def _run_claimed_for_agent(
-        self, claimed: Mapping[str, object], run_id: str
-    ) -> None:
-        try:
-            projection = await asyncio.to_thread(self.store.read_run_projection, run_id)
-        except Exception:  # noqa: BLE001 - durable claim must be terminal
-            logger.exception("Failed to read YaoYao group run projection")
-            await self._fail_claim_without_projection(run_id)
-            return
-
-        run = _required_mapping(projection.get("run"), "projection.run")
-        room = _required_mapping(projection.get("room"), "projection.room")
-        agent = _required_mapping(projection.get("agent"), "projection.agent")
-        room_id = _required_string(room.get("id"), "projection.room.id")
-        topic_id = _required_string(run.get("topicId"), "projection.run.topicId")
-        agent_id = _required_string(agent.get("id"), "projection.agent.id")
-        if _required_string(run.get("id"), "projection.run.id") != run_id:
-            raise GroupOrchestratorError("projection run identity changed")
-        if agent_id != _required_string(claimed.get("agentId"), "run.agentId"):
-            raise GroupOrchestratorError("projection Agent identity changed")
-        configuration = {
-            "model": agent.get("model"),
-            "provider": agent.get("provider"),
-            "reasoning_effort": agent.get("reasoningEffort"),
-            "fast": agent.get("fastMode"),
-        }
-        try:
-            rotated = await asyncio.to_thread(
-                self.store.prepare_run_session_configuration,
-                run_id,
-                configuration,
-            )
-            if rotated:
-                projection = await asyncio.to_thread(
-                    self.store.read_run_projection, run_id
-                )
-                run = _required_mapping(projection.get("run"), "projection.run")
-                room = _required_mapping(projection.get("room"), "projection.room")
-                agent = _required_mapping(projection.get("agent"), "projection.agent")
-        except Exception:
-            logger.exception("Failed to prepare YaoYao group Agent configuration")
-            await self._fail_claim_without_projection(run_id)
-            return
-        profile = _required_string(agent.get("profile"), "projection.agent.profile")
-        node_id = _required_string(
-            agent.get("nodeId", "local"), "projection.agent.nodeId"
-        )
-        reply_mode = _required_string(run.get("replyMode"), "projection.run.replyMode")
-        if reply_mode not in {"mentioned", "automatic"}:
-            raise GroupOrchestratorError("projection.run.replyMode is invalid")
-        required_reply = _required_bool(
-            run.get("requiredReply", False), "projection.run.requiredReply"
-        )
-        if required_reply and reply_mode != "automatic":
-            raise GroupOrchestratorError(
-                "projection.run.requiredReply requires automatic replyMode"
-            )
-        display_name = _required_string(
-            agent.get("displayName"), "projection.agent.displayName"
-        )
-        room_name = _required_string(room.get("name"), "projection.room.name")
-        cwd_value = room.get("cwd", "")
-        if not isinstance(cwd_value, str):
-            raise GroupOrchestratorError("projection.room.cwd must be a string")
-        expected_stored_id = _optional_string(
-            agent.get("storedSessionId"), "projection.agent.storedSessionId"
-        )
-        expected_context_seq = _required_nonnegative_int(
-            agent.get("lastContextMessageSeq"),
-            "projection.agent.lastContextMessageSeq",
-        )
-        through_seq = _required_nonnegative_int(
-            projection.get("throughSeq"), "projection.throughSeq"
-        )
-        room_detail = await asyncio.to_thread(self.store.get_room, room_id)
-        room_agents = room_detail.get("agents")
-        if not isinstance(room_agents, list) or not all(
-            isinstance(item, Mapping) for item in room_agents
-        ):
-            raise GroupOrchestratorError("room.agents must be a list of objects")
-        prompt = build_run_prompt(projection, room_agents)
-        gateway = self._required_gateway()
-        try:
-            if expected_stored_id is None:
-                if node_id == "local":
-                    identity = await asyncio.to_thread(
-                        gateway.create_session,
-                        profile,
-                        f"[群聊] {room_name} · {display_name}",
-                        cwd_value,
-                        [],
-                        configuration,
-                    )
-                else:
-                    create_remote = getattr(
-                        gateway, "create_session_for_node", None
-                    )
-                    if not callable(create_remote):
-                        raise GroupOrchestratorError(
-                            "Gateway does not support remote nodes"
-                        )
-                    identity = await asyncio.to_thread(
-                        create_remote,
-                        node_id,
-                        profile,
-                        f"[群聊] {room_name} · {display_name}",
-                        "",
-                        [],
-                        configuration,
-                    )
-            else:
-                if node_id == "local":
-                    identity = await asyncio.to_thread(
-                        gateway.resume_session, profile, expected_stored_id
-                    )
-                else:
-                    resume_remote = getattr(
-                        gateway, "resume_session_for_node", None
-                    )
-                    if not callable(resume_remote):
-                        raise GroupOrchestratorError(
-                            "Gateway does not support remote nodes"
-                        )
-                    identity = await asyncio.to_thread(
-                        resume_remote,
-                        node_id,
-                        profile,
-                        expected_stored_id,
-                    )
-        except Exception:  # noqa: BLE001 - never create a fallback session
-            logger.error("YaoYao group session create/resume failed")
-            await self._settle_unbound_failed(
-                run_id,
-                expected_stored_id=expected_stored_id,
-                stored_session_id=expected_stored_id,
-                error="Agent session setup failed",
-            )
-            return
-
-        identity = self._validated_identity(identity)
-        if identity.running:
-            # A busy resume may belong to another consumer.  Persist rotation,
-            # but never adopt, submit to, interrupt, or close that runtime.
-            await self._settle_unbound_failed(
-                run_id,
-                expected_stored_id=expected_stored_id,
-                stored_session_id=identity.stored_id,
-                error="Agent stored session is already running",
-            )
-            return
-
-        bound = False
-        for delay in (*_STORE_RETRY_DELAYS, None):
-            try:
-                await asyncio.to_thread(
-                    self.store.bind_run_runtime, run_id, identity.runtime_id
-                )
-                bound = True
-                break
-            except Exception:  # noqa: BLE001 - exact bind replay is idempotent
-                if delay is None:
-                    try:
-                        durable = await asyncio.to_thread(self.store.get_run, run_id)
-                    except Exception:  # noqa: BLE001 - identity remains unknown
-                        durable = None
-                    bound = (
-                        isinstance(durable, Mapping)
-                        and durable.get("status") in {"running", "awaiting_input"}
-                        and durable.get("runtimeSessionId") == identity.runtime_id
-                    )
-                    break
-                await asyncio.sleep(delay)
-        if not bound:
-            logger.error("Failed to bind YaoYao group runtime")
-            await self._close_unbound_runtime(identity.runtime_id)
-            await self._settle_unbound_failed(
-                run_id,
-                expected_stored_id=expected_stored_id,
-                stored_session_id=identity.stored_id,
-                error="Agent runtime binding failed",
-            )
-            return
-
-        async with self._room_serial(room_id):
-            async with self._submission_serial(agent_id):
-                durable = None
-                for delay in (*_STORE_RETRY_DELAYS, None):
-                    try:
-                        durable = await asyncio.to_thread(self.store.get_run, run_id)
-                        break
-                    except Exception:  # noqa: BLE001 - unknown owner cannot submit
-                        if delay is None:
-                            break
-                        await asyncio.sleep(delay)
-                if (
-                    not isinstance(durable, Mapping)
-                    or durable.get("status") not in {"running", "awaiting_input"}
-                    or durable.get("runtimeSessionId") != identity.runtime_id
-                ):
-                    logger.error("Bound YaoYao group runtime lost durable ownership")
-                    await self._close_unbound_runtime(identity.runtime_id)
-                    if not (
-                        isinstance(durable, Mapping)
-                        and durable.get("status") in _TERMINAL_RUN_STATUSES
-                    ):
-                        await self._settle_unbound_failed(
-                            run_id,
-                            expected_stored_id=expected_stored_id,
-                            stored_session_id=identity.stored_id,
-                            error="Agent runtime ownership check failed",
-                        )
-                    return
-
-                state = self._install_runtime(
-                    run_id=run_id,
-                    room_id=room_id,
-                    topic_id=topic_id,
-                    agent_id=agent_id,
-                    identity=identity,
-                    expected_stored_id=expected_stored_id,
-                    expected_context_seq=expected_context_seq,
-                    through_seq=through_seq,
-                    profile=profile,
-                    reply_mode=reply_mode,
-                    required_reply=required_reply,
-                )
-                if self._closing:
-                    state.prompt_ready.set()
-                    await self._finalize_state(
-                        state,
-                        outcome="interrupted",
-                        error="Group orchestrator stopped",
-                        interrupt=True,
-                    )
-                    return
-
-                try:
-                    await self._run_state_blocking(
-                        state, gateway.submit_prompt, identity.runtime_id, prompt
-                    )
-                except Exception:  # noqa: BLE001 - ACK is intentionally unknown
-                    logger.error("YaoYao group prompt submission failed")
-                    state.prompt_ready.set()
-                    await self._finalize_state(
-                        state,
-                        outcome="failed",
-                        error="Prompt submission result is unknown",
-                        interrupt=True,
-                    )
-                    return
-
-                try:
-                    for delay in (*_STORE_RETRY_DELAYS, None):
-                        try:
-                            await self._run_state_blocking(
-                                state,
-                                self.store.commit_prompt_submission,
-                                run_id,
-                                expected_stored_session_id=expected_stored_id,
-                                stored_session_id=identity.stored_id,
-                                runtime_session_id=identity.runtime_id,
-                                expected_context_seq=expected_context_seq,
-                                through_seq=through_seq,
-                            )
-                            state.prompt_committed = True
-                            break
-                        except Exception:
-                            if delay is None:
-                                raise
-                            await asyncio.sleep(delay)
-                except Exception:  # noqa: BLE001 - prompts are never retried
-                    logger.error("Failed to commit YaoYao group prompt ACK")
-                    state.prompt_ready.set()
-                    await self._finalize_state(
-                        state,
-                        outcome="failed",
-                        error="Prompt acknowledgement could not be committed",
-                        interrupt=True,
-                    )
-                    return
-                finally:
-                    state.prompt_ready.set()
-
-        if state.overflowed:
-            await self._finalize_state(
-                state,
-                outcome="failed",
-                error="Runtime control event buffer exceeded capacity",
-                interrupt=True,
-            )
-            return
-
-        shutdown_event = self._shutdown_event
-        if shutdown_event is None:
-            raise GroupOrchestratorError("Run started without shutdown state")
-        finished_wait = asyncio.create_task(state.finished.wait())
-        shutdown_wait = asyncio.create_task(shutdown_event.wait())
-        try:
-            done, pending = await asyncio.wait(
-                {finished_wait, shutdown_wait},
-                return_when=asyncio.FIRST_COMPLETED,
-            )
-            for waiter in pending:
-                waiter.cancel()
-            if finished_wait in done and state.finished.is_set():
-                return
-            if shutdown_wait in done and shutdown_event.is_set():
-                outcome = "interrupted"
-                error = "Group orchestrator stopped"
-            await self._finalize_state(
-                state, outcome=outcome, error=error, interrupt=True
-            )
-        finally:
-            for waiter in (finished_wait, shutdown_wait):
-                if not waiter.done():
-                    waiter.cancel()
-
-    async def _fail_claim_without_projection(self, run_id: str) -> None:
-        for delay in (*_STORE_RETRY_DELAYS, None):
-            try:
-                await asyncio.to_thread(
-                    self.store.transition_run,
-                    run_id,
-                    "failed",
-                    error="Agent context projection failed",
-                )
-                return
-            except Exception:  # noqa: BLE001 - reconcile before retrying
-                if await self._run_is_durably_terminal(run_id):
-                    return
-                if delay is None:
-                    logger.exception("Failed to settle malformed YaoYao group claim")
-                    self._record_durable_failure(
-                        "Durable claimed run settlement failed"
-                    )
-                    return
-                await asyncio.sleep(delay)
-
-    async def _settle_unbound_failed(
-        self,
-        run_id: str,
-        *,
-        expected_stored_id: str | None,
-        stored_session_id: str | None,
-        error: str,
-    ) -> None:
-        for delay in (*_STORE_RETRY_DELAYS, None):
-            try:
-                await asyncio.to_thread(
-                    self.store.settle_run,
-                    run_id,
-                    runtime_session_id=None,
-                    expected_stored_session_id=expected_stored_id,
-                    stored_session_id=stored_session_id,
-                    outcome="failed",
-                    error=self._bounded_error(error),
-                )
-                return
-            except Exception:  # noqa: BLE001 - reconcile before retrying
-                if await self._run_is_durably_terminal(run_id):
-                    return
-                if delay is None:
-                    logger.exception("Failed to settle unbound YaoYao group run")
-                    self._record_durable_failure(
-                        "Durable unbound run settlement failed"
-                    )
-                    return
-                await asyncio.sleep(delay)
-
-    def _record_durable_failure(self, message: str) -> None:
-        failure = GroupOrchestratorError(message)
-        with self._failure_lock:
-            self._durable_failures.append(failure)
-
-    async def _run_is_durably_terminal(self, run_id: str) -> bool:
-        try:
-            durable = await asyncio.to_thread(self.store.get_run, run_id)
-        except Exception:  # noqa: BLE001 - missing is safe only for local cleanup
-            return False
-        return (
-            isinstance(durable, Mapping)
-            and durable.get("status") in _TERMINAL_RUN_STATUSES
-        )
-
-    async def _close_unbound_runtime(self, runtime_id: str) -> None:
-        try:
-            await asyncio.to_thread(self._required_gateway().close, runtime_id)
-        except Exception:  # noqa: BLE001 - best effort after failed durable bind
-            logger.exception("Failed to close unbound YaoYao group runtime")
-
-    @staticmethod
-    def _validated_identity(identity: object) -> SessionIdentity:
-        stored_id = _required_string(
-            getattr(identity, "stored_id", None), "session.stored_id"
-        )
-        runtime_id = _required_string(
-            getattr(identity, "runtime_id", None), "session.runtime_id"
-        )
-        running = getattr(identity, "running", None)
-        if not isinstance(running, bool):
-            raise GroupOrchestratorError("session.running must be a boolean")
-        return SessionIdentity(stored_id, runtime_id, running)
-
-    def _install_runtime(
-        self,
-        *,
-        run_id: str,
-        room_id: str,
-        topic_id: str,
-        agent_id: str,
-        identity: SessionIdentity,
-        expected_stored_id: str | None,
-        expected_context_seq: int,
-        through_seq: int,
-        profile: str,
-        reply_mode: str,
-        required_reply: bool,
-    ) -> _RuntimeState:
-        with self._mapping_lock:
-            if identity.runtime_id in self._runtime_states:
-                raise GroupOrchestratorError(
-                    "Gateway runtime is already mapped to an active generation"
-                )
-            self._next_generation += 1
-            state = _RuntimeState(
-                run_id=run_id,
-                room_id=room_id,
-                topic_id=topic_id,
-                agent_id=agent_id,
-                runtime_id=identity.runtime_id,
-                generation=self._next_generation,
-                expected_stored_id=expected_stored_id,
-                session_stored_id=identity.stored_id,
-                expected_context_seq=expected_context_seq,
-                through_seq=through_seq,
-                profile=profile,
-                reply_mode=reply_mode,
-                required_reply=required_reply,
-                automatic_published=required_reply,
-            )
-            self._runtime_states[identity.runtime_id] = (
-                state.generation,
-                state,
-            )
-            state.event_task = asyncio.create_task(
-                self._consume_runtime_events(state),
-                name=f"yaoyao-group-runtime-{state.generation}",
-            )
-            return state
-
-    def _remove_runtime(self, state: _RuntimeState) -> None:
-        with self._mapping_lock:
-            current = self._runtime_states.get(state.runtime_id)
-            if current == (state.generation, state):
-                self._runtime_states.pop(state.runtime_id, None)
-
-    def _gateway_event_callback(
-        self,
-        runtime_id: str,
-        event_type: str,
-        payload: dict[str, object],
-    ) -> None:
-        """Bridge the Gateway callback thread into one bounded asyncio queue."""
-
-        if event_type not in _PERSISTED_EVENTS:
-            return
-
-        with self._mapping_lock:
-            current = self._runtime_states.get(runtime_id)
-        if current is None:
-            logger.debug("Ignored event for an unmapped group runtime")
-            return
-        generation, _state = current
-        loop = self._loop
-        queue = self._event_queue
-        if loop is None or queue is None or loop.is_closed():
-            return
-        try:
-            safe_payload = _strict_json_copy(payload, "gateway.payload")
-        except GroupOrchestratorError:
-            logger.warning("Ignored malformed group Gateway payload")
-            return
-        if not isinstance(safe_payload, dict):
-            return
-        envelope = _GatewayEvent(
-            runtime_id=runtime_id,
-            generation=generation,
-            event_type=event_type,
-            payload=safe_payload,
-        )
-        if threading.get_ident() == self._loop_thread_id:
-            # The production transport uses a dedicated worker.  Supporting a
-            # loop-local test callback is still safe while the queue has room.
-            try:
-                queue.put_nowait(envelope)
-            except asyncio.QueueFull:
-                logger.error("Loop-local group Gateway callback exceeded capacity")
-            return
-        try:
-            future = asyncio.run_coroutine_threadsafe(queue.put(envelope), loop)
-            future.result()
-        except (RuntimeError, asyncio.CancelledError):
-            return
-
-    async def _consume_events(self) -> None:
-        queue = self._event_queue
-        if queue is None:
-            raise GroupOrchestratorError("Event consumer has no queue")
-        while True:
-            event = await queue.get()
-            try:
-                if event is None:
-                    return
-                await self._handle_event(event)
-            except Exception:  # noqa: BLE001 - isolate all Gateway callbacks
-                logger.exception("Failed to consume YaoYao group Gateway event")
-            finally:
-                queue.task_done()
-
-    async def _handle_event(self, event: _GatewayEvent) -> None:
-        if event.event_type not in _PERSISTED_EVENTS:
-            return
-        with self._mapping_lock:
-            current = self._runtime_states.get(event.runtime_id)
-        if current is None or current[0] != event.generation:
-            logger.debug("Ignored stale group Gateway generation")
-            return
-        state = current[1]
-        if state.finished.is_set() or state.finalizing:
-            return
-        try:
-            state.pending_events.put_nowait(event)
-        except asyncio.QueueFull:
-            # The transport already applies global backpressure. A per-runtime
-            # overflow is an invariant breach: fail that run without blocking
-            # unrelated sessions in the one global router.
-            state.overflowed = True
-            state.prompt_ready.set()
-
-    async def _consume_runtime_events(self, state: _RuntimeState) -> None:
-        """Serialize one runtime without head-of-line blocking other sessions."""
-
-        await state.prompt_ready.wait()
-        while not state.finished.is_set():
-            if state.finalizing:
-                return
-            if state.overflowed and state.prompt_committed:
-                await self._finalize_state(
-                    state,
-                    outcome="failed",
-                    error="Runtime control event buffer exceeded capacity",
-                    interrupt=True,
-                )
-                return
-            timeout: float | None = None
-            if state.stream_dirty and not (
-                state.reply_mode == "automatic" and not state.automatic_published
-            ):
-                timeout = max(
-                    0.0,
-                    STREAM_FLUSH_INTERVAL
-                    - (asyncio.get_running_loop().time() - state.last_stream_flush),
-                )
-            try:
-                if timeout is None:
-                    event = await state.pending_events.get()
-                else:
-                    event = await asyncio.wait_for(
-                        state.pending_events.get(), timeout=timeout
-                    )
-            except asyncio.TimeoutError:
-                async with state.mutation_lock:
-                    if state.finished.is_set() or state.finalizing:
-                        return
-                    with self._mapping_lock:
-                        current = self._runtime_states.get(state.runtime_id)
-                    if current != (state.generation, state):
-                        continue
-                    try:
-                        await self._flush_streaming(state)
-                    except Exception:  # noqa: BLE001 - fail this runtime durably
-                        logger.error("Failed to persist YaoYao group streaming message")
-                        await self._finalize_state_locked(
-                            state,
-                            outcome="failed",
-                            error="Streaming Agent message could not be persisted",
-                            interrupt=True,
-                        )
-                continue
-            try:
-                if event is None:
-                    return
-                if not state.prompt_committed:
-                    continue
-                with self._mapping_lock:
-                    current = self._runtime_states.get(event.runtime_id)
-                if current != (event.generation, state):
-                    continue
-                state.event_index += 1
-                async with state.mutation_lock:
-                    try:
-                        await self._apply_runtime_event(state, event)
-                    except Exception:  # noqa: BLE001 - fail this runtime only
-                        logger.error("Failed to process YaoYao group runtime event")
-                        await self._finalize_state_locked(
-                            state,
-                            outcome="failed",
-                            error="Gateway control event could not be persisted",
-                            interrupt=True,
-                        )
-            except Exception:  # noqa: BLE001 - isolate this runtime only
-                logger.error("Failed to lock YaoYao group runtime event")
-                await self._finalize_state(
-                    state,
-                    outcome="failed",
-                    error="Gateway control event could not be persisted",
-                    interrupt=True,
-                )
-            finally:
-                state.pending_events.task_done()
-
-    async def _apply_runtime_event(
-        self, state: _RuntimeState, event: _GatewayEvent
-    ) -> None:
-        event_type = event.event_type
-        payload = event.payload
-        if state.finalizing:
-            return
-        self._require_safe_control_payload(event_type, payload)
-        if state.complete_seen and event_type != "session.info":
-            return
-        if event_type == "message.start":
-            if state.reply_mode == "mentioned" or state.automatic_published:
-                await self._persist_message_snapshot(state, status="streaming")
-            return
-        if event_type in {"message.delta", "reasoning.delta"}:
-            text = payload.get("text")
-            if not isinstance(text, str):
-                raise GroupOrchestratorError("Gateway delta text is invalid")
-            if event_type == "message.delta":
-                state.content = self._append_bounded_text(
-                    state.content, text, "content"
-                )
-            else:
-                state.reasoning = self._append_bounded_text(
-                    state.reasoning, text, "reasoning"
-                )
-            state.stream_dirty = True
-            now = asyncio.get_running_loop().time()
-            if state.last_stream_flush == 0.0 or (
-                now - state.last_stream_flush >= STREAM_FLUSH_INTERVAL
-            ):
-                await self._flush_streaming(state)
-            return
-        if event_type.startswith("tool."):
-            await self._publish_automatic_state(state)
-            await self._flush_streaming(state)
-            self._merge_tool_event(state, event_type, payload)
-            await self._persist_message_snapshot(state, status="streaming")
-            return
-        if event_type == "approval.request":
-            await self._publish_automatic_state(state)
-            await self._flush_streaming(state)
-            await self._persist_approval(state, payload)
-            return
-        if event_type == "clarify.request":
-            await self._publish_automatic_state(state)
-            await self._flush_streaming(state)
-            await self._persist_clarification(state, payload)
-            return
-        if event_type == "clarify.expire":
-            await self._publish_automatic_state(state)
-            await self._flush_streaming(state)
-            await self._expire_clarification(state, payload)
-            return
-        if event_type == "message.complete":
-            if state.complete_seen:
-                return
-            await self._flush_streaming(state)
-            await self._expire_pending_interactions(state)
-            status = payload.get("status")
-            outcomes = {
-                "complete": "completed",
-                "error": "failed",
-                "interrupted": "interrupted",
-            }
-            outcome = outcomes.get(status) if isinstance(status, str) else None
-            if outcome is None:
-                outcome = "failed"
-                state.terminal_error = "Invalid message.complete status"
-            else:
-                raw_error = payload.get("error")
-                if outcome != "completed" and isinstance(raw_error, str):
-                    state.terminal_error = self._bounded_error(raw_error)
-            for tool in state.tool_state:
-                if tool.get("status") == "running":
-                    tool["status"] = "completed" if outcome == "completed" else "failed"
-            final_text = payload.get("text", payload.get("content"))
-            if isinstance(final_text, str):
-                state.content = self._bounded_text(final_text, "content")
-            final_reasoning = payload.get("reasoning")
-            if isinstance(final_reasoning, str):
-                state.reasoning = self._bounded_text(final_reasoning, "reasoning")
-            automatic_unpublished = (
-                state.reply_mode == "automatic" and not state.automatic_published
-            )
-            if state.reply_mode == "automatic":
-                state.content = _sanitize_no_reply_text(state.content)
-                state.reasoning = _sanitize_no_reply_text(state.reasoning)
-            if (
-                state.required_reply
-                and outcome == "completed"
-                and not state.content.strip()
-                and not state.had_visible_interaction
-            ):
-                state.content = _HOST_FALLBACK_REPLY
-            suppress_automatic = automatic_unpublished and (
-                outcome != "completed" or not state.content.strip()
-            )
-            if suppress_automatic:
-                state.content = ""
-                state.reasoning = ""
-                state.tool_state = []
-            elif automatic_unpublished:
-                state.automatic_published = True
-            # GroupStore only accepts completed as a direct running-run
-            # terminal upsert. Failure/interruption must first persist the
-            # partial body as streaming; settle_run atomically maps both run
-            # and response message to the final failed/interrupted status.
-            message_status = "completed" if outcome == "completed" else "streaming"
-            try:
-                await self._persist_message_snapshot(
-                    state,
-                    status=message_status,
-                    error=state.terminal_error,
-                    publish=not suppress_automatic,
-                )
-                state.stream_dirty = False
-            except Exception:
-                await self._finalize_state_locked(
-                    state,
-                    outcome="failed",
-                    error="Terminal Agent message could not be persisted",
-                    interrupt=True,
-                )
-                return
-            state.terminal_status = outcome
-            state.complete_seen = True
-            state.complete_index = state.event_index
-            state.grace_task = asyncio.create_task(
-                self._await_terminal_info(state),
-                name=f"yaoyao-group-grace-{state.generation}",
-            )
-            return
-        if event_type == "session.info":
-            await self._flush_streaming(state)
-            if (
-                payload.get("running") is not False
-                or not state.complete_seen
-                or state.event_index <= state.complete_index
-            ):
-                return
-            profile_name = payload.get("profile_name")
-            if profile_name != state.profile:
-                await self._finalize_state_locked(
-                    state,
-                    outcome="failed",
-                    error="Final session profile is missing",
-                    stored_session_id=state.session_stored_id,
-                    interrupt=True,
-                )
-                return
-            rotated = payload.get("stored_session_id")
-            if not isinstance(rotated, str) or not rotated:
-                await self._finalize_state_locked(
-                    state,
-                    outcome="failed",
-                    error="Final session identity is missing",
-                    stored_session_id=state.session_stored_id,
-                    interrupt=True,
-                )
-                return
-            actual_model = payload.get("model")
-            actual_provider = payload.get("provider")
-            if (
-                isinstance(actual_model, str)
-                and actual_model.strip()
-                and isinstance(actual_provider, str)
-                and actual_provider.strip()
-            ):
-                state.actual_model = actual_model.strip()
-                state.actual_provider = actual_provider.strip()
-            actual_reasoning = payload.get("reasoning_effort")
-            if isinstance(actual_reasoning, str) and actual_reasoning.strip():
-                state.actual_reasoning_effort = actual_reasoning.strip()
-            actual_fast = payload.get("fast")
-            if isinstance(actual_fast, bool):
-                state.actual_fast_mode = actual_fast
-            state.terminal_info_received.set()
-            await self._finalize_state_locked(
-                state,
-                outcome=state.terminal_status or "failed",
-                error=state.terminal_error,
-                stored_session_id=rotated,
-                interrupt=False,
-            )
-            return
-        if event_type == "error":
-            await self._flush_streaming(state)
-            await self._finalize_state_locked(
-                state,
-                outcome="failed",
-                error="Agent Gateway reported a failure",
-                interrupt=True,
-            )
-
-    @staticmethod
-    def _require_safe_control_payload(
-        event_type: str, payload: Mapping[str, object]
-    ) -> None:
-        truncated = payload.get("truncatedFields")
-        invalid = payload.get("invalidFields")
-        truncated_fields = (
-            {item for item in truncated if isinstance(item, str)}
-            if isinstance(truncated, list)
-            else set()
-        )
-        invalid_fields = (
-            {item for item in invalid if isinstance(item, str)}
-            if isinstance(invalid, list)
-            else set()
-        )
-        if payload.get("transportInvalidPayload") is True and not invalid_fields:
-            raise GroupOrchestratorError("Gateway control payload is invalid")
-        critical: set[str]
-        if event_type == "message.complete":
-            critical = {"status", "text", "reasoning"}
-        elif event_type == "session.info":
-            critical = {"running", "stored_session_id", "profile_name"}
-        elif event_type in {"approval.request", "clarify.request"}:
-            if payload.get("transportTruncated") is True:
-                raise GroupOrchestratorError(
-                    "Gateway interaction request was truncated"
-                )
-            critical = {
-                "request_id",
-                "question",
-                "command",
-                "choices",
-                "tool",
-                "name",
-            }
-        elif event_type == "clarify.expire":
-            critical = {"request_id"}
-        elif event_type.startswith("tool."):
-            critical = {"tool_id", "id"}
-            if event_type == "tool.output_risk":
-                critical |= {"risk", "redacted"}
-        elif event_type == "error":
-            critical = {"message", "error", "reason"}
-        else:
-            critical = set()
-        if critical & (truncated_fields | invalid_fields):
-            raise GroupOrchestratorError(
-                "Gateway control payload lost a critical field"
-            )
-        if payload.get("transportInvalidPayload") is True:
-            # Known-invalid non-critical diagnostics never justify trusting an
-            # approval/tool/terminal control frame as authoritative.
-            if event_type != "session.info":
-                raise GroupOrchestratorError("Gateway control payload is invalid")
-        if (
-            payload.get("transportTruncated") is True
-            and not truncated_fields
-            and event_type
-            in {
-                "message.complete",
-                "session.info",
-                "approval.request",
-                "clarify.request",
-                "clarify.expire",
-            }
-        ):
-            raise GroupOrchestratorError("Gateway control payload was replaced")
-
-    async def _flush_streaming(self, state: _RuntimeState) -> None:
-        if not state.stream_dirty:
-            return
-        if state.reply_mode == "automatic" and not state.automatic_published:
-            return
-        await self._persist_message_snapshot(state, status="streaming")
-        state.stream_dirty = False
-        state.last_stream_flush = asyncio.get_running_loop().time()
-
-    async def _persist_message_snapshot(
-        self,
-        state: _RuntimeState,
-        *,
-        status: str,
-        error: str = "",
-        publish: bool | None = None,
-    ) -> None:
-        should_publish = (
-            state.reply_mode == "mentioned" or state.automatic_published
-            if publish is None
-            else publish
-        )
-        content = (
-            _sanitize_no_reply_text(state.content)
-            if state.reply_mode == "automatic"
-            else state.content
-        )
-        reasoning = (
-            _sanitize_no_reply_text(state.reasoning)
-            if state.reply_mode == "automatic"
-            else state.reasoning
-        )
-        persisted = False
-        for delay in (*_STORE_RETRY_DELAYS, None):
-            try:
-                await self._run_state_blocking(
-                    state,
-                    self.store.upsert_agent_message,
-                    state.run_id,
-                    content=content,
-                    reasoning=reasoning,
-                    tool_state=state.tool_state,
-                    status=status,
-                    error=error,
-                    publish=should_publish,
-                )
-                persisted = True
-                break
-            except Exception:  # noqa: BLE001 - reconcile a lost Store reply
-                try:
-                    persisted = bool(
-                        await self._run_state_blocking(
-                            state,
-                            self._terminal_message_is_durable,
-                            state,
-                            content=content,
-                            reasoning=reasoning,
-                            tool_state=state.tool_state,
-                            status=status,
-                            error=error,
-                        )
-                    )
-                except Exception:  # noqa: BLE001 - retry the exact snapshot
-                    persisted = False
-                if persisted:
-                    break
-                if delay is None:
-                    break
-                await asyncio.sleep(delay)
-        if not persisted:
-            raise GroupOrchestratorError("Agent message snapshot is not durable")
-
-    async def _publish_automatic_state(self, state: _RuntimeState) -> None:
-        if state.reply_mode != "automatic" or state.automatic_published:
-            return
-        state.automatic_published = True
-        await self._persist_message_snapshot(state, status="streaming", publish=True)
-        state.stream_dirty = False
-        state.last_stream_flush = asyncio.get_running_loop().time()
-
-    @staticmethod
-    def _bounded_text(value: str, field_name: str) -> str:
-        try:
-            size = len(value.encode("utf-8"))
-        except UnicodeEncodeError as error:
-            raise GroupOrchestratorError(
-                f"Gateway {field_name} is not valid UTF-8"
-            ) from error
-        if size > MAX_MESSAGE_BYTES:
-            raise GroupOrchestratorError(
-                f"Gateway {field_name} exceeds the group message limit"
-            )
-        return value
-
-    @classmethod
-    def _append_bounded_text(cls, existing: str, delta: str, field_name: str) -> str:
-        return cls._bounded_text(existing + delta, field_name)
-
-    def _merge_tool_event(
-        self,
-        state: _RuntimeState,
-        event_type: str,
-        payload: Mapping[str, object],
-    ) -> None:
-        if payload.get("transportInvalidPayload") is True:
-            raise GroupOrchestratorError("Gateway tool payload is invalid")
-        tool_id = payload.get("tool_id", payload.get("id"))
-        tool_id = _required_string(tool_id, "tool.tool_id")
-        if tool_id == _TOOL_TRUNCATION_ID:
-            raise GroupOrchestratorError("Gateway tool id is reserved")
-        if len(tool_id.encode("utf-8")) > _TOOL_TEXT_LIMIT:
-            raise GroupOrchestratorError("Gateway tool id exceeds the limit")
-        name_value = payload.get("name")
-        name = (
-            self._bounded_tool_text(name_value)
-            if isinstance(name_value, str) and name_value
-            else None
-        )
-        existing = self._tool_state_for_id(state, tool_id)
-        tool: dict[str, object] = (
-            dict(existing)
-            if existing is not None
-            else {"id": tool_id, "name": name or "unknown", "status": "running"}
-        )
-        if name is not None:
-            tool["name"] = name
-        if "args" in payload:
-            tool["arguments"] = self._bounded_tool_value(payload["args"], "tool.args")
-        elif "args_text" in payload:
-            args_text = payload["args_text"]
-            if not isinstance(args_text, str):
-                raise GroupOrchestratorError("Gateway tool args_text is invalid")
-            tool["arguments"] = self._bounded_tool_text(args_text)
-        if event_type == "tool.output_risk":
-            output_risk, risk_preview = self._project_output_risk(payload)
-            tool["outputRisk"] = output_risk
-            tool["preview"] = risk_preview
-        preview = next(
-            (
-                value
-                for key in ("summary", "context", "result_text", "args_text")
-                if isinstance((value := payload.get(key)), str) and value
-            ),
-            None,
-        )
-        if preview is not None and event_type != "tool.output_risk":
-            tool["preview"] = self._bounded_tool_text(preview)
-        if "result" in payload:
-            tool["result"] = self._bounded_tool_value(payload["result"], "tool.result")
-        error = payload.get("error")
-        if isinstance(error, str) and error:
-            tool["error"] = self._bounded_tool_text(error)
-        duration = payload.get("duration_s")
-        if (
-            isinstance(duration, (int, float))
-            and not isinstance(duration, bool)
-            and math.isfinite(duration)
-            and duration >= 0
-        ):
-            tool["durationSeconds"] = float(duration)
-        if event_type == "tool.complete":
-            raw_status = payload.get("status")
-            tool["status"] = (
-                "failed"
-                if tool.get("error")
-                or raw_status in {"error", "failed", "cancelled", "canceled"}
-                else "completed"
-            )
-        elif existing is None:
-            tool["status"] = "running"
-        self._upsert_tool_state(state, tool)
-
-    @staticmethod
-    def _bounded_tool_text(value: str, limit: int = _TOOL_TEXT_LIMIT) -> str:
-        try:
-            encoded = value.encode("utf-8")
-        except UnicodeEncodeError as error:
-            raise GroupOrchestratorError(
-                "Gateway tool text is not valid UTF-8"
-            ) from error
-        if len(encoded) <= limit:
-            return value
-        suffix = "..."
-        prefix = encoded[: limit - len(suffix)]
-        while prefix:
-            try:
-                return prefix.decode("utf-8") + suffix
-            except UnicodeDecodeError:
-                prefix = prefix[:-1]
-        return suffix
-
-    @classmethod
-    def _bounded_tool_value(cls, value: object, field_name: str) -> object:
-        copied = _strict_json_copy(value, field_name)
-        encoded = json.dumps(
-            copied,
-            ensure_ascii=False,
-            sort_keys=True,
-            separators=(",", ":"),
-            allow_nan=False,
-        ).encode("utf-8")
-        if len(encoded) <= _TOOL_VALUE_LIMIT:
-            return copied
-        return {"originalBytes": len(encoded), "truncated": True}
-
-    @classmethod
-    def _project_output_risk(
-        cls, payload: Mapping[str, object]
-    ) -> tuple[dict[str, object], str]:
-        risk_value = payload.get("risk")
-        findings_value = payload.get("findings")
-        redacted = payload.get("redacted")
-        if not isinstance(risk_value, str) or not risk_value:
-            raise GroupOrchestratorError("Gateway tool output risk is invalid")
-        if not isinstance(findings_value, list) or not all(
-            isinstance(item, str) for item in findings_value
-        ):
-            raise GroupOrchestratorError("Gateway tool output findings are invalid")
-        if not isinstance(redacted, bool):
-            raise GroupOrchestratorError("Gateway tool output redaction is invalid")
-        risk = cls._bounded_tool_text(risk_value, 256)
-        findings = [
-            cls._bounded_tool_text(item, 512)
-            for item in findings_value[:_TOOL_FINDING_LIMIT]
-        ]
-        truncated = (
-            len(findings_value) > len(findings)
-            or risk != risk_value
-            or any(
-                projected != original
-                for projected, original in zip(findings, findings_value)
-            )
-        )
-        transport_truncated = payload.get("truncatedFields")
-        if isinstance(transport_truncated, list) and "findings" in transport_truncated:
-            truncated = True
-        output_risk: dict[str, object] = {
-            "risk": risk,
-            "findings": findings,
-            "redacted": redacted,
-        }
-        if truncated:
-            output_risk["truncated"] = True
-        preview = f"Output risk: {risk}"
-        if findings:
-            preview += "; findings: " + ", ".join(findings)
-        preview += f"; redacted: {'true' if redacted else 'false'}"
-        return output_risk, cls._bounded_tool_text(preview)
-
-    @staticmethod
-    def _tool_state_for_id(
-        state: _RuntimeState, tool_id: str
-    ) -> dict[str, object] | None:
-        index = state.tool_indexes.get(tool_id)
-        return None if index is None else state.tool_state[index]
-
-    @classmethod
-    def _upsert_tool_state(cls, state: _RuntimeState, tool: dict[str, object]) -> None:
-        tool_id = str(tool["id"])
-        index = state.tool_indexes.get(tool_id)
-        candidate = [dict(item) for item in state.tool_state]
-        if index is None:
-            candidate.append(dict(tool))
-        else:
-            candidate[index] = dict(tool)
-        candidate = cls._fit_tool_state(candidate, newest_tool_id=tool_id)
-        state.tool_state = candidate
-        state.tool_indexes = {
-            str(item["id"]): offset for offset, item in enumerate(candidate)
-        }
-
-    @classmethod
-    def _fit_tool_state(
-        cls,
-        candidate: list[dict[str, object]],
-        *,
-        newest_tool_id: str,
-    ) -> list[dict[str, object]]:
-        def encoded_size(items: list[dict[str, object]]) -> int:
-            try:
-                return len(
-                    json.dumps(
-                        items,
-                        ensure_ascii=False,
-                        sort_keys=True,
-                        separators=(",", ":"),
-                        allow_nan=False,
-                    ).encode("utf-8")
-                )
-            except (TypeError, ValueError, UnicodeEncodeError) as error:
-                raise GroupOrchestratorError("Gateway tool state is invalid") from error
-
-        if (
-            len(candidate) <= _TOOL_COUNT_LIMIT
-            and encoded_size(candidate) <= _TOOL_STATE_INTERNAL_LIMIT
-        ):
-            return candidate
-
-        newest = next(
-            (item for item in candidate if item.get("id") == newest_tool_id), None
-        )
-        if newest is None:
-            raise GroupOrchestratorError("Gateway tool state merge lost its tool")
-        retained = [
-            item
-            for item in candidate
-            if item.get("id") not in {newest_tool_id, _TOOL_TRUNCATION_ID}
-        ]
-        marker = {
-            "id": _TOOL_TRUNCATION_ID,
-            "name": "hermes",
-            "status": "completed",
-            "preview": "Earlier tool state omitted by the group size limit",
-        }
-        fitted = [*retained, marker, newest]
-        while (
-            len(fitted) > _TOOL_COUNT_LIMIT
-            or encoded_size(fitted) > _TOOL_STATE_INTERNAL_LIMIT
-        ):
-            if not retained:
-                break
-            retained.pop(0)
-            fitted = [*retained, marker, newest]
-        if (
-            len(fitted) > _TOOL_COUNT_LIMIT
-            or encoded_size(fitted) > _TOOL_STATE_INTERNAL_LIMIT
-        ):
-            compact_newest: dict[str, object] = {
-                "id": newest_tool_id,
-                "name": cls._bounded_tool_text(
-                    str(newest.get("name") or "unknown"), 256
-                ),
-                "status": str(newest.get("status") or "running"),
-                "preview": cls._bounded_tool_text(
-                    str(newest.get("preview") or "Tool state truncated"), 4096
-                ),
-            }
-            output_risk = newest.get("outputRisk")
-            if isinstance(output_risk, Mapping):
-                compact_newest["outputRisk"] = {
-                    "risk": cls._bounded_tool_text(
-                        str(output_risk.get("risk") or "unknown"), 256
-                    ),
-                    "findings": [
-                        cls._bounded_tool_text(item, 512)
-                        for item in output_risk.get("findings", [])[
-                            :_TOOL_FINDING_LIMIT
-                        ]
-                        if isinstance(item, str)
-                    ],
-                    "redacted": output_risk.get("redacted") is True,
-                    "truncated": True,
-                }
-            fitted = [marker, compact_newest]
-        if encoded_size(fitted) > MAX_TOOL_STATE_BYTES:
-            raise GroupOrchestratorError("Gateway tool state exceeds the limit")
-        return fitted
-
-    async def _store_retry(
-        self,
-        state: _RuntimeState,
-        function: Callable[..., object],
-        *args: object,
-        **kwargs: object,
-    ) -> object:
-        last_error: Exception | None = None
-        for delay in (*_STORE_RETRY_DELAYS, None):
-            try:
-                return await self._run_state_blocking(state, function, *args, **kwargs)
-            except Exception as error:  # noqa: BLE001 - exact Store APIs replay
-                last_error = error
-                if delay is None:
-                    break
-                await asyncio.sleep(delay)
-        if last_error is None:
-            raise GroupOrchestratorError("Store operation failed")
-        raise last_error
-
-    async def _persist_approval(
-        self, state: _RuntimeState, payload: Mapping[str, object]
-    ) -> None:
-        if payload.get("transportInvalidPayload") is True:
-            raise GroupOrchestratorError("Gateway approval payload is invalid")
-        raw_choices = payload.get("choices")
-        if raw_choices is None:
-            choices = ["deny"]
-        elif (
-            not isinstance(raw_choices, list)
-            or not raw_choices
-            or not all(
-                isinstance(choice, str) and choice in _APPROVAL_CHOICES
-                for choice in raw_choices
-            )
-        ):
-            raise GroupOrchestratorError("Gateway approval choices are invalid")
-        else:
-            choices = list(dict.fromkeys(raw_choices))
-        safe_payload = dict(payload)
-        safe_payload["choices"] = choices
-        state.approval_ordinal += 1
-        interaction_id = "approval-" + str(
-            uuid.uuid5(
-                uuid.NAMESPACE_URL,
-                f"{state.run_id}:{state.generation}:approval:{state.approval_ordinal}",
-            )
-        )
-        interaction = await self._store_retry(
-            state,
-            self.store.create_gateway_interaction,
-            state.run_id,
-            kind="approval",
-            gateway_interaction_id=interaction_id,
-            payload=safe_payload,
-        )
-        if not isinstance(interaction, Mapping):
-            raise GroupOrchestratorError("Stored approval is invalid")
-        local_id = _required_string(interaction.get("id"), "interaction.id")
-        state.had_visible_interaction = True
-        state.pending_interaction_ids.add(local_id)
-
-    async def _persist_clarification(
-        self, state: _RuntimeState, payload: Mapping[str, object]
-    ) -> None:
-        if payload.get("transportInvalidPayload") is True:
-            raise GroupOrchestratorError("Gateway clarification payload is invalid")
-        request_id = _required_string(
-            payload.get("request_id"), "clarification.request_id"
-        )
-        interaction = await self._store_retry(
-            state,
-            self.store.create_gateway_interaction,
-            state.run_id,
-            kind="clarification",
-            gateway_interaction_id=request_id,
-            payload=dict(payload),
-        )
-        if not isinstance(interaction, Mapping):
-            raise GroupOrchestratorError("Stored clarification is invalid")
-        local_id = _required_string(interaction.get("id"), "interaction.id")
-        state.had_visible_interaction = True
-        state.clarification_ids[request_id] = local_id
-        state.pending_interaction_ids.add(local_id)
-
-    async def _expire_clarification(
-        self, state: _RuntimeState, payload: Mapping[str, object]
-    ) -> None:
-        request_id = _required_string(
-            payload.get("request_id"), "clarification.request_id"
-        )
-        local_id = state.clarification_ids.get(request_id)
-        if local_id is None:
-            return
-        await self._store_retry(state, self.store.expire_interaction, local_id)
-        state.pending_interaction_ids.discard(local_id)
-
-    async def _expire_pending_interactions(self, state: _RuntimeState) -> None:
-        for interaction_id in tuple(sorted(state.pending_interaction_ids)):
-            await self._store_retry(
-                state, self.store.expire_interaction, interaction_id
-            )
-            state.pending_interaction_ids.discard(interaction_id)
-
-    def _terminal_message_is_durable(
-        self,
-        state: _RuntimeState,
-        *,
-        content: str,
-        reasoning: str,
-        tool_state: list[dict[str, object]],
-        status: str,
-        error: str,
-    ) -> bool:
-        """Reconcile a lost Store reply without accepting another run's write."""
-
-        run = self.store.get_run(state.run_id)
-        if not isinstance(run, Mapping):
-            return False
-        response_message_id = run.get("responseMessageId")
-        if not isinstance(response_message_id, str) or not response_message_id:
-            return False
-        if (
-            run.get("id") != state.run_id
-            or run.get("roomId") != state.room_id
-            or run.get("agentId") != state.agent_id
-            or run.get("runtimeSessionId") != state.runtime_id
-            or run.get("status") not in {"running", "awaiting_input"}
-        ):
-            return False
-        message = self.store.get_message(response_message_id)
-        if not isinstance(message, Mapping):
-            return False
-        return (
-            message.get("id") == response_message_id
-            and message.get("roomId") == state.room_id
-            and message.get("senderKind") == "agent"
-            and message.get("senderId") == state.agent_id
-            and message.get("content") == content
-            and message.get("reasoning") == reasoning
-            and message.get("toolState") == tool_state
-            and message.get("status") == status
-            and message.get("error") == error
-        )
-
-    async def _run_state_blocking(
-        self,
-        state: _RuntimeState,
-        function: Callable[..., object],
-        *args: object,
-        **kwargs: object,
-    ) -> object:
-        """Track a blocking call so shutdown never abandons its worker thread."""
-
-        return await self._run_states_blocking([state], function, *args, **kwargs)
-
-    @staticmethod
-    async def _run_states_blocking(
-        states: list[_RuntimeState],
-        function: Callable[..., object],
-        *args: object,
-        **kwargs: object,
-    ) -> object:
-        """Shield one worker call and expose it to every affected runtime."""
-
-        task: asyncio.Task[object] = asyncio.create_task(
-            asyncio.to_thread(function, *args, **kwargs)
-        )
-        unique_states = tuple({id(state): state for state in states}.values())
-        for state in unique_states:
-            state.inflight_calls.add(task)
-
-        def finished(done: asyncio.Task[object]) -> None:
-            for state in unique_states:
-                state.inflight_calls.discard(done)
-
-        task.add_done_callback(finished)
-        return await asyncio.shield(task)
-
-    async def _await_terminal_info(self, state: _RuntimeState) -> None:
-        """Apply the grace timeout only after a terminal message.complete."""
-
-        terminal_wait = asyncio.create_task(state.terminal_info_received.wait())
-        finished_wait = asyncio.create_task(state.finished.wait())
-        try:
-            done, pending = await asyncio.wait(
-                {terminal_wait, finished_wait},
-                timeout=self._completion_timeout,
-                return_when=asyncio.FIRST_COMPLETED,
-            )
-            for waiter in pending:
-                waiter.cancel()
-            if terminal_wait in done or finished_wait in done:
-                return
-            await self._finalize_state(
-                state,
-                outcome=(
-                    state.terminal_status
-                    if state.terminal_status in {"failed", "interrupted"}
-                    else "interrupted"
-                ),
-                error=state.terminal_error or "Final session state timed out",
-                interrupt=True,
-            )
-        finally:
-            for waiter in (terminal_wait, finished_wait):
-                if not waiter.done():
-                    waiter.cancel()
-
-    async def _finalize_state(
-        self,
-        state: _RuntimeState,
-        *,
-        outcome: str,
-        error: str,
-        interrupt: bool,
-        stored_session_id: str | None = None,
-    ) -> None:
-        async with state.mutation_lock:
-            await self._finalize_state_locked(
-                state,
-                outcome=outcome,
-                error=error,
-                interrupt=interrupt,
-                stored_session_id=stored_session_id,
-            )
-
-    async def _finalize_state_locked(
-        self,
-        state: _RuntimeState,
-        *,
-        outcome: str,
-        error: str,
-        interrupt: bool,
-        stored_session_id: str | None = None,
-    ) -> None:
-        async with state.finalize_lock:
-            if state.finished.is_set():
-                return
-            state.finalizing = True
-            current_task = asyncio.current_task()
-            pending_calls = tuple(state.inflight_calls)
-            if pending_calls:
-                await asyncio.gather(*pending_calls, return_exceptions=True)
-            gateway = self._required_gateway()
-            if interrupt:
-                try:
-                    await self._run_state_blocking(
-                        state, gateway.interrupt, state.runtime_id
-                    )
-                except Exception:  # noqa: BLE001 - settle remains mandatory
-                    logger.exception("Failed to interrupt YaoYao group runtime")
-            expected_stored = (
-                state.session_stored_id
-                if state.prompt_committed
-                else state.expected_stored_id
-            )
-            rotated_stored = stored_session_id or state.session_stored_id
-            settled = False
-            for delay in (*_STORE_RETRY_DELAYS, None):
-                try:
-                    await self._run_state_blocking(
-                        state,
-                        self.store.settle_run,
-                        state.run_id,
-                        runtime_session_id=state.runtime_id,
-                        expected_stored_session_id=expected_stored,
-                        stored_session_id=rotated_stored,
-                        outcome=outcome,
-                        actual_model=state.actual_model,
-                        actual_provider=state.actual_provider,
-                        actual_reasoning_effort=state.actual_reasoning_effort,
-                        actual_fast_mode=state.actual_fast_mode,
-                        error=self._bounded_error(error),
-                    )
-                    settled = True
-                    break
-                except Exception:  # noqa: BLE001 - reconcile before retrying
-                    if await self._run_is_durably_terminal(state.run_id):
-                        settled = True
-                        break
-                    if delay is None:
-                        logger.exception("Failed to settle YaoYao group runtime")
-                        break
-                    await asyncio.sleep(delay)
-            if not settled:
-                state.settle_error = GroupOrchestratorError(
-                    "Durable runtime settlement failed"
-                )
-                return
-
-            state.settle_error = None
-            self._remove_runtime(state)
-            try:
-                await self._run_state_blocking(state, gateway.close, state.runtime_id)
-            except Exception:  # noqa: BLE001 - durable state is already terminal
-                logger.exception("Failed to close settled YaoYao group runtime")
-            if outcome == "completed":
-                try:
-                    cascade = await self._run_state_blocking(
-                        state, self.store.complete_cascade, state.run_id
-                    )
-                except Exception:  # noqa: BLE001 - source is already durably complete
-                    logger.error("Pending YaoYao group cascade remains durable")
-                    self.wake()
-                else:
-                    if (
-                        isinstance(cascade, Mapping)
-                        and isinstance(cascade.get("runCount"), int)
-                        and not isinstance(cascade.get("runCount"), bool)
-                        and cascade["runCount"] > 0
-                    ):
-                        self.wake()
-            state.finished.set()
-            state.terminal_info_received.set()
-            if state.event_task is not None and state.event_task is not current_task:
-                if not state.event_task.done():
-                    state.event_task.cancel()
-                await asyncio.gather(state.event_task, return_exceptions=True)
-            if state.grace_task is not None and state.grace_task is not current_task:
-                if not state.grace_task.done():
-                    state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-
-    def _required_gateway(self) -> _Gateway:
-        if self._gateway is None:
-            raise GroupOrchestratorError("Gateway adapter is not started")
-        return self._gateway
-
-    @staticmethod
-    def _bounded_error(value: str) -> str:
-        encoded = value.encode("utf-8", errors="replace")
-        if len(encoded) <= _ERROR_TEXT_LIMIT:
-            return value
-        shortened = encoded[: _ERROR_TEXT_LIMIT - 3]
-        while shortened:
-            try:
-                return shortened.decode("utf-8") + "..."
-            except UnicodeDecodeError:
-                shortened = shortened[:-1]
-        return "..."
-
-
-__all__ = [
-    "DEFAULT_COMPLETION_TIMEOUT",
-    "DEFAULT_EVENT_QUEUE_SIZE",
-    "GroupOrchestrator",
-    "GroupOrchestratorError",
-    "build_run_prompt",
-]

+ 0 - 1769
hermes-plugins/yaoyao/dashboard/group_plugin_api.py

@@ -1,1769 +0,0 @@
-"""Authenticated REST adapter for the authoritative Yaoyao Group store."""
-
-from __future__ import annotations
-
-import asyncio
-import base64
-import hashlib
-import importlib
-import inspect
-import json
-import logging
-import os
-import re
-import sqlite3
-import sys
-import threading
-from collections.abc import Callable
-from contextlib import asynccontextmanager
-from importlib.machinery import ModuleSpec
-from pathlib import Path
-from types import ModuleType
-from typing import Annotated, Any
-from urllib.error import HTTPError, URLError
-from urllib.parse import urlencode
-from urllib.request import Request as URLRequest, build_opener, ProxyHandler
-from uuid import UUID, uuid4
-
-from fastapi import APIRouter, File, Query, Request, UploadFile, WebSocket
-from fastapi import Path as APIPath
-from fastapi.exceptions import RequestValidationError
-from fastapi.responses import JSONResponse, StreamingResponse
-from fastapi.routing import APIRoute
-
-logger = logging.getLogger(__name__)
-_PLUGIN_NAME = "yaoyao"
-_agent_name_resolver: Callable[[str], str] = lambda _profile: ""
-
-_MAX_GROUP_UPLOAD_FILES = 8
-_MAX_GROUP_UPLOAD_FILE_BYTES = 25 * 1_024 * 1_024
-_MAX_GROUP_UPLOAD_REQUEST_BYTES = 50 * 1_024 * 1_024
-_GROUP_UPLOAD_CHUNK_BYTES = 1_024 * 1_024
-
-_DASHBOARD_DIR = Path(__file__).resolve().parent
-_LOCAL_PACKAGE = (
-    "_hermes_yaoyao_group_"
-    + hashlib.sha256(str(_DASHBOARD_DIR).encode("utf-8")).hexdigest()[:24]
-)
-
-
-def _log_runtime_failure(message: str, error: BaseException) -> None:
-    """Log lifecycle context and type without attacker-controlled exception text."""
-
-    logger.error("%s [errorType=%s]", message, type(error).__name__)
-
-
-def _plugin_runtime_enabled() -> bool:
-    """Mirror the core HTTP plugin gate for the group WebSocket channel."""
-
-    try:
-        from hermes_cli import web_server
-        from hermes_cli.plugins_cmd import _get_disabled_set, _get_enabled_set
-
-        enabled_set = _get_enabled_set()
-        disabled_set = _get_disabled_set()
-        plugin = next(
-            (
-                candidate
-                for candidate in web_server._get_dashboard_plugins()
-                if candidate.get("name") == _PLUGIN_NAME
-            ),
-            None,
-        )
-    except Exception:
-        return False
-
-    if plugin is None:
-        return False
-    source = plugin.get("source")
-    if source == "bundled":
-        return _PLUGIN_NAME not in disabled_set
-    if source == "user":
-        return _PLUGIN_NAME in enabled_set and _PLUGIN_NAME not in disabled_set
-    return False
-
-
-def _ensure_local_package() -> ModuleType:
-    """Return the stable private package assigned to this resolved directory."""
-    package = ModuleType(_LOCAL_PACKAGE)
-    package.__package__ = _LOCAL_PACKAGE
-    package.__path__ = [str(_DASHBOARD_DIR)]
-    package_spec = ModuleSpec(_LOCAL_PACKAGE, loader=None, is_package=True)
-    package_spec.submodule_search_locations = [str(_DASHBOARD_DIR)]
-    package.__spec__ = package_spec
-    shared = sys.modules.setdefault(_LOCAL_PACKAGE, package)
-    paths = getattr(shared, "__path__", None)
-    if (
-        not isinstance(shared, ModuleType)
-        or not paths
-        or Path(paths[0]).resolve() != _DASHBOARD_DIR
-    ):
-        raise ImportError("Yaoyao Group private package identity is invalid")
-    return shared
-
-
-_package = _ensure_local_package()
-_protocol = importlib.import_module(f"{_LOCAL_PACKAGE}.group_protocol")
-_store_module = importlib.import_module(f"{_LOCAL_PACKAGE}.group_store")
-_stream_module = importlib.import_module(f"{_LOCAL_PACKAGE}.group_stream")
-_node_worker_module = importlib.import_module(
-    f"{_LOCAL_PACKAGE}.group_node_worker"
-)
-_node_registry_module = importlib.import_module(
-    f"{_LOCAL_PACKAGE}.group_node_registry"
-)
-
-
-PROTOCOL_VERSION = _protocol.PROTOCOL_VERSION
-EVENT_TYPES = _protocol.EVENT_TYPES
-MAX_MESSAGE_PAGE_SIZE = _protocol.MAX_MESSAGE_PAGE_SIZE
-limits_payload = _protocol.limits_payload
-normalize_interaction_id = _protocol.normalize_interaction_id
-
-AddAgentRequest = _protocol.AddAgentRequest
-ApprovalRequest = _protocol.ApprovalRequest
-ClarificationRequest = _protocol.ClarificationRequest
-CreateRoomRequest = _protocol.CreateRoomRequest
-RequestIDRequest = _protocol.RequestIDRequest
-SendMessageRequest = _protocol.SendMessageRequest
-UpdateAgentRequest = _protocol.UpdateAgentRequest
-UpdateRoomRequest = _protocol.UpdateRoomRequest
-UpdateTopicRequest = _protocol.UpdateTopicRequest
-MarkTopicReadRequest = _protocol.MarkTopicReadRequest
-NodeWorkerOpenRequest = _node_worker_module.NodeWorkerOpenRequest
-NodeWorkerPromptRequest = _node_worker_module.NodeWorkerPromptRequest
-NodeWorkerApprovalRequest = _node_worker_module.NodeWorkerApprovalRequest
-NodeWorkerClarificationRequest = _node_worker_module.NodeWorkerClarificationRequest
-NodeGatewayWorker = _node_worker_module.NodeGatewayWorker
-PairedNodeRegistry = _node_registry_module.PairedNodeRegistry
-
-GroupStore = _store_module.GroupStore
-GroupStoreError = _store_module.GroupStoreError
-GroupNotFoundError = _store_module.GroupNotFoundError
-GroupConflictError = _store_module.GroupConflictError
-IdempotencyConflict = _store_module.IdempotencyConflict
-
-
-class GroupAPIError(RuntimeError):
-    """A stable public REST failure independent of internal exception text."""
-
-    def __init__(
-        self,
-        code: str,
-        message: str,
-        status_code: int,
-        details: dict[str, object] | None = None,
-    ) -> None:
-        super().__init__(message)
-        self.code = code
-        self.message = message
-        self.status_code = status_code
-        self.details = details or {}
-
-
-class RuntimeUnavailableError(GroupAPIError):
-    def __init__(self) -> None:
-        super().__init__(
-            "runtime_unavailable",
-            "Group runtime is unavailable",
-            503,
-        )
-
-
-class GroupInvalidRequest(GroupAPIError):
-    """A trusted Store or protocol input validator rejected the request."""
-
-    def __init__(self, message: str) -> None:
-        super().__init__("invalid_request", message, 400)
-
-
-class GroupStorageAPIError(GroupAPIError):
-    """A raw SQLite failure hidden behind the public storage boundary."""
-
-    def __init__(self) -> None:
-        super().__init__("storage_error", "Group storage failed", 500)
-
-
-class GroupInternalAPIError(GroupAPIError):
-    """An unexpected implementation failure safe for public serialization."""
-
-    def __init__(self) -> None:
-        super().__init__("internal_error", "Internal server error", 500)
-
-
-def _group_upload_root() -> Path:
-    store_path = getattr(_store_instance(), "path", None)
-    if not isinstance(store_path, Path):
-        raise GroupStorageAPIError()
-    return store_path.parent / "group-uploads"
-
-
-def _safe_upload_name(value: str | None) -> str:
-    candidate = (value or "attachment").replace("\\", "/").rsplit("/", 1)[-1]
-    cleaned = "".join(
-        character
-        for character in candidate
-        if ord(character) >= 32 and ord(character) != 127
-    ).strip()[:240]
-    return cleaned or "attachment"
-
-
-def _safe_upload_extension(name: str) -> str:
-    suffix = Path(name).suffix.lower()
-    return suffix if re.fullmatch(r"\.[a-z0-9]{1,10}", suffix) else ""
-
-
-async def _persist_group_uploads(
-    room_id: str,
-    files: list[UploadFile],
-    *,
-    root: Path | None = None,
-) -> list[dict[str, object]]:
-    if not files:
-        raise GroupInvalidRequest("At least one attachment is required")
-    if len(files) > _MAX_GROUP_UPLOAD_FILES:
-        raise GroupAPIError(
-            "too_many_uploads",
-            f"At most {_MAX_GROUP_UPLOAD_FILES} attachments are allowed",
-            413,
-        )
-    upload_root = (root or _group_upload_root()).resolve()
-    room_root = upload_root / room_id
-    created: list[Path] = []
-    temporary: list[Path] = []
-    total_bytes = 0
-    result: list[dict[str, object]] = []
-    try:
-        room_root.mkdir(mode=0o700, parents=True, exist_ok=True)
-        os.chmod(upload_root, 0o700)
-        os.chmod(room_root, 0o700)
-        for source in files:
-            identifier = str(uuid4())
-            name = _safe_upload_name(source.filename)
-            destination = room_root / f"{identifier}{_safe_upload_extension(name)}"
-            partial = room_root / f".{identifier}.part"
-            temporary.append(partial)
-            file_bytes = 0
-            with partial.open("xb") as output:
-                os.chmod(partial, 0o600)
-                while True:
-                    chunk = await source.read(_GROUP_UPLOAD_CHUNK_BYTES)
-                    if not chunk:
-                        break
-                    file_bytes += len(chunk)
-                    total_bytes += len(chunk)
-                    if file_bytes > _MAX_GROUP_UPLOAD_FILE_BYTES:
-                        raise GroupAPIError(
-                            "upload_too_large",
-                            f"{name} exceeds 25 MiB",
-                            413,
-                        )
-                    if total_bytes > _MAX_GROUP_UPLOAD_REQUEST_BYTES:
-                        raise GroupAPIError(
-                            "upload_request_too_large",
-                            "Combined attachments exceed 50 MiB",
-                            413,
-                        )
-                    output.write(chunk)
-            partial.replace(destination)
-            temporary.remove(partial)
-            os.chmod(destination, 0o600)
-            created.append(destination)
-            media_type = (source.content_type or "application/octet-stream").strip()
-            result.append(
-                {
-                    "id": identifier,
-                    "name": name,
-                    "path": str(destination),
-                    "mimeType": media_type or "application/octet-stream",
-                    "size": file_bytes,
-                }
-            )
-        return result
-    except GroupAPIError:
-        for path in [*temporary, *created]:
-            path.unlink(missing_ok=True)
-        raise
-    except (OSError, ValueError) as error:
-        for path in [*temporary, *created]:
-            path.unlink(missing_ok=True)
-        _log_runtime_failure("Failed to persist a group attachment", error)
-        raise GroupStorageAPIError() from error
-    finally:
-        for source in files:
-            await source.close()
-
-
-def _error_response(error: GroupAPIError) -> JSONResponse:
-    return JSONResponse(
-        status_code=error.status_code,
-        content={
-            "detail": {
-                "code": error.code,
-                "message": error.message,
-                "details": error.details,
-            }
-        },
-    )
-
-
-def _validation_details(error: RequestValidationError) -> dict[str, object]:
-    errors = [
-        {
-            "location": list(item.get("loc", ())),
-            "message": item.get("msg", "Invalid value"),
-            "type": item.get("type", "validation_error"),
-        }
-        for item in error.errors()
-    ]
-    return {"errors": errors}
-
-
-def _public_error(error: Exception) -> GroupAPIError:
-    if isinstance(error, GroupAPIError):
-        return error
-    if isinstance(error, RequestValidationError):
-        return GroupAPIError(
-            "validation_error",
-            "Request validation failed",
-            422,
-            _validation_details(error),
-        )
-    if isinstance(error, IdempotencyConflict):
-        return GroupAPIError("idempotency_conflict", str(error), 409)
-    if isinstance(error, GroupNotFoundError):
-        return GroupAPIError("not_found", str(error), 404)
-    if isinstance(error, GroupConflictError):
-        return GroupAPIError("conflict", str(error), 409)
-    if isinstance(error, GroupStoreError):
-        return GroupStorageAPIError()
-    if isinstance(error, sqlite3.Error):
-        return GroupStorageAPIError()
-    return GroupInternalAPIError()
-
-
-class GroupAPIRoute(APIRoute):
-    """Apply the plugin error envelope to validation and endpoint failures."""
-
-    def get_route_handler(self) -> Callable[[Request], Any]:
-        original = super().get_route_handler()
-
-        async def wrapped(request: Request):
-            try:
-                return await original(request)
-            except Exception as error:
-                public = _public_error(error)
-                return _error_response(public)
-
-        return wrapped
-
-
-class _UnavailableRuntime:
-    async def wake(self) -> None:
-        """A missing orchestrator is harmless until Task 8 binds one."""
-
-    async def create_room(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def update_room(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def archive_room(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def restore_room(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def archive_topic(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def restore_topic(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def add_agent(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def update_agent(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def delete_agent(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def send_message(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def interrupt_agent(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def respond_approval(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-    async def respond_clarification(self, **_: object) -> dict[str, object]:
-        raise _package._yaoyao_group_runtime_unavailable_error()
-
-
-def _default_orchestrator_factory(store: object) -> object:
-    """Construct the runtime lazily so importing the plugin has no side effects."""
-
-    module = importlib.import_module(f"{_LOCAL_PACKAGE}.group_orchestrator")
-    return module.GroupOrchestrator(store, work_enabled=_plugin_runtime_enabled)
-
-
-class _RuntimeManager:
-    """Own exactly one orchestrator for one nested Router lifespan generation."""
-
-    def __init__(self) -> None:
-        self._lock: asyncio.Lock | None = None
-        self._leases = 0
-        self._orchestrator: object | None = None
-        self._accepting = False
-        self._starting = False
-        self._releasing = False
-        self._generation = 0
-        self._inflight = 0
-        self._inflight_zero: asyncio.Event | None = None
-        self._start_done: asyncio.Event | None = None
-        self._release_done: asyncio.Event | None = None
-        self._release_task: asyncio.Task[None] | None = None
-
-    def _current_lock(self) -> asyncio.Lock:
-        if self._lock is None:
-            self._lock = asyncio.Lock()
-        return self._lock
-
-    async def acquire(self) -> None:
-        lock = self._current_lock()
-        while True:
-            async with lock:
-                if self._releasing:
-                    wait_for = self._release_done
-                elif self._starting:
-                    wait_for = self._start_done
-                elif self._leases:
-                    self._leases += 1
-                    return
-                else:
-                    wait_for = None
-                    self._generation += 1
-                    generation = self._generation
-                    self._leases = 1
-                    self._starting = True
-                    self._accepting = False
-                    self._inflight = 0
-                    self._inflight_zero = asyncio.Event()
-                    self._inflight_zero.set()
-                    self._start_done = asyncio.Event()
-                    if _package._yaoyao_group_runtime_override:
-                        self._starting = False
-                        self._accepting = True
-                        self._start_done.set()
-                        return
-            if wait_for is not None:
-                await wait_for.wait()
-                continue
-            break
-
-        orchestrator: object | None = None
-        try:
-            store = _store_instance()
-            factory = _package._yaoyao_group_orchestrator_factory
-
-            def adopt(created: object) -> None:
-                nonlocal orchestrator
-                orchestrator = created
-
-            await self._run_owned_start_worker(factory, store, adopt=adopt)
-            start = getattr(orchestrator, "start")
-            await self._run_owned_start(start(), cancel_worker=True)
-        except asyncio.CancelledError as start_cancellation:
-            cleanup_cancellation: asyncio.CancelledError | None = None
-            try:
-                await self._cleanup_failed_start(orchestrator)
-            except asyncio.CancelledError as error:
-                cleanup_cancellation = error
-            finally:
-                async with lock:
-                    if self._generation == generation and self._starting:
-                        self._leases = 0
-                        self._starting = False
-                        self._reset_generation()
-                        if self._start_done is not None:
-                            self._start_done.set()
-                            self._start_done = None
-            raise cleanup_cancellation or start_cancellation
-        except BaseException as error:  # noqa: BLE001 - isolate plugin startup
-            cleanup_cancellation = None
-            try:
-                await self._cleanup_failed_start(orchestrator)
-            except asyncio.CancelledError as cancelled:
-                cleanup_cancellation = cancelled
-            async with lock:
-                _log_runtime_failure("YaoYao group runtime startup failed", error)
-                if self._generation == generation and self._starting:
-                    if cleanup_cancellation is not None:
-                        self._leases = 0
-                        self._reset_generation()
-                    else:
-                        self._starting = False
-                    if self._start_done is not None:
-                        self._start_done.set()
-                        self._start_done = None
-            if cleanup_cancellation is not None:
-                raise cleanup_cancellation
-            return
-
-        async with lock:
-            if self._generation != generation or not self._starting:
-                await self._cleanup_failed_start(orchestrator)
-                return
-            self._orchestrator = orchestrator
-            with _package._yaoyao_group_store_lock:
-                if _package._yaoyao_group_store is store:
-                    _package._yaoyao_group_store_ready = True
-            _publish_runtime(orchestrator)
-            self._starting = False
-            self._accepting = True
-            if self._start_done is not None:
-                self._start_done.set()
-                self._start_done = None
-
-    async def release(self) -> None:
-        lock = self._current_lock()
-        cancellation: asyncio.CancelledError | None = None
-        while True:
-            try:
-                await lock.acquire()
-                break
-            except asyncio.CancelledError as error:
-                if cancellation is None:
-                    cancellation = error
-                if not self._discard_current_cancellation():
-                    raise
-        release_task: asyncio.Task[None] | None = None
-        try:
-            if self._releasing:
-                release_task = self._release_task
-            elif self._leases:
-                self._leases -= 1
-                if self._leases == 0:
-                    self._releasing = True
-                    self._accepting = False
-                    self._release_done = asyncio.Event()
-                    generation = self._generation
-                    orchestrator = self._orchestrator
-                    release_done = self._release_done
-                    if not _package._yaoyao_group_runtime_override:
-                        _publish_runtime(_UnavailableRuntime())
-                    release_task = asyncio.create_task(
-                        self._release_generation(
-                            generation=generation,
-                            orchestrator=orchestrator,
-                            inflight_zero=self._inflight_zero,
-                            release_done=release_done,
-                        ),
-                        name=f"yaoyao-group-release-{generation}",
-                    )
-                    self._release_task = release_task
-        finally:
-            lock.release()
-        if release_task is not None:
-            try:
-                await self._wait_for_owned_task(release_task)
-            except BaseException:
-                if cancellation is not None:
-                    raise cancellation
-                raise
-        if cancellation is not None:
-            raise cancellation
-
-    async def _release_generation(
-        self,
-        *,
-        generation: int,
-        orchestrator: object | None,
-        inflight_zero: asyncio.Event | None,
-        release_done: asyncio.Event,
-    ) -> None:
-        try:
-            await self._wait_for_inflight_release(inflight_zero)
-            if orchestrator is not None:
-                await self._shutdown_owned_runtime(orchestrator, generation)
-        except BaseException as error:  # noqa: BLE001 - host shutdown must continue
-            _log_runtime_failure("YaoYao group runtime shutdown failed", error)
-        finally:
-            await self._finish_owned_release(
-                generation=generation,
-                orchestrator=orchestrator,
-                release_done=release_done,
-            )
-
-    @staticmethod
-    async def _wait_for_owned_task(task: asyncio.Task[object]) -> object:
-        """Return only after a manager-owned task, preserving caller cancellation."""
-
-        cancellation: asyncio.CancelledError | None = None
-        while not task.done():
-            try:
-                await asyncio.shield(task)
-            except asyncio.CancelledError as error:
-                if task.done():
-                    break
-                if cancellation is None:
-                    cancellation = error
-        try:
-            result = task.result()
-        except BaseException:
-            if cancellation is not None:
-                raise cancellation
-            raise
-        if cancellation is not None:
-            raise cancellation
-        return result
-
-    @staticmethod
-    def _discard_current_cancellation() -> bool:
-        """Clear cancellation counts only for cleanup tasks that intentionally persist."""
-
-        task = asyncio.current_task()
-        cancelling = getattr(task, "cancelling", None)
-        uncancel = getattr(task, "uncancel", None)
-        if not callable(cancelling) or not callable(uncancel):
-            return False
-        had_cancellation = bool(cancelling())
-        while cancelling():
-            uncancel()
-        return had_cancellation
-
-    async def _wait_for_inflight_release(
-        self, inflight_zero: asyncio.Event | None
-    ) -> None:
-        if inflight_zero is None:
-            return
-        while not inflight_zero.is_set():
-            try:
-                await inflight_zero.wait()
-            except asyncio.CancelledError:
-                if not self._discard_current_cancellation():
-                    raise
-
-    async def _shutdown_owned_runtime(
-        self, orchestrator: object, generation: int
-    ) -> None:
-        """Shield shutdown from release cancellation, including loop teardown."""
-
-        shutdown_task = asyncio.create_task(
-            self._run_owned_shutdown(orchestrator),
-            name=f"yaoyao-group-runtime-shutdown-{generation}",
-        )
-        while not shutdown_task.done():
-            try:
-                await asyncio.shield(shutdown_task)
-            except asyncio.CancelledError:
-                self._discard_current_cancellation()
-        shutdown_task.result()
-
-    async def _run_owned_shutdown(self, orchestrator: object) -> None:
-        while True:
-            try:
-                await getattr(orchestrator, "shutdown")()
-                return
-            except asyncio.CancelledError:
-                if not self._discard_current_cancellation():
-                    raise
-
-    async def _finish_owned_release(
-        self,
-        *,
-        generation: int,
-        orchestrator: object | None,
-        release_done: asyncio.Event,
-    ) -> None:
-        lock = self._current_lock()
-        while True:
-            try:
-                await lock.acquire()
-                break
-            except asyncio.CancelledError:
-                if not self._discard_current_cancellation():
-                    raise
-        try:
-            if (
-                self._generation == generation
-                and self._orchestrator is orchestrator
-                and self._releasing
-            ):
-                self._orchestrator = None
-                self._releasing = False
-                self._inflight = 0
-                self._inflight_zero = None
-                self._release_task = None
-                self._reset_generation()
-            if self._release_done is release_done:
-                self._release_done = None
-        finally:
-            release_done.set()
-            lock.release()
-
-    async def dispatch(self, method: str, **kwargs: object) -> object:
-        """Lease one published runtime through the complete request callback."""
-
-        runtime = await self._begin_operation(require_runtime=True)
-
-        async def invoke() -> object:
-            callback = getattr(runtime, method)
-            is_async = inspect.iscoroutinefunction(
-                callback
-            ) or inspect.iscoroutinefunction(getattr(callback, "__call__", None))
-            if is_async:
-                result = callback(**kwargs)
-            else:
-                result = await asyncio.to_thread(callback, **kwargs)
-            if inspect.isawaitable(result):
-                return await result
-            return result
-
-        return await self._run_owned_operation(
-            invoke(), name=f"yaoyao-group-dispatch-{method}"
-        )
-
-    async def dispatch_store(
-        self,
-        method: str,
-        *args: object,
-        **kwargs: object,
-    ) -> object:
-        """Lease the complete blocking Store read through its worker return."""
-
-        await self._begin_operation(require_runtime=False)
-        return await self._run_owned_operation(
-            asyncio.to_thread(_invoke_store, method, *args, **kwargs),
-            name=f"yaoyao-group-store-{method}",
-        )
-
-    async def _begin_operation(self, *, require_runtime: bool) -> object | None:
-        lock = self._current_lock()
-        async with lock:
-            override = bool(_package._yaoyao_group_runtime_override)
-            if self._starting or self._releasing or not self._accepting:
-                raise _package._yaoyao_group_runtime_unavailable_error()
-            runtime = _package._yaoyao_group_runtime if override else self._orchestrator
-            if require_runtime and (
-                runtime is None or isinstance(runtime, _UnavailableRuntime)
-            ):
-                raise _package._yaoyao_group_runtime_unavailable_error()
-            self._inflight += 1
-            if self._inflight_zero is None:
-                self._inflight_zero = asyncio.Event()
-            self._inflight_zero.clear()
-            return runtime
-
-    async def _run_owned_operation(self, operation: object, *, name: str) -> object:
-        if not inspect.isawaitable(operation):
-            raise TypeError("leased operation must be awaitable")
-        owned_task = asyncio.create_task(operation, name=name)
-
-        def finished(done: asyncio.Task[object]) -> None:
-            try:
-                if not done.cancelled():
-                    done.exception()
-            except asyncio.CancelledError:
-                pass
-            self._inflight -= 1
-            if self._inflight == 0 and self._inflight_zero is not None:
-                self._inflight_zero.set()
-
-        owned_task.add_done_callback(finished)
-        return await asyncio.shield(owned_task)
-
-    async def stream_store(
-        self, websocket: WebSocket, stream: Callable[..., object]
-    ) -> object:
-        """Lease a complete stream; closing invalidates its Store provider."""
-
-        await self._begin_operation(require_runtime=False)
-        generation = self._generation
-
-        async def invoke() -> object:
-            try:
-                result = stream(
-                    websocket, lambda: self.store_for_generation(generation)
-                )
-                if inspect.isawaitable(result):
-                    return await result
-                return result
-            except RuntimeUnavailableError:
-                await websocket.close(code=1013, reason="Group runtime is unavailable")
-                return None
-
-        return await self._run_owned_operation(
-            invoke(), name=f"yaoyao-group-stream-{generation}"
-        )
-
-    def store_for_generation(self, generation: int) -> object:
-        """Resolve Store only while a WebSocket still belongs to this generation."""
-
-        if (
-            generation != self._generation
-            or self._starting
-            or self._releasing
-            or not self._accepting
-        ):
-            raise _package._yaoyao_group_runtime_unavailable_error()
-        return _initialized_store()
-
-    @staticmethod
-    async def _cleanup_failed_start(orchestrator: object | None) -> None:
-        if orchestrator is None:
-            return
-        try:
-            await _RuntimeManager._run_owned_start(getattr(orchestrator, "shutdown")())
-        except asyncio.CancelledError:
-            raise
-        except BaseException as error:  # noqa: BLE001 - preserve startup isolation
-            _log_runtime_failure("YaoYao group partial runtime cleanup failed", error)
-
-    @staticmethod
-    async def _run_owned_start(
-        operation: object, *, cancel_worker: bool = False
-    ) -> object:
-        """Wait out caller cancellation before relinquishing startup ownership."""
-
-        if not inspect.isawaitable(operation):
-            raise TypeError("runtime start must be awaitable")
-        worker = asyncio.create_task(operation, name="yaoyao-group-runtime-start")
-        cancellation: asyncio.CancelledError | None = None
-        while not worker.done():
-            try:
-                await asyncio.shield(worker)
-            except asyncio.CancelledError as error:
-                if cancellation is None:
-                    cancellation = error
-                    if cancel_worker:
-                        worker.cancel()
-        try:
-            result = worker.result()
-        except BaseException:
-            if cancellation is not None:
-                raise cancellation
-            raise
-        if cancellation is not None:
-            raise cancellation
-        return result
-
-    @staticmethod
-    async def _run_owned_start_worker(
-        callback: Callable[..., object],
-        *args: object,
-        adopt: Callable[[object], None],
-    ) -> object:
-        worker = asyncio.create_task(
-            asyncio.to_thread(callback, *args),
-            name="yaoyao-group-runtime-create",
-        )
-        cancellation: asyncio.CancelledError | None = None
-        while not worker.done():
-            try:
-                await asyncio.shield(worker)
-            except asyncio.CancelledError as error:
-                if cancellation is None:
-                    cancellation = error
-        try:
-            result = worker.result()
-        except BaseException:
-            if cancellation is not None:
-                raise cancellation
-            raise
-        adopt(result)
-        if cancellation is not None:
-            raise cancellation
-        return result
-
-    def _reset_generation(self) -> None:
-        self._accepting = False
-        self._starting = False
-        if not _package._yaoyao_group_store_override:
-            with _package._yaoyao_group_store_lock:
-                _package._yaoyao_group_store = None
-                _package._yaoyao_group_store_ready = False
-
-
-@asynccontextmanager
-async def _router_lifespan(_: object):
-    manager = _package._yaoyao_group_runtime_manager
-    await manager.acquire()
-    try:
-        yield
-    finally:
-        await manager.release()
-
-
-_bootstrap_lock = vars(_package).setdefault(
-    "_yaoyao_group_bootstrap_lock", threading.RLock()
-)
-with _bootstrap_lock:
-    if not hasattr(_package, "_yaoyao_group_store_lock"):
-        _package._yaoyao_group_runtime_unavailable_error = RuntimeUnavailableError
-        _package._yaoyao_group_store_lock = threading.Lock()
-        _package._yaoyao_group_store = None
-        _package._yaoyao_group_store_ready = False
-        _package._yaoyao_group_store_override = False
-        _package._yaoyao_group_runtime = _UnavailableRuntime()
-        _package._yaoyao_group_runtime_override = False
-        _package._yaoyao_group_orchestrator_factory = _default_orchestrator_factory
-        _package._yaoyao_group_runtime_manager = _RuntimeManager()
-        _package._yaoyao_node_worker_lock = threading.Lock()
-        _package._yaoyao_node_worker = None
-        _package._yaoyao_node_registry_lock = threading.Lock()
-        _package._yaoyao_node_registry = None
-    if not hasattr(_package, "_yaoyao_node_worker_lock"):
-        _package._yaoyao_node_worker_lock = threading.Lock()
-        _package._yaoyao_node_worker = None
-    if not hasattr(_package, "_yaoyao_node_registry_lock"):
-        _package._yaoyao_node_registry_lock = threading.Lock()
-        _package._yaoyao_node_registry = None
-
-
-def set_store_for_testing(store: object | None) -> None:
-    """Inject an isolated store; initialization remains lazy and off-loop."""
-    with _package._yaoyao_group_store_lock:
-        _package._yaoyao_group_store = store
-        _package._yaoyao_group_store_ready = False
-        _package._yaoyao_group_store_override = store is not None
-
-
-def set_agent_name_resolver(resolver: Callable[[str], str]) -> None:
-    """Use the host-provided Hermes Bot display-name resolver."""
-    global _agent_name_resolver
-    _agent_name_resolver = resolver
-
-
-def set_node_worker_for_testing(worker: object | None) -> None:
-    with _package._yaoyao_node_worker_lock:
-        current = _package._yaoyao_node_worker
-        if current is not None and current is not worker:
-            shutdown = getattr(current, "shutdown", None)
-            if callable(shutdown):
-                shutdown()
-        _package._yaoyao_node_worker = worker
-
-
-def _node_worker_instance() -> object:
-    with _package._yaoyao_node_worker_lock:
-        worker = _package._yaoyao_node_worker
-        if worker is None:
-            worker = NodeGatewayWorker()
-            _package._yaoyao_node_worker = worker
-        return worker
-
-
-async def _node_worker_call(method: str, *args: object, **kwargs: object) -> object:
-    worker = _node_worker_instance()
-    operation = getattr(worker, method, None)
-    if not callable(operation):
-        raise RuntimeUnavailableError()
-    return await asyncio.to_thread(operation, *args, **kwargs)
-
-
-def set_node_registry_for_testing(registry: object | None) -> None:
-    with _package._yaoyao_node_registry_lock:
-        _package._yaoyao_node_registry = registry
-
-
-def _node_registry_instance() -> object:
-    with _package._yaoyao_node_registry_lock:
-        registry = _package._yaoyao_node_registry
-        if registry is None:
-            registry = PairedNodeRegistry.from_environment()
-            _package._yaoyao_node_registry = registry
-        return registry
-
-
-async def _node_registry_call(
-    method: str, *args: object, **kwargs: object
-) -> object:
-    registry = _node_registry_instance()
-    operation = getattr(registry, method, None)
-    if not callable(operation):
-        raise RuntimeUnavailableError()
-    return await asyncio.to_thread(operation, *args, **kwargs)
-
-
-def set_runtime_facade(runtime: object | None) -> None:
-    """Bind the narrow Task-8 runtime surface, or restore the safe default."""
-    _package._yaoyao_group_runtime_override = runtime is not None
-    _publish_runtime(_UnavailableRuntime() if runtime is None else runtime)
-    manager = _package._yaoyao_group_runtime_manager
-    if runtime is None:
-        manager._accepting = False
-    elif not manager._starting and not manager._releasing:
-        manager._accepting = True
-
-
-def set_orchestrator_factory_for_testing(
-    factory: Callable[[object], object] | None,
-) -> None:
-    """Inject construction without importing the real Gateway runtime."""
-
-    _package._yaoyao_group_orchestrator_factory = (
-        _default_orchestrator_factory if factory is None else factory
-    )
-
-
-def _publish_runtime(runtime: object) -> None:
-    _package._yaoyao_group_runtime = runtime
-
-
-def _store_instance() -> object:
-    with _package._yaoyao_group_store_lock:
-        if _package._yaoyao_group_store is None:
-            _package._yaoyao_group_store = GroupStore.from_environment(
-                agent_name_resolver=_agent_name_resolver
-            )
-        return _package._yaoyao_group_store
-
-
-def _initialized_store() -> object:
-    with _package._yaoyao_group_store_lock:
-        if _package._yaoyao_group_store is None:
-            _package._yaoyao_group_store = GroupStore.from_environment(
-                agent_name_resolver=_agent_name_resolver
-            )
-        store = _package._yaoyao_group_store
-        if not _package._yaoyao_group_store_ready:
-            store.initialize()
-            _package._yaoyao_group_store_ready = True
-        return store
-
-
-def _invoke_store(method: str, *args: object, **kwargs: object) -> object:
-    """Run one trusted Store operation and classify only its input failures."""
-    try:
-        store = _initialized_store()
-    except sqlite3.Error as error:
-        raise GroupStorageAPIError() from error
-    try:
-        return getattr(store, method)(*args, **kwargs)
-    except ValueError as error:
-        raise GroupInvalidRequest(str(error)) from error
-    except sqlite3.Error as error:
-        raise GroupStorageAPIError() from error
-
-
-async def _store_call(method: str, *args: object, **kwargs: object) -> object:
-    return await _package._yaoyao_group_runtime_manager.dispatch_store(
-        method, *args, **kwargs
-    )
-
-
-async def _runtime_call(method: str, **kwargs: object) -> object:
-    return await _package._yaoyao_group_runtime_manager.dispatch(method, **kwargs)
-
-
-def _command(model: object, *, exclude_unset: bool = False) -> dict[str, object]:
-    return model.model_dump(
-        mode="json",
-        by_alias=True,
-        exclude_unset=exclude_unset,
-    )
-
-
-def _create_room_command(request: CreateRoomRequest) -> dict[str, object]:
-    command = _command(request)
-    if "max_reply_rounds" not in request.model_fields_set:
-        command.pop("maxReplyRounds", None)
-    if "orchestration_mode" not in request.model_fields_set:
-        command.pop("orchestrationMode", None)
-    if "instructions" not in request.model_fields_set:
-        command.pop("instructions", None)
-    if "avatar" not in request.model_fields_set:
-        command.pop("avatar", None)
-    agents = command.get("agents")
-    if isinstance(agents, list):
-        for seed, item in zip(request.agents, agents):
-            if (
-                isinstance(item, dict)
-                and "reply_without_mention" not in seed.model_fields_set
-            ):
-                item.pop("replyWithoutMention", None)
-            if isinstance(item, dict) and "is_host" not in seed.model_fields_set:
-                item.pop("isHost", None)
-            if isinstance(item, dict) and "node_id" not in seed.model_fields_set:
-                item.pop("nodeId", None)
-            if isinstance(item, dict) and "node_label" not in seed.model_fields_set:
-                item.pop("nodeLabel", None)
-            if isinstance(item, dict):
-                for field, alias in (
-                    ("model", "model"),
-                    ("provider", "provider"),
-                    ("reasoning_effort", "reasoningEffort"),
-                    ("fast_mode", "fastMode"),
-                ):
-                    if field not in seed.model_fields_set:
-                        item.pop(alias, None)
-    return command
-
-
-def _add_agent_command(request: AddAgentRequest) -> dict[str, object]:
-    command = _command(request)
-    if "reply_without_mention" not in request.model_fields_set:
-        command.pop("replyWithoutMention", None)
-    if "is_host" not in request.model_fields_set:
-        command.pop("isHost", None)
-    if "node_id" not in request.model_fields_set:
-        command.pop("nodeId", None)
-    if "node_label" not in request.model_fields_set:
-        command.pop("nodeLabel", None)
-    for field, alias in (
-        ("model", "model"),
-        ("provider", "provider"),
-        ("reasoning_effort", "reasoningEffort"),
-        ("fast_mode", "fastMode"),
-    ):
-        if field not in request.model_fields_set:
-            command.pop(alias, None)
-    return command
-
-
-def _validated_interaction_id(value: str) -> str:
-    try:
-        return normalize_interaction_id(value)
-    except ValueError as error:
-        raise GroupInvalidRequest(str(error)) from error
-
-
-async def capabilities() -> dict[str, object]:
-    journal_epoch = await _store_call("journal_epoch")
-    latest_cursor = await _store_call("latest_cursor")
-    return {
-        "protocolVersion": PROTOCOL_VERSION,
-        "journalEpoch": journal_epoch,
-        "latestCursor": latest_cursor,
-        "limits": limits_payload(),
-        "eventTypes": sorted(EVENT_TYPES),
-        "features": [
-            "hostFlow", "roomInstructions", "roomAvatar", "globalTopics",
-            "nodeWorker", "nodeRegistry"
-        ],
-    }
-
-
-async def list_rooms(
-    limit: int = Query(default=50, ge=1, le=100),
-    cursor: str | None = Query(default=None, min_length=1, max_length=4096),
-    archived: bool = Query(default=False),
-) -> dict[str, object]:
-    page = await _store_call(
-        "list_rooms", limit=limit, cursor=cursor, archived=archived
-    )
-    return {"items": page.items, "nextCursor": page.next_cursor}
-
-
-async def list_topics(
-    room_id: UUID,
-    limit: int = Query(default=50, ge=1, le=100),
-    cursor: str | None = Query(default=None, min_length=1, max_length=4096),
-    archived: bool = Query(default=False),
-) -> dict[str, object]:
-    page = await _store_call(
-        "list_topics", str(room_id), limit=limit, cursor=cursor,
-        archived=archived,
-    )
-    return {"items": page.items, "nextCursor": page.next_cursor}
-
-
-async def list_global_topics(
-    limit: int = Query(default=50, ge=1, le=100),
-    cursor: str | None = Query(default=None, min_length=1, max_length=4096),
-) -> dict[str, object]:
-    page = await _store_call(
-        "list_global_topics", limit=limit, cursor=cursor
-    )
-    return {"items": page.items, "nextCursor": page.next_cursor}
-
-
-async def list_pinned_topics(
-    limit: int = Query(default=100, ge=1, le=100),
-) -> dict[str, object]:
-    page = await _store_call("list_pinned_topics", limit=limit)
-    return {"items": page.items, "nextCursor": page.next_cursor}
-
-
-async def update_topic(
-    room_id: UUID, topic_id: UUID, request: UpdateTopicRequest
-) -> dict[str, object]:
-    return await _runtime_call(
-        "update_topic",
-        room_id=str(room_id),
-        topic_id=str(topic_id),
-        command=_command(request, exclude_unset=True),
-    )
-
-
-async def archive_topic(
-    room_id: UUID, topic_id: UUID, request: RequestIDRequest
-) -> dict[str, object]:
-    return await _runtime_call(
-        "archive_topic", room_id=str(room_id), topic_id=str(topic_id),
-        request_id=str(request.request_id),
-    )
-
-
-async def restore_topic(
-    room_id: UUID, topic_id: UUID, request: RequestIDRequest
-) -> dict[str, object]:
-    return await _runtime_call(
-        "restore_topic", room_id=str(room_id), topic_id=str(topic_id),
-        request_id=str(request.request_id),
-    )
-
-
-async def mark_topic_read(
-    room_id: UUID, topic_id: UUID, request: MarkTopicReadRequest
-) -> dict[str, object]:
-    return await _runtime_call(
-        "mark_topic_read",
-        room_id=str(room_id),
-        topic_id=str(topic_id),
-        command=_command(request, exclude_unset=True),
-    )
-
-
-async def create_room(request: CreateRoomRequest) -> dict[str, object]:
-    return await _runtime_call("create_room", command=_create_room_command(request))
-
-
-async def get_room(room_id: UUID) -> dict[str, object]:
-    return await _store_call("room_snapshot", str(room_id))
-
-
-async def update_room(room_id: UUID, request: UpdateRoomRequest) -> dict[str, object]:
-    return await _runtime_call(
-        "update_room",
-        room_id=str(room_id),
-        command=_command(request, exclude_unset=True),
-    )
-
-
-async def archive_room(room_id: UUID, request: RequestIDRequest) -> dict[str, object]:
-    return await _runtime_call(
-        "archive_room",
-        room_id=str(room_id),
-        request_id=str(request.request_id),
-    )
-
-
-async def restore_room(room_id: UUID, request: RequestIDRequest) -> dict[str, object]:
-    return await _runtime_call(
-        "restore_room", room_id=str(room_id), request_id=str(request.request_id)
-    )
-
-
-async def add_agent(room_id: UUID, request: AddAgentRequest) -> dict[str, object]:
-    return await _runtime_call(
-        "add_agent", room_id=str(room_id), command=_add_agent_command(request)
-    )
-
-
-async def update_agent(
-    room_id: UUID,
-    agent_id: UUID,
-    request: UpdateAgentRequest,
-) -> dict[str, object]:
-    return await _runtime_call(
-        "update_agent",
-        room_id=str(room_id),
-        agent_id=str(agent_id),
-        command=_command(request, exclude_unset=True),
-    )
-
-
-async def delete_agent(
-    room_id: UUID,
-    agent_id: UUID,
-    request: RequestIDRequest,
-) -> dict[str, object]:
-    return await _runtime_call(
-        "delete_agent",
-        room_id=str(room_id),
-        agent_id=str(agent_id),
-        request_id=str(request.request_id),
-    )
-
-
-async def interrupt_agent(
-    room_id: UUID,
-    agent_id: UUID,
-    request: RequestIDRequest,
-) -> object:
-    return await _runtime_call(
-        "interrupt_agent",
-        room_id=str(room_id),
-        agent_id=str(agent_id),
-        request_id=str(request.request_id),
-    )
-
-
-async def list_messages(
-    room_id: UUID,
-    topic_id: UUID | None = Query(default=None, alias="topicId"),
-    before_seq: int | None = Query(default=None, alias="beforeSeq", ge=1),
-    after_seq: int | None = Query(default=None, alias="afterSeq", ge=1),
-    limit: int = Query(default=MAX_MESSAGE_PAGE_SIZE, ge=1, le=MAX_MESSAGE_PAGE_SIZE),
-) -> dict[str, object]:
-    items = await _store_call(
-        "list_messages",
-        str(room_id),
-        topic_id=None if topic_id is None else str(topic_id),
-        before_seq=before_seq,
-        after_seq=after_seq,
-        limit=limit,
-    )
-    return {"items": items}
-
-
-async def upload_group_files(
-    room_id: UUID,
-    files: Annotated[list[UploadFile], File(alias="file")],
-) -> dict[str, object]:
-    canonical_room_id = str(room_id)
-    await _store_call("room_snapshot", canonical_room_id)
-    return {
-        "files": await _persist_group_uploads(canonical_room_id, files),
-    }
-
-
-async def send_message(room_id: UUID, request: SendMessageRequest) -> dict[str, object]:
-    return await _runtime_call(
-        "send_message",
-        room_id=str(room_id),
-        request_id=str(request.request_id),
-        client_message_id=str(request.client_message_id),
-        topic_id=None if request.topic_id is None else str(request.topic_id),
-        content=request.content,
-        mention_agent_ids=[str(agent_id) for agent_id in request.mention_agent_ids],
-    )
-
-
-async def respond_approval(
-    room_id: UUID,
-    request: ApprovalRequest,
-    interaction_id: str = APIPath(min_length=1, max_length=200),
-) -> object:
-    canonical_interaction_id = _validated_interaction_id(interaction_id)
-    return await _runtime_call(
-        "respond_approval",
-        room_id=str(room_id),
-        interaction_id=canonical_interaction_id,
-        request_id=str(request.request_id),
-        choice=request.choice,
-        permanent=request.permanent,
-    )
-
-
-async def respond_clarification(
-    room_id: UUID,
-    request: ClarificationRequest,
-    interaction_id: str = APIPath(min_length=1, max_length=200),
-) -> object:
-    canonical_interaction_id = _validated_interaction_id(interaction_id)
-    return await _runtime_call(
-        "respond_clarification",
-        room_id=str(room_id),
-        interaction_id=canonical_interaction_id,
-        request_id=str(request.request_id),
-        response=request.response,
-    )
-
-
-def _node_client_id(request: Request) -> str:
-    value = request.headers.get("x-yaoyao-node-client", "").strip().lower()
-    try:
-        canonical = str(UUID(value))
-    except ValueError as error:
-        raise GroupInvalidRequest("Paired node client identity is required") from error
-    if canonical != value:
-        raise GroupInvalidRequest("Paired node client identity is required")
-    return canonical
-
-
-async def node_worker_open_session(
-    payload: NodeWorkerOpenRequest,
-    request: Request,
-) -> object:
-    return await _node_worker_call(
-        "open_session", payload, _node_client_id(request)
-    )
-
-
-async def register_paired_node(request: Request) -> object:
-    try:
-        payload = await request.json()
-    except Exception as error:
-        raise GroupInvalidRequest("Node registration requires JSON") from error
-    if not isinstance(payload, dict):
-        raise GroupInvalidRequest("Node registration must be an object")
-    return await _node_registry_call("register", payload)
-
-
-async def list_paired_nodes() -> dict[str, object]:
-    nodes = await _node_registry_call("list")
-    return {"items": nodes}
-
-
-async def refresh_paired_node_identities() -> dict[str, object]:
-    nodes = await _node_registry_call("list")
-    refreshed: list[dict[str, object]] = []
-    failed: list[str] = []
-    opener = build_opener(ProxyHandler({}))
-    for public in nodes:
-        node_id = public.get("nodeId") if isinstance(public, dict) else None
-        if not isinstance(node_id, str):
-            continue
-        try:
-            node = await _node_registry_call("get", node_id)
-            server_url = node.get("serverUrl")
-            access_token = node.get("accessToken")
-            if not isinstance(server_url, str) or not isinstance(access_token, str):
-                raise ValueError("invalid node route")
-            remote_request = URLRequest(
-                server_url.rstrip("/") + "/api/profile-identities",
-                method="GET",
-                headers={
-                    "Accept": "application/json",
-                    "Authorization": f"Bearer {access_token}",
-                },
-            )
-
-            def fetch() -> object:
-                with opener.open(remote_request, timeout=35) as response:
-                    raw = response.read(32 * 1024 * 1024 + 1)
-                if len(raw) > 32 * 1024 * 1024:
-                    raise ValueError("identity response too large")
-                return json.loads(raw)
-
-            payload = await asyncio.to_thread(fetch)
-            profiles = payload.get("profiles") if isinstance(payload, dict) else None
-            refreshed.append(await _node_registry_call("register", {
-                "nodeId": node_id,
-                "name": node["name"],
-                "serverUrl": server_url,
-                "fingerprint": node["fingerprint"],
-                "accessToken": access_token,
-                "profiles": profiles,
-            }))
-        except Exception:
-            failed.append(node_id)
-    return {"items": refreshed, "failedNodeIds": failed}
-
-
-async def revoke_paired_node(node_id: UUID) -> dict[str, object]:
-    removed = await _node_registry_call("revoke", str(node_id))
-    if not removed:
-        raise GroupInvalidRequest("Paired Hermes node was not found")
-    return {"ok": True}
-
-
-async def download_paired_node_file(
-    node_id: UUID,
-    request: Request,
-    path: Annotated[str, Query(min_length=1, max_length=8192)],
-) -> object:
-    try:
-        node = await _node_registry_call("get", str(node_id))
-    except Exception as error:
-        raise GroupInvalidRequest("Paired Hermes node was not found") from error
-    server_url = node.get("serverUrl")
-    access_token = node.get("accessToken")
-    if not isinstance(server_url, str) or not isinstance(access_token, str):
-        raise GroupInvalidRequest("Paired Hermes node route is invalid")
-    target = server_url.rstrip("/") + "/api/node-files?" + urlencode({"path": path})
-    headers = {
-        "Accept": "application/octet-stream",
-        "Authorization": f"Bearer {access_token}",
-    }
-    requested_range = request.headers.get("range", "")
-    if requested_range and re.fullmatch(r"bytes=\d*-\d*", requested_range):
-        headers["Range"] = requested_range
-    remote_request = URLRequest(target, method="GET", headers=headers)
-    opener = build_opener(ProxyHandler({}))
-    try:
-        response = await asyncio.to_thread(opener.open, remote_request, timeout=60)
-    except HTTPError as error:
-        status = error.code if 400 <= error.code <= 599 else 502
-        error.close()
-        return JSONResponse(
-            status_code=status,
-            content={"error": "Remote node file request was rejected"},
-        )
-    except (URLError, TimeoutError, OSError) as error:
-        raise GroupInvalidRequest("Remote node file is unavailable") from error
-
-    def body_stream():
-        try:
-            while True:
-                chunk = response.read(256 * 1024)
-                if not chunk:
-                    break
-                yield chunk
-        finally:
-            response.close()
-
-    outgoing_headers = {"Cache-Control": "private, no-store"}
-    for source, target_name in (
-        ("Content-Length", "Content-Length"),
-        ("Content-Range", "Content-Range"),
-        ("Accept-Ranges", "Accept-Ranges"),
-        ("Content-Disposition", "Content-Disposition"),
-    ):
-        value = response.headers.get(source)
-        if value and "\r" not in value and "\n" not in value:
-            outgoing_headers[target_name] = value
-    return StreamingResponse(
-        body_stream(),
-        status_code=getattr(response, "status", 200),
-        media_type=response.headers.get("Content-Type", "application/octet-stream"),
-        headers=outgoing_headers,
-    )
-
-
-async def node_worker_submit_prompt(
-    runtime_session_id: str,
-    payload: NodeWorkerPromptRequest,
-    request: Request,
-) -> dict[str, object]:
-    await _node_worker_call(
-        "submit_prompt", runtime_session_id, payload, _node_client_id(request)
-    )
-    return {"status": "streaming"}
-
-
-async def node_worker_interrupt(
-    runtime_session_id: str,
-    request: Request,
-) -> dict[str, object]:
-    await _node_worker_call(
-        "interrupt", runtime_session_id, _node_client_id(request)
-    )
-    return {"status": "interrupted"}
-
-
-async def node_worker_close_session(
-    runtime_session_id: str,
-    request: Request,
-) -> dict[str, object]:
-    closed = await _node_worker_call(
-        "close_session", runtime_session_id, _node_client_id(request)
-    )
-    return {"closed": bool(closed)}
-
-
-async def node_worker_respond_approval(
-    runtime_session_id: str,
-    payload: NodeWorkerApprovalRequest,
-    request: Request,
-) -> dict[str, object]:
-    resolved = await _node_worker_call(
-        "respond_approval",
-        runtime_session_id,
-        payload,
-        _node_client_id(request),
-    )
-    return {"resolved": resolved}
-
-
-async def node_worker_respond_clarification(
-    payload: NodeWorkerClarificationRequest,
-    request: Request,
-) -> dict[str, object]:
-    status = await _node_worker_call(
-        "respond_clarification", payload, _node_client_id(request)
-    )
-    return {"status": status}
-
-
-async def node_worker_events(
-    request: Request,
-    after: int = Query(default=0, ge=0),
-    runtime_session_id: str | None = Query(
-        default=None, alias="runtimeSessionId", min_length=1, max_length=4096
-    ),
-    limit: int = Query(default=100, ge=1, le=256),
-) -> object:
-    return await _node_worker_call(
-        "events",
-        after=after,
-        runtime_id=runtime_session_id,
-        limit=limit,
-        client_id=_node_client_id(request),
-    )
-
-
-async def node_worker_attach_file(
-    runtime_session_id: str,
-    request: Request,
-) -> object:
-    encoded_name = request.headers.get("x-file-name-b64", "")
-    mime_type = request.headers.get("x-mime-type", "application/octet-stream")
-    try:
-        name = base64.urlsafe_b64decode(
-            encoded_name + "=" * (-len(encoded_name) % 4)
-        ).decode("utf-8")
-    except (ValueError, UnicodeDecodeError) as error:
-        raise GroupInvalidRequest("Attachment name header is invalid") from error
-    content = await request.body()
-    if not content or len(content) > _MAX_GROUP_UPLOAD_FILE_BYTES:
-        raise GroupInvalidRequest("Remote attachment content is invalid")
-    return await _node_worker_call(
-        "attach_file",
-        runtime_session_id,
-        name=name,
-        mime_type=mime_type,
-        content=content,
-        client_id=_node_client_id(request),
-    )
-
-
-async def stream_events(websocket: WebSocket) -> None:
-    """Delegate the read-only event channel to the authenticated streamer."""
-    allowed, close_code = _stream_module.websocket_upgrade_allowed(websocket)
-    if not allowed:
-        await websocket.close(code=close_code)
-        return
-    if not await asyncio.to_thread(_plugin_runtime_enabled):
-        await websocket.close(code=_stream_module.PLUGIN_DISABLED_CLOSE_CODE)
-        return
-
-    async def stream_authorized(
-        websocket: WebSocket, store_provider: Callable[[], object]
-    ) -> None:
-        await _stream_module.stream_authorized_group_events(
-            websocket,
-            store_provider,
-            availability_provider=_plugin_runtime_enabled,
-        )
-
-    try:
-        manager = _package._yaoyao_group_runtime_manager
-        await manager.stream_store(websocket, stream_authorized)
-    except RuntimeUnavailableError:
-        await websocket.close(code=1013, reason="Group runtime is unavailable")
-
-
-def _build_router() -> APIRouter:
-    """Build the immutable route table once per resolved plugin directory."""
-    built = APIRouter(
-        prefix="/v1",
-        tags=["yaoyao-group"],
-        route_class=GroupAPIRoute,
-        lifespan=_router_lifespan,
-    )
-    built.add_api_route("/capabilities", capabilities, methods=["GET"])
-    built.add_api_route("/rooms", list_rooms, methods=["GET"])
-    built.add_api_route("/topics", list_global_topics, methods=["GET"])
-    built.add_api_route("/topics/pinned", list_pinned_topics, methods=["GET"])
-    built.add_api_route("/rooms", create_room, methods=["POST"])
-    built.add_api_route("/rooms/{room_id}", get_room, methods=["GET"])
-    built.add_api_route("/rooms/{room_id}", update_room, methods=["PATCH"])
-    built.add_api_route("/rooms/{room_id}", archive_room, methods=["DELETE"])
-    built.add_api_route("/rooms/{room_id}/restore", restore_room, methods=["POST"])
-    built.add_api_route("/rooms/{room_id}/topics", list_topics, methods=["GET"])
-    built.add_api_route(
-        "/rooms/{room_id}/topics/{topic_id}", update_topic, methods=["PATCH"]
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/topics/{topic_id}", archive_topic, methods=["DELETE"]
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/topics/{topic_id}/restore", restore_topic,
-        methods=["POST"],
-    )
-    built.add_api_route("/rooms/{room_id}/agents", add_agent, methods=["POST"])
-    built.add_api_route(
-        "/rooms/{room_id}/agents/{agent_id}", update_agent, methods=["PATCH"]
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/agents/{agent_id}", delete_agent, methods=["DELETE"]
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/agents/{agent_id}/interrupt",
-        interrupt_agent,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/topics/{topic_id}/read",
-        mark_topic_read,
-        methods=["PATCH"],
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/uploads", upload_group_files, methods=["POST"]
-    )
-    built.add_api_route("/rooms/{room_id}/messages", list_messages, methods=["GET"])
-    built.add_api_route("/rooms/{room_id}/messages", send_message, methods=["POST"])
-    built.add_api_route(
-        "/rooms/{room_id}/interactions/{interaction_id}/approval",
-        respond_approval,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/rooms/{room_id}/interactions/{interaction_id}/clarification",
-        respond_clarification,
-        methods=["POST"],
-    )
-    built.add_api_route("/nodes", register_paired_node, methods=["POST"])
-    built.add_api_route("/nodes", list_paired_nodes, methods=["GET"])
-    built.add_api_route(
-        "/nodes/refresh-identities",
-        refresh_paired_node_identities,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/nodes/{node_id}", revoke_paired_node, methods=["DELETE"]
-    )
-    built.add_api_route(
-        "/nodes/{node_id}/files", download_paired_node_file, methods=["GET"]
-    )
-    built.add_api_route(
-        "/node-worker/sessions", node_worker_open_session, methods=["POST"]
-    )
-    built.add_api_route(
-        "/node-worker/sessions/{runtime_session_id}/prompt",
-        node_worker_submit_prompt,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/node-worker/sessions/{runtime_session_id}/interrupt",
-        node_worker_interrupt,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/node-worker/sessions/{runtime_session_id}",
-        node_worker_close_session,
-        methods=["DELETE"],
-    )
-    built.add_api_route(
-        "/node-worker/sessions/{runtime_session_id}/approval",
-        node_worker_respond_approval,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/node-worker/clarification",
-        node_worker_respond_clarification,
-        methods=["POST"],
-    )
-    built.add_api_route(
-        "/node-worker/events", node_worker_events, methods=["GET"]
-    )
-    built.add_api_route(
-        "/node-worker/sessions/{runtime_session_id}/attachments",
-        node_worker_attach_file,
-        methods=["POST"],
-    )
-    built.add_api_websocket_route("/events", stream_events)
-    return built
-
-
-with _bootstrap_lock:
-    router = getattr(_package, "_yaoyao_group_router", None)
-    if router is None:
-        router = _build_router()
-        _package._yaoyao_group_router = router

+ 0 - 601
hermes-plugins/yaoyao/dashboard/group_protocol.py

@@ -1,601 +0,0 @@
-"""Shared protocol limits and input normalization for YaoYao Group Chat."""
-
-from __future__ import annotations
-
-import base64
-import binascii
-import re
-import unicodedata
-from pathlib import Path
-from typing import Any, Literal
-from uuid import UUID
-
-from pydantic import (
-    BaseModel,
-    ConfigDict,
-    Field,
-    StrictBool,
-    StrictInt,
-    field_validator,
-    model_validator,
-)
-
-
-PROTOCOL_VERSION = 12
-MAX_AGENTS_PER_ROOM = 8
-MAX_MESSAGE_BYTES = 64 * 1024
-MAX_TOOL_STATE_BYTES = 256 * 1024
-MAX_INTERACTION_PAYLOAD_BYTES = 64 * 1024
-MAX_MESSAGE_PAGE_SIZE = 100
-MAX_EVENT_BATCH_SIZE = 200
-MAX_EVENT_FRAME_BYTES = 2 * 1024 * 1024
-MAX_AGENT_DEPTH = 2
-DEFAULT_MAX_REPLY_ROUNDS = 3
-UNLIMITED_REPLY_ROUNDS = -1
-MAX_FINITE_REPLY_ROUNDS = 100
-MAX_AGENT_DISPLAY_NAME_LENGTH = 100
-MAX_ROOM_INSTRUCTIONS_LENGTH = 4_000
-MAX_ROOM_AVATAR_LENGTH = 512 * 1024
-MAX_ROOM_CONCURRENCY = 3
-MAX_PLUGIN_CONCURRENCY = 4
-INITIAL_CONTEXT_MESSAGE_LIMIT = 50
-CONTEXT_CHARACTER_BUDGET = 32_000
-REASONING_EFFORTS = frozenset({
-    "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"
-})
-ORCHESTRATION_MODES = frozenset({"free", "host"})
-BUILTIN_TEAM_AVATARS = frozenset({
-    "builtin:team-animal:fox",
-    "builtin:team-animal:whale",
-    "builtin:team-animal:owl",
-    "builtin:team-animal:rabbit",
-    "builtin:team-animal:bear",
-})
-_ROOM_AVATAR_PATTERN = re.compile(
-    r"^data:image/(png|jpeg|webp);base64,([A-Za-z0-9+/]+={0,2})$",
-    re.IGNORECASE,
-)
-
-# These literals address the room as a whole and must never become a member
-# display-name or alias target.  Keep the stable wire spelling for existing
-# clients while accepting the localized spelling shown by the iOS UI.
-ALL_MENTION_ALIASES = ("所有人", "all")
-_ALL_MENTION_ALIAS_KEYS = frozenset(
-    alias.casefold() for alias in ALL_MENTION_ALIASES
-)
-
-EVENT_TYPES = frozenset({
-    "room.created",
-    "room.updated",
-    "room.deleted",
-    "room.restored",
-    "agent.created",
-    "agent.updated",
-    "agent.deleted",
-    "agent.status",
-    "message.upsert",
-    "topic.updated",
-    "topic.archived",
-    "topic.restored",
-    "room.activity",
-    "interaction.requested",
-    "interaction.resolved",
-    "run.updated",
-})
-
-
-def limits_payload() -> dict[str, int]:
-    """Return the public, lower-camel protocol limits advertised to clients."""
-    return {
-        "maxAgentsPerRoom": MAX_AGENTS_PER_ROOM,
-        "maxMessageBytes": MAX_MESSAGE_BYTES,
-        "maxToolStateBytes": MAX_TOOL_STATE_BYTES,
-        "maxInteractionPayloadBytes": MAX_INTERACTION_PAYLOAD_BYTES,
-        "maxMessagePageSize": MAX_MESSAGE_PAGE_SIZE,
-        "maxEventBatchSize": MAX_EVENT_BATCH_SIZE,
-        "maxEventFrameBytes": MAX_EVENT_FRAME_BYTES,
-        "maxAgentDepth": MAX_AGENT_DEPTH,
-        "defaultMaxReplyRounds": DEFAULT_MAX_REPLY_ROUNDS,
-        "unlimitedReplyRoundsValue": UNLIMITED_REPLY_ROUNDS,
-        "maxAgentDisplayNameLength": MAX_AGENT_DISPLAY_NAME_LENGTH,
-        "maxRoomInstructionsLength": MAX_ROOM_INSTRUCTIONS_LENGTH,
-        "maxRoomAvatarLength": MAX_ROOM_AVATAR_LENGTH,
-        "maxRoomConcurrency": MAX_ROOM_CONCURRENCY,
-        "maxPluginConcurrency": MAX_PLUGIN_CONCURRENCY,
-    }
-
-
-def normalize_room_avatar(value: object) -> str:
-    """Validate a persisted built-in or custom team avatar."""
-    if not isinstance(value, str):
-        raise ValueError("avatar must be a built-in avatar, data image URL, or an empty string")
-    normalized = value.strip()
-    if not normalized:
-        return ""
-    if normalized in BUILTIN_TEAM_AVATARS:
-        return normalized
-    if len(normalized) > MAX_ROOM_AVATAR_LENGTH:
-        raise ValueError("avatar is too large")
-    match = _ROOM_AVATAR_PATTERN.fullmatch(normalized)
-    if match is None:
-        raise ValueError("avatar must be a known built-in avatar or a PNG, JPEG, or WebP data image URL")
-    try:
-        decoded = base64.b64decode(match.group(2), validate=True)
-    except (binascii.Error, ValueError) as error:
-        raise ValueError("avatar contains invalid base64 data") from error
-    if not decoded:
-        raise ValueError("avatar image is empty")
-    return normalized
-
-
-class GroupModel(BaseModel):
-    """Public request base with lower-camel aliases and forbidden extras."""
-
-    model_config = ConfigDict(populate_by_name=True, extra="forbid")
-
-
-class AgentSeed(GroupModel):
-    profile: str = Field(min_length=1, max_length=100)
-    node_id: str = Field(default="local", alias="nodeId", min_length=1, max_length=64)
-    node_label: str = Field(default="", alias="nodeLabel", max_length=100)
-    display_name: str | None = Field(
-        default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
-    )
-    description: str = Field(default="", max_length=500)
-    reply_without_mention: StrictBool = Field(
-        default=False, alias="replyWithoutMention"
-    )
-    is_host: StrictBool = Field(default=False, alias="isHost")
-    model: str | None = Field(default=None, max_length=4096)
-    provider: str | None = Field(default=None, max_length=4096)
-    reasoning_effort: str | None = Field(
-        default=None, alias="reasoningEffort", max_length=32
-    )
-    fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
-
-    @field_validator("model", "provider", "reasoning_effort")
-    @classmethod
-    def normalize_optional_configuration(cls, value: str | None) -> str | None:
-        return normalize_optional_agent_configuration(value)
-
-    @field_validator("reasoning_effort")
-    @classmethod
-    def validate_reasoning_effort(cls, value: str | None) -> str | None:
-        return validate_reasoning_override(value)
-
-    @model_validator(mode="after")
-    def validate_model_selection(self) -> "AgentSeed":
-        validate_model_provider_pair(self.model, self.provider)
-        return self
-
-    @field_validator("display_name")
-    @classmethod
-    def reject_reserved_display_name(cls, value: str | None) -> str | None:
-        return validate_optional_display_name(value)
-
-    @field_validator("node_id")
-    @classmethod
-    def validate_node_id(cls, value: str) -> str:
-        return normalize_node_id(value)
-
-    @field_validator("node_label")
-    @classmethod
-    def normalize_node_label(cls, value: str) -> str:
-        return " ".join(value.split())
-
-
-class CreateRoomRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    name: str = Field(min_length=1, max_length=100)
-    cwd: str = Field(default="", max_length=4096)
-    instructions: str = Field(default="", max_length=MAX_ROOM_INSTRUCTIONS_LENGTH)
-    avatar: str = Field(default="", max_length=MAX_ROOM_AVATAR_LENGTH)
-    max_reply_rounds: StrictInt = Field(
-        default=DEFAULT_MAX_REPLY_ROUNDS, alias="maxReplyRounds"
-    )
-    orchestration_mode: Literal["free", "host"] = Field(
-        default="free", alias="orchestrationMode"
-    )
-    agents: list[AgentSeed] = Field(min_length=1, max_length=MAX_AGENTS_PER_ROOM)
-
-    @field_validator("max_reply_rounds")
-    @classmethod
-    def validate_max_reply_rounds(cls, value: int) -> int:
-        return normalize_max_reply_rounds(value)
-
-    @field_validator("instructions")
-    @classmethod
-    def normalize_instructions(cls, value: str) -> str:
-        return normalize_room_instructions(value)
-
-    @field_validator("avatar")
-    @classmethod
-    def normalize_avatar(cls, value: str) -> str:
-        return normalize_room_avatar(value)
-
-    @model_validator(mode="after")
-    def validate_unique_host(self) -> "CreateRoomRequest":
-        if sum(agent.is_host for agent in self.agents) > 1:
-            raise ValueError("Room may contain only one administrator Agent")
-        return self
-
-
-class UpdateRoomRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    name: str | None = Field(default=None, min_length=1, max_length=100)
-    cwd: str | None = Field(default=None, max_length=4096)
-    instructions: str | None = Field(
-        default=None, max_length=MAX_ROOM_INSTRUCTIONS_LENGTH
-    )
-    avatar: str | None = Field(default=None, max_length=MAX_ROOM_AVATAR_LENGTH)
-    max_reply_rounds: StrictInt | None = Field(default=None, alias="maxReplyRounds")
-    orchestration_mode: Literal["free", "host"] | None = Field(
-        default=None, alias="orchestrationMode"
-    )
-
-    @field_validator(
-        "name", "cwd", "instructions", "avatar", "max_reply_rounds", "orchestration_mode",
-        mode="before"
-    )
-    @classmethod
-    def reject_explicit_null(cls, value: Any) -> Any:
-        if value is None:
-            raise ValueError("field must not be null")
-        return value
-
-    @model_validator(mode="after")
-    def require_change(self) -> "UpdateRoomRequest":
-        if not (
-            {"name", "cwd", "instructions", "avatar", "max_reply_rounds", "orchestration_mode"}
-            & self.model_fields_set
-        ):
-            raise ValueError(
-                "Room update requires name, cwd, instructions, avatar, maxReplyRounds, or orchestrationMode"
-            )
-        return self
-
-    @field_validator("instructions")
-    @classmethod
-    def normalize_instructions(cls, value: str | None) -> str | None:
-        return None if value is None else normalize_room_instructions(value)
-
-    @field_validator("avatar")
-    @classmethod
-    def normalize_avatar(cls, value: str | None) -> str | None:
-        return None if value is None else normalize_room_avatar(value)
-
-    @field_validator("max_reply_rounds")
-    @classmethod
-    def validate_max_reply_rounds(cls, value: int | None) -> int | None:
-        return None if value is None else normalize_max_reply_rounds(value)
-
-
-class UpdateTopicRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    title: str | None = Field(default=None, min_length=1, max_length=120)
-    pinned: StrictBool | None = None
-
-    @field_validator("title")
-    @classmethod
-    def normalize_title(cls, value: str | None) -> str | None:
-        if value is None:
-            return None
-        normalized = " ".join(value.split()).strip()
-        if not normalized:
-            raise ValueError("title must not be blank")
-        return normalized
-
-    @model_validator(mode="after")
-    def require_change(self) -> "UpdateTopicRequest":
-        if not ({"title", "pinned"} & self.model_fields_set):
-            raise ValueError("Topic update requires title or pinned")
-        return self
-
-
-class MarkTopicReadRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    through_seq: StrictInt = Field(alias="throughSeq", ge=0)
-
-
-class AddAgentRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    profile: str = Field(min_length=1, max_length=100)
-    node_id: str = Field(default="local", alias="nodeId", min_length=1, max_length=64)
-    node_label: str = Field(default="", alias="nodeLabel", max_length=100)
-    display_name: str | None = Field(
-        default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
-    )
-    description: str = Field(default="", max_length=500)
-    reply_without_mention: StrictBool = Field(
-        default=False, alias="replyWithoutMention"
-    )
-    is_host: StrictBool = Field(default=False, alias="isHost")
-    model: str | None = Field(default=None, max_length=4096)
-    provider: str | None = Field(default=None, max_length=4096)
-    reasoning_effort: str | None = Field(
-        default=None, alias="reasoningEffort", max_length=32
-    )
-    fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
-
-    @field_validator("model", "provider", "reasoning_effort")
-    @classmethod
-    def normalize_optional_configuration(cls, value: str | None) -> str | None:
-        return normalize_optional_agent_configuration(value)
-
-    @field_validator("reasoning_effort")
-    @classmethod
-    def validate_reasoning_effort(cls, value: str | None) -> str | None:
-        return validate_reasoning_override(value)
-
-    @model_validator(mode="after")
-    def validate_model_selection(self) -> "AddAgentRequest":
-        validate_model_provider_pair(self.model, self.provider)
-        return self
-
-    @field_validator("display_name")
-    @classmethod
-    def reject_reserved_display_name(cls, value: str | None) -> str | None:
-        return validate_optional_display_name(value)
-
-    @field_validator("node_id")
-    @classmethod
-    def validate_node_id(cls, value: str) -> str:
-        return normalize_node_id(value)
-
-    @field_validator("node_label")
-    @classmethod
-    def normalize_node_label(cls, value: str) -> str:
-        return " ".join(value.split())
-
-
-class UpdateAgentRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    display_name: str | None = Field(
-        default=None, alias="displayName", max_length=MAX_AGENT_DISPLAY_NAME_LENGTH
-    )
-    description: str | None = Field(default=None, max_length=500)
-    enabled: StrictBool | None = None
-    reply_without_mention: StrictBool | None = Field(
-        default=None, alias="replyWithoutMention"
-    )
-    is_host: StrictBool | None = Field(default=None, alias="isHost")
-    model: str | None = Field(default=None, max_length=4096)
-    provider: str | None = Field(default=None, max_length=4096)
-    reasoning_effort: str | None = Field(
-        default=None, alias="reasoningEffort", max_length=32
-    )
-    fast_mode: StrictBool | None = Field(default=None, alias="fastMode")
-
-    @field_validator(
-        "display_name", "description", "enabled", "reply_without_mention", "is_host",
-        mode="before"
-    )
-    @classmethod
-    def reject_explicit_null(cls, value: Any) -> Any:
-        if value is None:
-            raise ValueError("field must not be null")
-        return value
-
-    @field_validator("display_name")
-    @classmethod
-    def reject_reserved_display_name(cls, value: str | None) -> str | None:
-        return validate_optional_display_name(value)
-
-    @field_validator("model", "provider", "reasoning_effort")
-    @classmethod
-    def normalize_optional_configuration(cls, value: str | None) -> str | None:
-        return normalize_optional_agent_configuration(value)
-
-    @field_validator("reasoning_effort")
-    @classmethod
-    def validate_reasoning_effort(cls, value: str | None) -> str | None:
-        return validate_reasoning_override(value)
-
-    @model_validator(mode="after")
-    def require_change(self) -> "UpdateAgentRequest":
-        if not (
-            {
-                "display_name", "description", "enabled", "reply_without_mention",
-                "is_host",
-                "model", "provider", "reasoning_effort", "fast_mode",
-            }
-            & self.model_fields_set
-        ):
-            raise ValueError(
-                "Agent update requires a mutable agent field"
-            )
-        model_fields = {"model", "provider"} & self.model_fields_set
-        if model_fields and model_fields != {"model", "provider"}:
-            raise ValueError("model and provider must be updated together")
-        if model_fields:
-            validate_model_provider_pair(self.model, self.provider)
-        return self
-
-
-def normalize_optional_agent_configuration(value: str | None) -> str | None:
-    if value is None:
-        return None
-    normalized = value.strip()
-    if not normalized:
-        raise ValueError("configuration value must not be blank")
-    return normalized
-
-
-def normalize_node_id(value: str) -> str:
-    normalized = value.strip().lower()
-    if normalized == "local":
-        return normalized
-    try:
-        canonical = str(UUID(normalized))
-    except ValueError as error:
-        raise ValueError("nodeId must be local or a canonical UUID") from error
-    if canonical != normalized:
-        raise ValueError("nodeId must be local or a canonical UUID")
-    return canonical
-
-
-def validate_reasoning_override(value: str | None) -> str | None:
-    if value is not None and value not in REASONING_EFFORTS:
-        raise ValueError("reasoningEffort is invalid")
-    return value
-
-
-def validate_model_provider_pair(model: str | None, provider: str | None) -> None:
-    if (model is None) != (provider is None):
-        raise ValueError("model and provider must both be set or both be null")
-
-
-class RequestIDRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-
-
-class SendMessageRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    client_message_id: UUID = Field(alias="clientMessageId")
-    topic_id: UUID | None = Field(default=None, alias="topicId")
-    content: str
-    mention_agent_ids: list[UUID] = Field(
-        alias="mentionAgentIds", max_length=MAX_AGENTS_PER_ROOM
-    )
-
-    @field_validator("content")
-    @classmethod
-    def validate_content_bytes(cls, value: str) -> str:
-        try:
-            encoded = value.encode("utf-8")
-        except UnicodeEncodeError as error:
-            raise ValueError("content must be valid UTF-8") from error
-        if len(encoded) > MAX_MESSAGE_BYTES:
-            raise ValueError("content exceeds maximum size")
-        if not value.strip():
-            raise ValueError("content must not be blank")
-        return value
-
-
-class ApprovalRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    choice: Literal["once", "session", "always", "deny"]
-    permanent: StrictBool = False
-
-    @model_validator(mode="after")
-    def validate_choice(self) -> "ApprovalRequest":
-        if (self.choice == "always") != self.permanent:
-            raise ValueError("permanent must be true exactly for choice=always")
-        return self
-
-
-class ClarificationRequest(GroupModel):
-    request_id: UUID = Field(alias="requestId")
-    response: str
-
-    @field_validator("response")
-    @classmethod
-    def validate_response_bytes(cls, value: str) -> str:
-        try:
-            encoded = value.encode("utf-8")
-        except UnicodeEncodeError as error:
-            raise ValueError("response must be valid UTF-8") from error
-        if not value.strip():
-            raise ValueError("response must not be blank")
-        if len(encoded) > MAX_MESSAGE_BYTES:
-            raise ValueError("response exceeds maximum size")
-        return value
-
-
-def normalize_room_name(value: str) -> str:
-    """Return a trimmed room name within the protocol's character limit."""
-    normalized = value.strip()
-    if not 1 <= len(normalized) <= 100:
-        raise ValueError("Room name must contain 1 to 100 characters")
-    return normalized
-
-
-def normalize_room_instructions(value: str) -> str:
-    """Normalize optional multiline room rules without changing their structure."""
-    if not isinstance(value, str):
-        raise ValueError("Room instructions must be a string")
-    normalized = value.replace("\r\n", "\n").replace("\r", "\n").strip()
-    if len(normalized) > MAX_ROOM_INSTRUCTIONS_LENGTH:
-        raise ValueError(
-            f"Room instructions must contain at most {MAX_ROOM_INSTRUCTIONS_LENGTH} characters"
-        )
-    if any(
-        unicodedata.category(character) == "Cc" and character not in {"\n", "\t"}
-        for character in normalized
-    ):
-        raise ValueError("Room instructions contain unsupported control characters")
-    return normalized
-
-
-def normalize_display_name(value: str) -> tuple[str, str]:
-    """Return a trimmed display name and its case-insensitive uniqueness key."""
-    normalized = value.strip()
-    if not 1 <= len(normalized) <= MAX_AGENT_DISPLAY_NAME_LENGTH:
-        raise ValueError(
-            f"Display name must contain 1 to {MAX_AGENT_DISPLAY_NAME_LENGTH} characters"
-        )
-    uniqueness_key = normalized.casefold()
-    if uniqueness_key in _ALL_MENTION_ALIAS_KEYS:
-        raise ValueError("Display name is reserved")
-    return normalized, uniqueness_key
-
-
-def is_reserved_mention_alias(value: str) -> bool:
-    """Return whether a member-facing name would claim a room-wide Mention."""
-    return value.strip().casefold() in _ALL_MENTION_ALIAS_KEYS
-
-
-def validate_optional_display_name(value: str | None) -> str | None:
-    """Reject only non-empty reserved names; blank still means use the fallback."""
-    if value is not None and value.strip() and is_reserved_mention_alias(value):
-        raise ValueError("Display name is reserved")
-    return value
-
-
-def normalize_max_reply_rounds(value: object) -> int:
-    """Validate a finite reply-round ceiling or the explicit unlimited marker."""
-    if isinstance(value, bool) or not isinstance(value, int):
-        raise ValueError("maxReplyRounds must be an integer")
-    if value == UNLIMITED_REPLY_ROUNDS:
-        return value
-    if not 1 <= value <= MAX_FINITE_REPLY_ROUNDS:
-        raise ValueError(
-            f"maxReplyRounds must be -1 or 1 to {MAX_FINITE_REPLY_ROUNDS}"
-        )
-    return value
-
-
-def normalize_interaction_id(value: object) -> str:
-    """Canonicalize an opaque Gateway interaction identity for URL use."""
-    if not isinstance(value, str):
-        raise ValueError("interactionId must be a string")
-    normalized = value.strip()
-    if (
-        not normalized
-        or len(normalized) > 200
-        or any(unicodedata.category(character) == "Cc" for character in normalized)
-    ):
-        raise ValueError("interactionId is invalid")
-    return normalized
-
-
-def normalize_room_cwd(value: str) -> str:
-    """Validate and canonicalize an optional room working directory."""
-    if not isinstance(value, str):
-        raise ValueError("Room cwd must be a string")
-    if value and any(unicodedata.category(character) == "Cc" for character in value):
-        raise ValueError("Room cwd must not contain control characters")
-    normalized = value.strip()
-    if not normalized:
-        return ""
-    path = Path(normalized)
-    if not path.is_absolute():
-        raise ValueError("Room cwd must be an absolute path")
-    try:
-        resolved = path.resolve()
-        is_directory = resolved.is_dir()
-    except (OSError, RuntimeError) as error:
-        raise ValueError("Room cwd could not be resolved") from error
-    if not is_directory:
-        raise ValueError("Room cwd must exist and be a directory")
-    return str(resolved)

+ 0 - 488
hermes-plugins/yaoyao/dashboard/group_remote_gateway.py

@@ -1,488 +0,0 @@
-"""Route native group sessions to local or paired remote Hermes nodes."""
-
-from __future__ import annotations
-
-import json
-import base64
-import mimetypes
-import os
-from pathlib import Path
-import re
-import threading
-import time
-from typing import Any, Callable, Mapping
-from urllib.error import HTTPError, URLError
-from urllib.parse import quote, unquote, urlencode
-from urllib.request import build_opener, ProxyHandler, Request
-import uuid
-
-from .group_gateway import GroupGatewayAdapter, SessionIdentity
-from .group_node_registry import PairedNodeRegistry
-
-
-EventCallback = Callable[[str, str, dict[str, object]], None]
-_ATTACHMENT_PATTERN = re.compile(r"(!?\[[^\]]*\]\(<([^>]+)>\))")
-
-
-class RemoteGatewayError(RuntimeError):
-    pass
-
-
-class _DrainFacade:
-    def drain(self, timeout: float | None = None) -> bool:
-        _ = timeout
-        return True
-
-
-class RemoteNodeGatewayAdapter:
-    """Blocking Gateway-compatible client over the paired Web node proxy."""
-
-    def __init__(
-        self,
-        node: Mapping[str, object],
-        on_event: EventCallback,
-        *,
-        poll_interval: float = 0.2,
-        attachment_root: Path | None = None,
-    ) -> None:
-        server_url = node.get("serverUrl")
-        access_token = node.get("accessToken")
-        if not isinstance(server_url, str) or not isinstance(access_token, str):
-            raise RemoteGatewayError("Paired node route is invalid")
-        self.server_url = server_url.rstrip("/")
-        self.access_token = access_token
-        self._on_event = on_event
-        self._poll_interval = poll_interval
-        self._cursor = 0
-        self._condition = threading.Condition(threading.RLock())
-        self._active_runtimes: set[str] = set()
-        self._clarification_ids: set[str] = set()
-        self._closed = False
-        self._opener = build_opener(ProxyHandler({}))
-        hermes_home = Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")
-        self._attachment_root = (
-            attachment_root
-            or hermes_home / "plugins" / "yaoyao" / "data" / "group-uploads"
-        ).resolve()
-        self.transport = _DrainFacade()
-        self._poller = threading.Thread(
-            target=self._poll_events,
-            name="yaoyao-remote-node-events",
-            daemon=True,
-        )
-        self._poller.start()
-
-    def create_session(
-        self,
-        profile: str,
-        title: str,
-        cwd: str,
-        seed_messages: list[dict[str, Any]],
-        configuration: dict[str, Any] | None = None,
-    ) -> SessionIdentity:
-        if seed_messages:
-            raise RemoteGatewayError("Remote node seed messages are unsupported")
-        body: dict[str, object] = {
-            "profile": profile,
-            "title": title,
-            "cwd": cwd,
-        }
-        configuration = configuration or {}
-        for source, target in (
-            ("model", "model"),
-            ("provider", "provider"),
-            ("reasoning_effort", "reasoningEffort"),
-            ("fast", "fastMode"),
-        ):
-            if configuration.get(source) is not None:
-                body[target] = configuration[source]
-        return self._open(body)
-
-    def resume_session(self, profile: str, stored_id: str) -> SessionIdentity:
-        return self._open(
-            {
-                "profile": profile,
-                "title": "恢复跨节点群聊",
-                "cwd": "",
-                "storedSessionId": stored_id,
-            }
-        )
-
-    def submit_prompt(self, runtime_id: str, text: str) -> None:
-        text = self._mirror_attachments(runtime_id, text)
-        self._request(
-            "POST",
-            f"/sessions/{quote(runtime_id, safe='')}/prompt",
-            {"text": text},
-        )
-
-    def _mirror_attachments(self, runtime_id: str, text: str) -> str:
-        mirrored: dict[str, str] = {}
-
-        def replace(match: re.Match[str]) -> str:
-            raw_path = unquote(match.group(2))
-            candidate = Path(raw_path)
-            if not candidate.is_absolute():
-                return match.group(1)
-            try:
-                resolved = candidate.resolve(strict=True)
-                resolved.relative_to(self._attachment_root)
-            except (OSError, RuntimeError, ValueError):
-                return match.group(1)
-            if not resolved.is_file():
-                return match.group(1)
-            key = str(resolved)
-            if key not in mirrored:
-                if resolved.stat().st_size > 25 * 1024 * 1024:
-                    raise RemoteGatewayError("Group attachment exceeds 25 MiB")
-                self._upload_attachment(runtime_id, resolved)
-                mirrored[key] = resolved.name
-            return match.group(1).replace(
-                f"<{match.group(2)}>",
-                f"<attachment://{quote(mirrored[key])}>",
-            )
-
-        return _ATTACHMENT_PATTERN.sub(replace, text)
-
-    def _upload_attachment(self, runtime_id: str, path: Path) -> None:
-        content = path.read_bytes()
-        encoded_name = base64.urlsafe_b64encode(
-            path.name.encode("utf-8")
-        ).decode("ascii").rstrip("=")
-        mime_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
-        request = Request(
-            self.server_url
-            + "/api/plugins/yaoyao/v1/node-worker/sessions/"
-            + quote(runtime_id, safe="")
-            + "/attachments",
-            data=content,
-            method="POST",
-            headers={
-                "Accept": "application/json",
-                "Authorization": f"Bearer {self.access_token}",
-                "Content-Type": "application/octet-stream",
-                "X-File-Name-B64": encoded_name,
-                "X-Mime-Type": mime_type,
-            },
-        )
-        try:
-            with self._opener.open(request, timeout=120) as response:
-                raw = response.read(1024 * 1024 + 1)
-        except (HTTPError, URLError, TimeoutError, OSError) as error:
-            raise RemoteGatewayError("Remote attachment transfer failed") from error
-        if len(raw) > 1024 * 1024:
-            raise RemoteGatewayError("Remote attachment response is too large")
-        try:
-            result = json.loads(raw)
-        except (ValueError, UnicodeDecodeError) as error:
-            raise RemoteGatewayError("Remote attachment response is invalid") from error
-        if not isinstance(result, dict):
-            raise RemoteGatewayError("Remote attachment response is invalid")
-
-    def interrupt(self, runtime_id: str) -> None:
-        self._request(
-            "POST", f"/sessions/{quote(runtime_id, safe='')}/interrupt", {}
-        )
-
-    def close(self, runtime_id: str) -> bool:
-        response = self._request(
-            "DELETE", f"/sessions/{quote(runtime_id, safe='')}", None
-        )
-        with self._condition:
-            self._active_runtimes.discard(runtime_id)
-        return response.get("closed") is True
-
-    def respond_approval(self, runtime_id: str, choice: str) -> int:
-        response = self._request(
-            "POST",
-            f"/sessions/{quote(runtime_id, safe='')}/approval",
-            {"choice": choice},
-        )
-        value = response.get("resolved")
-        if isinstance(value, bool) or not isinstance(value, int):
-            raise RemoteGatewayError("Remote approval response is invalid")
-        return value
-
-    def respond_clarification(self, request_id: str, answer: str) -> str:
-        response = self._request(
-            "POST",
-            "/clarification",
-            {"requestId": request_id, "answer": answer},
-        )
-        status = response.get("status")
-        if status not in {"ok", "expired"}:
-            raise RemoteGatewayError("Remote clarification response is invalid")
-        with self._condition:
-            self._clarification_ids.discard(request_id)
-        return str(status)
-
-    def owns_clarification(self, request_id: str) -> bool:
-        with self._condition:
-            return request_id in self._clarification_ids
-
-    def shutdown(self) -> None:
-        with self._condition:
-            if self._closed:
-                return
-            self._closed = True
-            self._condition.notify_all()
-        if threading.current_thread() is not self._poller:
-            self._poller.join(timeout=5)
-
-    def _open(self, body: dict[str, object]) -> SessionIdentity:
-        response = self._request("POST", "/sessions", body)
-        stored = response.get("storedSessionId")
-        runtime = response.get("runtimeSessionId")
-        running = response.get("running", False)
-        if (
-            not isinstance(stored, str)
-            or not stored
-            or not isinstance(runtime, str)
-            or not runtime
-            or not isinstance(running, bool)
-        ):
-            raise RemoteGatewayError("Remote session identity is invalid")
-        with self._condition:
-            self._active_runtimes.add(runtime)
-            self._condition.notify_all()
-        return SessionIdentity(stored, runtime, running)
-
-    def _poll_events(self) -> None:
-        failures = 0
-        while True:
-            with self._condition:
-                while not self._active_runtimes and not self._closed:
-                    self._condition.wait()
-                if self._closed:
-                    return
-            try:
-                response = self._request(
-                    "GET",
-                    "/events?" + urlencode({"after": self._cursor, "limit": 256}),
-                    None,
-                )
-                latest = response.get("latestCursor")
-                items = response.get("items")
-                if isinstance(latest, bool) or not isinstance(latest, int):
-                    raise RemoteGatewayError("Remote event cursor is invalid")
-                if not isinstance(items, list):
-                    raise RemoteGatewayError("Remote event page is invalid")
-                if response.get("reset") is True:
-                    raise RemoteGatewayError("Remote event history was truncated")
-                for item in items:
-                    if not isinstance(item, dict):
-                        continue
-                    cursor = item.get("cursor")
-                    runtime_id = item.get("runtimeSessionId")
-                    event_type = item.get("type")
-                    payload = item.get("payload")
-                    if (
-                        isinstance(cursor, int)
-                        and not isinstance(cursor, bool)
-                        and isinstance(runtime_id, str)
-                        and isinstance(event_type, str)
-                        and isinstance(payload, dict)
-                    ):
-                        if event_type == "clarify.request":
-                            request_id = payload.get("request_id") or payload.get(
-                                "requestId"
-                            )
-                            if isinstance(request_id, str):
-                                with self._condition:
-                                    self._clarification_ids.add(request_id)
-                        self._on_event(runtime_id, event_type, payload)
-                        self._cursor = max(self._cursor, cursor)
-                self._cursor = max(self._cursor, latest)
-                failures = 0
-                time.sleep(self._poll_interval)
-            except Exception:
-                failures += 1
-                time.sleep(min(5.0, self._poll_interval * (2 ** min(failures, 5))))
-
-    def _request(
-        self,
-        method: str,
-        path: str,
-        body: dict[str, object] | None,
-    ) -> dict[str, object]:
-        if self._closed:
-            raise RemoteGatewayError("Remote node adapter is closed")
-        encoded = None if body is None else json.dumps(body).encode("utf-8")
-        request = Request(
-            self.server_url
-            + "/api/plugins/yaoyao/v1/node-worker"
-            + path,
-            data=encoded,
-            method=method,
-            headers={
-                "Accept": "application/json",
-                "Authorization": f"Bearer {self.access_token}",
-                **({"Content-Type": "application/json"} if encoded is not None else {}),
-            },
-        )
-        try:
-            with self._opener.open(request, timeout=35) as response:
-                raw = response.read(4 * 1024 * 1024 + 1)
-        except (HTTPError, URLError, TimeoutError, OSError) as error:
-            raise RemoteGatewayError("Remote Hermes node request failed") from error
-        if len(raw) > 4 * 1024 * 1024:
-            raise RemoteGatewayError("Remote Hermes node response is too large")
-        try:
-            value = json.loads(raw)
-        except (ValueError, UnicodeDecodeError) as error:
-            raise RemoteGatewayError("Remote Hermes node response is invalid") from error
-        if not isinstance(value, dict):
-            raise RemoteGatewayError("Remote Hermes node response is invalid")
-        return value
-
-
-class GroupGatewayRouter:
-    """One process-local Gateway plus lazily connected remote node adapters."""
-
-    def __init__(
-        self,
-        on_event: EventCallback,
-        *,
-        registry: PairedNodeRegistry | None = None,
-        local: GroupGatewayAdapter | None = None,
-        remote_factory: Callable[
-            [Mapping[str, object], EventCallback], RemoteNodeGatewayAdapter
-        ] | None = None,
-    ) -> None:
-        self._on_event = on_event
-        self._registry = registry
-        self._local = local or GroupGatewayAdapter(on_event=on_event)
-        self._remote_factory = remote_factory or (
-            lambda node, callback: RemoteNodeGatewayAdapter(node, callback)
-        )
-        self._lock = threading.RLock()
-        self._remotes: dict[str, RemoteNodeGatewayAdapter] = {}
-        self._runtime_routes: dict[str, tuple[str, str]] = {}
-        self.transport = self
-
-    def create_session(self, *args: object, **kwargs: object) -> SessionIdentity:
-        return self._local.create_session(*args, **kwargs)
-
-    def resume_session(self, *args: object, **kwargs: object) -> SessionIdentity:
-        return self._local.resume_session(*args, **kwargs)
-
-    def create_session_for_node(
-        self,
-        node_id: str,
-        profile: str,
-        title: str,
-        cwd: str,
-        seed_messages: list[dict[str, Any]],
-        configuration: dict[str, Any] | None = None,
-    ) -> SessionIdentity:
-        adapter = self._remote(node_id)
-        return self._adopt_remote(
-            node_id,
-            adapter.create_session(
-                profile, title, cwd, seed_messages, configuration
-            ),
-        )
-
-    def resume_session_for_node(
-        self, node_id: str, profile: str, stored_id: str
-    ) -> SessionIdentity:
-        adapter = self._remote(node_id)
-        return self._adopt_remote(
-            node_id, adapter.resume_session(profile, stored_id)
-        )
-
-    def submit_prompt(self, runtime_id: str, text: str) -> None:
-        adapter, remote_id = self._route(runtime_id)
-        adapter.submit_prompt(remote_id, text)
-
-    def interrupt(self, runtime_id: str) -> None:
-        adapter, remote_id = self._route(runtime_id)
-        adapter.interrupt(remote_id)
-
-    def close(self, runtime_id: str) -> bool:
-        adapter, remote_id = self._route(runtime_id)
-        result = adapter.close(remote_id)
-        with self._lock:
-            self._runtime_routes.pop(runtime_id, None)
-        return result
-
-    def respond_approval(self, runtime_id: str, choice: str) -> int:
-        adapter, remote_id = self._route(runtime_id)
-        return adapter.respond_approval(remote_id, choice)
-
-    def respond_clarification(self, request_id: str, answer: str) -> str:
-        with self._lock:
-            remotes = list(self._remotes.values())
-        for remote in remotes:
-            if remote.owns_clarification(request_id):
-                return remote.respond_clarification(request_id, answer)
-        return self._local.respond_clarification(request_id, answer)
-
-    def drain(self, timeout: float | None = None) -> bool:
-        local_transport = getattr(self._local, "transport", None)
-        drain = getattr(local_transport, "drain", None)
-        return True if not callable(drain) else bool(drain(timeout=timeout))
-
-    def shutdown(self) -> None:
-        with self._lock:
-            remotes = list(self._remotes.values())
-            self._remotes.clear()
-            self._runtime_routes.clear()
-        for remote in remotes:
-            remote.shutdown()
-        self._local.shutdown()
-
-    def _remote(self, node_id: str) -> RemoteNodeGatewayAdapter:
-        with self._lock:
-            existing = self._remotes.get(node_id)
-            if existing is not None:
-                return existing
-            if self._registry is None:
-                self._registry = PairedNodeRegistry.from_environment()
-            node = self._registry.get(node_id)
-
-            def callback(
-                remote_runtime_id: str,
-                event_type: str,
-                payload: dict[str, object],
-            ) -> None:
-                with self._lock:
-                    opaque = next(
-                        (
-                            key for key, route in self._runtime_routes.items()
-                            if route == (node_id, remote_runtime_id)
-                        ),
-                        None,
-                    )
-                if opaque is not None:
-                    self._on_event(opaque, event_type, payload)
-
-            created = self._remote_factory(node, callback)
-            self._remotes[node_id] = created
-            return created
-
-    def _adopt_remote(
-        self, node_id: str, identity: SessionIdentity
-    ) -> SessionIdentity:
-        opaque = f"remote:{uuid.uuid4()}"
-        with self._lock:
-            self._runtime_routes[opaque] = (node_id, identity.runtime_id)
-        return SessionIdentity(identity.stored_id, opaque, identity.running)
-
-    def _route(self, runtime_id: str):
-        with self._lock:
-            route = self._runtime_routes.get(runtime_id)
-            if route is None:
-                return self._local, runtime_id
-            node_id, remote_id = route
-            remote = self._remotes.get(node_id)
-        if remote is None:
-            raise RemoteGatewayError("Remote runtime route is unavailable")
-        return remote, remote_id
-
-
-__all__ = [
-    "GroupGatewayRouter",
-    "RemoteGatewayError",
-    "RemoteNodeGatewayAdapter",
-]

+ 0 - 7432
hermes-plugins/yaoyao/dashboard/group_store.py

@@ -1,7432 +0,0 @@
-"""Durable SQLite storage primitives for the YaoYao Group Chat plugin."""
-
-from __future__ import annotations
-
-import base64
-import binascii
-import hashlib
-import json
-import math
-import os
-import re
-import sqlite3
-import time
-import unicodedata
-import uuid
-from contextlib import contextmanager
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Callable, Iterator, Mapping
-
-from .data_paths import ensure_durable_data_root
-from .group_protocol import (
-    ALL_MENTION_ALIASES,
-    CONTEXT_CHARACTER_BUDGET,
-    DEFAULT_MAX_REPLY_ROUNDS,
-    INITIAL_CONTEXT_MESSAGE_LIMIT,
-    MAX_AGENTS_PER_ROOM,
-    MAX_EVENT_BATCH_SIZE,
-    MAX_FINITE_REPLY_ROUNDS,
-    MAX_INTERACTION_PAYLOAD_BYTES,
-    MAX_MESSAGE_BYTES,
-    MAX_MESSAGE_PAGE_SIZE,
-    MAX_PLUGIN_CONCURRENCY,
-    MAX_ROOM_CONCURRENCY,
-    MAX_ROOM_INSTRUCTIONS_LENGTH,
-    MAX_TOOL_STATE_BYTES,
-    ORCHESTRATION_MODES,
-    is_reserved_mention_alias,
-    normalize_display_name,
-    normalize_interaction_id,
-    normalize_max_reply_rounds,
-    normalize_room_cwd,
-    normalize_room_instructions,
-    normalize_room_avatar,
-    normalize_room_name,
-)
-
-
-SCHEMA_VERSION = 14
-_WAL_RETRY_DELAYS = (0.01, 0.02, 0.04, 0.08)
-EVENT_RETENTION_SECONDS = 30 * 24 * 60 * 60
-MIN_RETAINED_EVENTS = 100_000
-UNSET = object()
-
-RUN_TRANSITIONS = {
-    "queued": frozenset({"running", "interrupted", "failed"}),
-    "running": frozenset({"awaiting_input", "completed", "failed", "interrupted"}),
-    "awaiting_input": frozenset({"running", "failed", "interrupted"}),
-    "completed": frozenset(),
-    "failed": frozenset(),
-    "interrupted": frozenset(),
-}
-_MESSAGE_STATUSES = frozenset(
-    {"queued", "streaming", "completed", "failed", "interrupted"}
-)
-_AGENT_MESSAGE_STATUSES_BY_RUN = {
-    "queued": frozenset({"queued"}),
-    "running": frozenset({"queued", "streaming", "completed"}),
-    "awaiting_input": frozenset({"queued", "streaming"}),
-    "completed": frozenset(),
-    "failed": frozenset(),
-    "interrupted": frozenset(),
-}
-_AGENT_MESSAGE_TRANSITIONS = {
-    "queued": frozenset({"queued", "streaming", "completed"}),
-    "streaming": frozenset({"streaming", "completed"}),
-    "completed": frozenset(),
-    "failed": frozenset(),
-    "interrupted": frozenset(),
-}
-_MESSAGE_STATUSES_BY_RUN = {
-    "queued": frozenset({"queued"}),
-    "running": frozenset({"queued", "streaming", "completed"}),
-    "awaiting_input": frozenset({"queued", "streaming"}),
-    "completed": frozenset({"completed"}),
-    "failed": frozenset({"failed", "completed"}),
-    "interrupted": frozenset({"interrupted", "completed"}),
-}
-_INTERACTION_KINDS = frozenset({"approval", "clarification"})
-_INTERACTION_TERMINAL_STATUSES = frozenset({"resolved", "cancelled"})
-_CASCADE_PENDING_OPERATION = "internal.cascade.pending"
-_CASCADE_COMPLETED_OPERATION = "internal.cascade.completed"
-_CASCADE_DISCARDED_OPERATION = "internal.cascade.discarded"
-_CASCADE_OPERATIONS = frozenset(
-    {
-        _CASCADE_PENDING_OPERATION,
-        _CASCADE_COMPLETED_OPERATION,
-        _CASCADE_DISCARDED_OPERATION,
-    }
-)
-_CASCADE_PARSE_VERSION = 3
-_MAX_CASCADE_PAGE_SIZE = 32
-_MAX_CASCADE_PLAN_BYTES = 16 * 1024
-_HOST_FLOW_BARRIER_CONTENT = "internal.host-flow.parallel-barrier"
-_TOPIC_TITLE_LENGTH = 120
-_TOPIC_PREVIEW_LENGTH = 240
-_DEFAULT_SESSION_CONFIGURATION_JSON = (
-    '{"fast":null,"model":null,"provider":null,"reasoning_effort":null}'
-)
-
-_SCHEMA_STATEMENTS = (
-    """CREATE TABLE IF NOT EXISTS group_meta (
-        key TEXT PRIMARY KEY,
-        value TEXT NOT NULL
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_rooms (
-        id TEXT PRIMARY KEY,
-        name TEXT NOT NULL,
-        cwd TEXT NOT NULL DEFAULT '',
-        instructions TEXT NOT NULL DEFAULT '',
-        avatar_data_url TEXT NOT NULL DEFAULT '',
-        max_reply_rounds INTEGER NOT NULL DEFAULT 3,
-        orchestration_mode TEXT NOT NULL DEFAULT 'free',
-        created_at REAL NOT NULL,
-        updated_at REAL NOT NULL,
-        archived INTEGER NOT NULL DEFAULT 0
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_topics (
-        id TEXT PRIMARY KEY,
-        room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-        title TEXT NOT NULL,
-        last_read_message_seq INTEGER NOT NULL DEFAULT 0,
-        created_at REAL NOT NULL,
-        updated_at REAL NOT NULL,
-        archived INTEGER NOT NULL DEFAULT 0,
-        pinned INTEGER NOT NULL DEFAULT 0,
-        UNIQUE(room_id, id)
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_agents (
-        id TEXT PRIMARY KEY,
-        room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-        profile TEXT NOT NULL,
-        node_id TEXT NOT NULL DEFAULT 'local',
-        node_label TEXT NOT NULL DEFAULT '',
-        execution_profile TEXT,
-        display_name TEXT NOT NULL,
-        display_name_key TEXT NOT NULL,
-        description TEXT NOT NULL DEFAULT '',
-        stored_session_id TEXT,
-        last_context_message_seq INTEGER NOT NULL DEFAULT 0,
-        enabled INTEGER NOT NULL DEFAULT 1,
-        reply_without_mention INTEGER NOT NULL DEFAULT 0,
-        is_host INTEGER NOT NULL DEFAULT 0,
-        model_override TEXT,
-        provider_override TEXT,
-        reasoning_effort_override TEXT,
-        fast_mode_override INTEGER,
-        session_config_json TEXT,
-        created_at REAL NOT NULL,
-        updated_at REAL NOT NULL,
-        UNIQUE(room_id, profile),
-        UNIQUE(room_id, display_name_key)
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_agent_topic_state (
-        agent_id TEXT NOT NULL REFERENCES group_agents(id) ON DELETE CASCADE,
-        topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
-        last_context_message_seq INTEGER NOT NULL DEFAULT 0,
-        created_at REAL NOT NULL,
-        updated_at REAL NOT NULL,
-        PRIMARY KEY(agent_id, topic_id)
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_messages (
-        seq INTEGER PRIMARY KEY AUTOINCREMENT,
-        id TEXT NOT NULL UNIQUE,
-        room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-        topic_id TEXT NOT NULL,
-        sender_kind TEXT NOT NULL,
-        sender_id TEXT NOT NULL,
-        sender_name TEXT NOT NULL,
-        root_message_id TEXT NOT NULL,
-        reply_to_message_id TEXT,
-        client_message_id TEXT UNIQUE,
-        content TEXT NOT NULL DEFAULT '',
-        reasoning TEXT NOT NULL DEFAULT '',
-        tool_state_json TEXT NOT NULL DEFAULT '[]',
-        status TEXT NOT NULL,
-        error TEXT NOT NULL DEFAULT '',
-        visible INTEGER NOT NULL DEFAULT 1,
-        created_at REAL NOT NULL,
-        updated_at REAL NOT NULL,
-        FOREIGN KEY(room_id, topic_id)
-            REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_agent_runs (
-        id TEXT PRIMARY KEY,
-        room_id TEXT NOT NULL,
-        topic_id TEXT NOT NULL,
-        agent_id TEXT NOT NULL,
-        trigger_message_id TEXT NOT NULL,
-        response_message_id TEXT NOT NULL,
-        root_message_id TEXT NOT NULL,
-        depth INTEGER NOT NULL,
-        reply_mode TEXT NOT NULL DEFAULT 'mentioned',
-        required_reply INTEGER NOT NULL DEFAULT 0,
-        status TEXT NOT NULL,
-        runtime_session_id TEXT,
-        requested_model TEXT,
-        requested_provider TEXT,
-        requested_reasoning_effort TEXT,
-        requested_fast_mode INTEGER,
-        actual_model TEXT,
-        actual_provider TEXT,
-        actual_reasoning_effort TEXT,
-        actual_fast_mode INTEGER,
-        error TEXT NOT NULL DEFAULT '',
-        created_at REAL NOT NULL,
-        updated_at REAL NOT NULL,
-        FOREIGN KEY(room_id, topic_id)
-            REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_interactions (
-        id TEXT PRIMARY KEY,
-        room_id TEXT NOT NULL,
-        topic_id TEXT NOT NULL,
-        agent_id TEXT NOT NULL,
-        run_id TEXT NOT NULL,
-        kind TEXT NOT NULL,
-        payload_json TEXT NOT NULL,
-        status TEXT NOT NULL,
-        created_at REAL NOT NULL,
-        resolved_at REAL,
-        FOREIGN KEY(room_id, topic_id)
-            REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_events (
-        cursor INTEGER PRIMARY KEY AUTOINCREMENT,
-        epoch TEXT NOT NULL,
-        room_id TEXT,
-        event_type TEXT NOT NULL,
-        payload_json TEXT NOT NULL,
-        created_at REAL NOT NULL
-    )""",
-    """CREATE TABLE IF NOT EXISTS group_idempotency (
-        request_id TEXT PRIMARY KEY,
-        operation TEXT NOT NULL,
-        request_hash TEXT NOT NULL,
-        response_json TEXT NOT NULL,
-        created_at REAL NOT NULL
-    )""",
-    "CREATE INDEX IF NOT EXISTS idx_group_rooms_ordering ON group_rooms(archived, updated_at DESC, id DESC)",
-    "CREATE INDEX IF NOT EXISTS idx_group_topics_room_ordering ON group_topics(room_id, archived, pinned DESC, updated_at DESC, id DESC)",
-    "CREATE INDEX IF NOT EXISTS idx_group_messages_room_seq ON group_messages(room_id, seq)",
-    "CREATE INDEX IF NOT EXISTS idx_group_messages_topic_seq ON group_messages(topic_id, seq)",
-    "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_room ON group_agent_runs(room_id)",
-    "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_topic ON group_agent_runs(topic_id)",
-    "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_agent_status ON group_agent_runs(agent_id, status)",
-    "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_room_status ON group_agent_runs(room_id, status)",
-    "CREATE INDEX IF NOT EXISTS idx_group_agent_runs_status_order ON group_agent_runs(status, created_at, id)",
-    """CREATE UNIQUE INDEX IF NOT EXISTS idx_group_agents_room_host
-    ON group_agents(room_id) WHERE is_host = 1""",
-    """CREATE UNIQUE INDEX IF NOT EXISTS idx_group_agent_runs_active_runtime
-    ON group_agent_runs(runtime_session_id)
-    WHERE runtime_session_id IS NOT NULL
-      AND status IN ('running', 'awaiting_input')""",
-    "CREATE INDEX IF NOT EXISTS idx_group_interactions_room_agent ON group_interactions(room_id, agent_id)",
-    "CREATE INDEX IF NOT EXISTS idx_group_interactions_topic ON group_interactions(topic_id)",
-    "CREATE INDEX IF NOT EXISTS idx_group_interactions_run_status_kind ON group_interactions(run_id, status, kind)",
-    "CREATE INDEX IF NOT EXISTS idx_group_events_room_created_at ON group_events(room_id, created_at)",
-    "CREATE INDEX IF NOT EXISTS idx_group_events_created_at ON group_events(created_at)",
-    "CREATE INDEX IF NOT EXISTS idx_group_idempotency_operation ON group_idempotency(operation)",
-)
-
-_EXPECTED_TABLES = frozenset(
-    {
-        "group_meta",
-        "group_rooms",
-        "group_topics",
-        "group_agents",
-        "group_agent_topic_state",
-        "group_messages",
-        "group_agent_runs",
-        "group_interactions",
-        "group_events",
-        "group_idempotency",
-    }
-)
-
-_LEGACY_TABLES = _EXPECTED_TABLES - {"group_topics", "group_agent_topic_state"}
-
-
-class GroupStoreError(RuntimeError):
-    """Raised when the group-chat database is uninitialized or corrupt."""
-
-
-class GroupNotFoundError(GroupStoreError):
-    """Raised when a room or agent is absent, or unavailable because it is archived."""
-
-
-class GroupConflictError(GroupStoreError):
-    """Raised when a requested room-member invariant would be violated."""
-
-
-class IdempotencyConflict(GroupStoreError):
-    """Raised when a request ID is reused for a different operation or payload."""
-
-
-@dataclass(frozen=True)
-class CursorPage:
-    """A page of room summaries and the opaque cursor for its successor."""
-
-    items: list[dict[str, object]]
-    next_cursor: str | None
-
-
-class GroupStore:
-    """The versioned SQLite authority for public group-chat state."""
-
-    def __init__(
-        self,
-        path: Path,
-        *,
-        agent_name_resolver: Callable[[str], str] | None = None,
-    ):
-        self.path = Path(path)
-        self._agent_name_resolver = agent_name_resolver or (lambda _profile: "")
-
-    @classmethod
-    def from_environment(
-        cls, *, agent_name_resolver: Callable[[str], str] | None = None
-    ) -> "GroupStore":
-        hermes_home = Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")
-        return cls(
-            ensure_durable_data_root(hermes_home).data_root / "group-chat.db",
-            agent_name_resolver=agent_name_resolver,
-        )
-
-    def connect(self) -> sqlite3.Connection:
-        self.path.parent.mkdir(parents=True, exist_ok=True)
-        connection = sqlite3.connect(self.path, timeout=5, isolation_level=None)
-        connection.row_factory = sqlite3.Row
-        connection.execute("PRAGMA foreign_keys = ON")
-        connection.execute("PRAGMA busy_timeout = 5000")
-        return connection
-
-    @contextmanager
-    def connection(self) -> Iterator[sqlite3.Connection]:
-        """Yield a raw SQLite connection and always close it afterwards."""
-        connection = self.connect()
-        try:
-            yield connection
-        finally:
-            connection.close()
-
-    def initialize(self) -> None:
-        """Create or validate the versioned schema without changing its epoch."""
-        for attempt, delay in enumerate(_WAL_RETRY_DELAYS):
-            try:
-                self._initialize_once()
-                return
-            except sqlite3.OperationalError as error:
-                if (
-                    not self._is_busy_or_locked(error)
-                    or attempt == len(_WAL_RETRY_DELAYS) - 1
-                ):
-                    raise
-                time.sleep(delay)
-
-    def _initialize_once(self) -> None:
-        with self.connection() as connection:
-            connection.execute("PRAGMA journal_mode = WAL")
-            connection.execute("BEGIN IMMEDIATE")
-            try:
-                table_names = self._user_table_names(connection)
-                if not table_names:
-                    self._create_fresh_schema(connection)
-                else:
-                    self._validate_existing_schema(connection, table_names)
-                self._ensure_indexes(connection)
-                self._sync_legacy_fallback_agent_names(connection)
-            except Exception:
-                connection.execute("ROLLBACK")
-                raise
-            else:
-                connection.execute("COMMIT")
-
-    def _sync_legacy_fallback_agent_names(
-        self, connection: sqlite3.Connection
-    ) -> None:
-        """Adopt configured names for active legacy members without overriding edits."""
-        rows = connection.execute(
-            """SELECT group_agents.* FROM group_agents
-            JOIN group_rooms ON group_rooms.id = group_agents.room_id
-            WHERE group_agents.display_name = group_agents.profile
-              AND group_rooms.archived = 0
-            ORDER BY group_rooms.created_at ASC, group_rooms.id ASC,
-                     group_agents.created_at ASC, group_agents.id ASC"""
-        ).fetchall()
-        for row in rows:
-            configured = self._resolved_agent_name(row["profile"])
-            if not configured:
-                continue
-            try:
-                display_name, display_name_key = normalize_display_name(configured)
-            except ValueError:
-                continue
-            if (
-                display_name == row["display_name"]
-                and display_name_key == row["display_name_key"]
-            ):
-                continue
-            conflict = connection.execute(
-                """SELECT 1 FROM group_agents
-                WHERE room_id = ? AND display_name_key = ? AND id != ?
-                LIMIT 1""",
-                (row["room_id"], display_name_key, row["id"]),
-            ).fetchone()
-            if conflict is not None:
-                continue
-
-            now = self._now()
-            connection.execute(
-                """UPDATE group_agents
-                SET display_name = ?, display_name_key = ?, updated_at = ?
-                WHERE id = ? AND room_id = ?""",
-                (display_name, display_name_key, now, row["id"], row["room_id"]),
-            )
-            connection.execute(
-                "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
-                (now, row["room_id"]),
-            )
-            agent = self._agent_detail(connection, row["room_id"], row["id"])
-            self._append_event(
-                connection,
-                row["room_id"],
-                "agent.updated",
-                agent,
-                created_at=now,
-            )
-            self._append_room_updated_summary(
-                connection, row["room_id"], created_at=now
-            )
-
-    def schema_version(self) -> int:
-        value = self._metadata_value("schema_version")
-        return self._validated_schema_version(value)
-
-    def journal_epoch(self) -> str:
-        value = self._metadata_value("journal_epoch")
-        try:
-            canonical = str(uuid.UUID(value))
-        except (ValueError, AttributeError) as error:
-            raise GroupStoreError("GroupStore journal_epoch is corrupt") from error
-        if value != canonical:
-            raise GroupStoreError("GroupStore journal_epoch is corrupt")
-        return canonical
-
-    def _create_fresh_schema(self, connection: sqlite3.Connection) -> None:
-        for statement in _SCHEMA_STATEMENTS:
-            connection.execute(statement)
-        connection.execute(
-            "INSERT INTO group_meta(key, value) VALUES ('schema_version', ?)",
-            (str(SCHEMA_VERSION),),
-        )
-        connection.execute(
-            "INSERT INTO group_meta(key, value) VALUES ('journal_epoch', ?)",
-            (str(uuid.uuid4()),),
-        )
-
-    def _validate_existing_schema(
-        self, connection: sqlite3.Connection, table_names: set[str]
-    ) -> None:
-        if table_names not in {_EXPECTED_TABLES, _LEGACY_TABLES}:
-            raise GroupStoreError("GroupStore schema is partial or corrupt")
-        raw_version = self._metadata_value_from_connection(connection, "schema_version")
-        if raw_version == "1":
-            self._migrate_v1_to_v2(connection)
-            raw_version = "2"
-        if raw_version == "2":
-            self._migrate_v2_to_v3(connection)
-            raw_version = "3"
-        if raw_version == "3":
-            self._migrate_v3_to_v4(connection)
-            raw_version = "4"
-        if raw_version == "4":
-            self._repair_early_v4(connection)
-            self._migrate_v4_to_v5(connection)
-            raw_version = "5"
-        if raw_version == "5":
-            self._migrate_v5_to_v6(connection)
-            raw_version = "6"
-        if raw_version == "6":
-            self._migrate_v6_to_v7(connection)
-            raw_version = "7"
-        if raw_version == "7":
-            self._migrate_v7_to_v8(connection)
-            raw_version = "8"
-        if raw_version == "8":
-            self._migrate_v8_to_v9(connection)
-            raw_version = "9"
-        if raw_version == "9":
-            self._migrate_v9_to_v10(connection)
-            raw_version = "10"
-        if raw_version == "10":
-            self._migrate_v10_to_v11(connection)
-            raw_version = "11"
-        if raw_version == "11":
-            self._migrate_v11_to_v12(connection)
-            raw_version = "12"
-        if raw_version == "12":
-            self._migrate_v12_to_v13(connection)
-            raw_version = "13"
-        if raw_version == "13":
-            self._migrate_v13_to_v14(connection)
-        self._validated_schema_version(
-            self._metadata_value_from_connection(connection, "schema_version")
-        )
-        self._validated_epoch(
-            self._metadata_value_from_connection(connection, "journal_epoch")
-        )
-        self._validate_v8_columns(connection)
-        self._validate_v7_values(connection)
-
-    @staticmethod
-    def _migrate_v1_to_v2(connection: sqlite3.Connection) -> None:
-        connection.execute(
-            "ALTER TABLE group_rooms ADD COLUMN max_reply_rounds INTEGER NOT NULL DEFAULT 3"
-        )
-        connection.execute(
-            "ALTER TABLE group_agents ADD COLUMN reply_without_mention INTEGER NOT NULL DEFAULT 0"
-        )
-        connection.execute(
-            "ALTER TABLE group_messages ADD COLUMN visible INTEGER NOT NULL DEFAULT 1"
-        )
-        connection.execute(
-            "ALTER TABLE group_agent_runs ADD COLUMN reply_mode TEXT NOT NULL DEFAULT 'mentioned'"
-        )
-        connection.execute(
-            "UPDATE group_meta SET value = '2' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v2_to_v3(connection: sqlite3.Connection) -> None:
-        connection.execute("ALTER TABLE group_agents ADD COLUMN model_override TEXT")
-        connection.execute("ALTER TABLE group_agents ADD COLUMN provider_override TEXT")
-        connection.execute(
-            "ALTER TABLE group_agents ADD COLUMN reasoning_effort_override TEXT"
-        )
-        connection.execute(
-            "ALTER TABLE group_agents ADD COLUMN fast_mode_override INTEGER"
-        )
-        connection.execute(
-            "ALTER TABLE group_agents ADD COLUMN session_config_json TEXT"
-        )
-        connection.execute(
-            """UPDATE group_agents SET session_config_json = ?
-            WHERE stored_session_id IS NOT NULL""",
-            (_DEFAULT_SESSION_CONFIGURATION_JSON,),
-        )
-        connection.execute(
-            "UPDATE group_meta SET value = '3' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v3_to_v4(connection: sqlite3.Connection) -> None:
-        """Split legacy root chains into writable topics without touching rooms/Agents."""
-        orphan_run = connection.execute(
-            """SELECT run.id FROM group_agent_runs AS run
-            LEFT JOIN group_messages AS trigger ON trigger.id = run.trigger_message_id
-            LEFT JOIN group_messages AS response ON response.id = run.response_message_id
-            WHERE trigger.id IS NULL OR response.id IS NULL LIMIT 1"""
-        ).fetchone()
-        if orphan_run is not None:
-            raise GroupStoreError("GroupStore run messages are orphaned")
-        orphan_interaction = connection.execute(
-            """SELECT interaction.id FROM group_interactions AS interaction
-            LEFT JOIN group_agent_runs AS run ON run.id = interaction.run_id
-            WHERE run.id IS NULL LIMIT 1"""
-        ).fetchone()
-        if orphan_interaction is not None:
-            raise GroupStoreError("GroupStore interaction run is orphaned")
-        connection.execute(
-            """CREATE TABLE group_topics (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-                title TEXT NOT NULL,
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL,
-                UNIQUE(room_id, id)
-            )"""
-        )
-        roots = connection.execute(
-            """SELECT messages.room_id, messages.root_message_id,
-                      MIN(messages.created_at) AS created_at,
-                      COALESCE(
-                        MAX(CASE WHEN messages.visible = 1
-                                 THEN messages.updated_at END),
-                        MAX(messages.updated_at)
-                      ) AS updated_at,
-                      COALESCE(
-                        (SELECT human.content FROM group_messages AS human
-                         WHERE human.room_id = messages.room_id
-                           AND human.root_message_id = messages.root_message_id
-                           AND human.sender_kind = 'human'
-                         ORDER BY human.seq ASC LIMIT 1),
-                        (SELECT visible.content FROM group_messages AS visible
-                         WHERE visible.room_id = messages.room_id
-                           AND visible.root_message_id = messages.root_message_id
-                           AND visible.visible = 1
-                         ORDER BY visible.seq ASC LIMIT 1),
-                        '话题'
-                      ) AS title
-               FROM group_messages AS messages
-               GROUP BY messages.room_id, messages.root_message_id
-               ORDER BY MIN(messages.seq) ASC"""
-        ).fetchall()
-        for root in roots:
-            title = " ".join(str(root["title"]).split()).strip()
-            if not title:
-                title = "话题"
-            connection.execute(
-                """INSERT INTO group_topics
-                (id, room_id, title, created_at, updated_at)
-                VALUES (?, ?, ?, ?, ?)""",
-                (
-                    root["root_message_id"],
-                    root["room_id"],
-                    title[:_TOPIC_TITLE_LENGTH],
-                    root["created_at"],
-                    root["updated_at"],
-                ),
-            )
-
-        connection.execute(
-            """CREATE TABLE group_messages_v4 (
-                seq INTEGER PRIMARY KEY AUTOINCREMENT,
-                id TEXT NOT NULL UNIQUE,
-                room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-                topic_id TEXT NOT NULL,
-                sender_kind TEXT NOT NULL,
-                sender_id TEXT NOT NULL,
-                sender_name TEXT NOT NULL,
-                root_message_id TEXT NOT NULL,
-                reply_to_message_id TEXT,
-                client_message_id TEXT UNIQUE,
-                content TEXT NOT NULL DEFAULT '',
-                reasoning TEXT NOT NULL DEFAULT '',
-                tool_state_json TEXT NOT NULL DEFAULT '[]',
-                status TEXT NOT NULL,
-                error TEXT NOT NULL DEFAULT '',
-                visible INTEGER NOT NULL DEFAULT 1,
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL,
-                FOREIGN KEY(room_id, topic_id)
-                    REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_messages_v4
-            (seq, id, room_id, topic_id, sender_kind, sender_id, sender_name,
-             root_message_id, reply_to_message_id, client_message_id, content,
-             reasoning, tool_state_json, status, error, visible, created_at, updated_at)
-            SELECT seq, id, room_id, root_message_id, sender_kind, sender_id,
-                   sender_name, root_message_id, reply_to_message_id,
-                   client_message_id, content, reasoning, tool_state_json,
-                   status, error, visible, created_at, updated_at
-            FROM group_messages ORDER BY seq ASC"""
-        )
-        connection.execute(
-            """CREATE TABLE group_agent_runs_v4 (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL,
-                topic_id TEXT NOT NULL,
-                agent_id TEXT NOT NULL,
-                trigger_message_id TEXT NOT NULL,
-                response_message_id TEXT NOT NULL,
-                root_message_id TEXT NOT NULL,
-                depth INTEGER NOT NULL,
-                reply_mode TEXT NOT NULL DEFAULT 'mentioned',
-                status TEXT NOT NULL,
-                runtime_session_id TEXT,
-                error TEXT NOT NULL DEFAULT '',
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL,
-                FOREIGN KEY(room_id, topic_id)
-                    REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_agent_runs_v4
-            (id, room_id, topic_id, agent_id, trigger_message_id,
-             response_message_id, root_message_id, depth, reply_mode, status,
-             runtime_session_id, error, created_at, updated_at)
-            SELECT id, room_id, root_message_id, agent_id, trigger_message_id,
-                   response_message_id, root_message_id, depth, reply_mode,
-                   status, runtime_session_id, error, created_at, updated_at
-            FROM group_agent_runs"""
-        )
-        connection.execute(
-            """CREATE TABLE group_interactions_v4 (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL,
-                topic_id TEXT NOT NULL,
-                agent_id TEXT NOT NULL,
-                run_id TEXT NOT NULL,
-                kind TEXT NOT NULL,
-                payload_json TEXT NOT NULL,
-                status TEXT NOT NULL,
-                created_at REAL NOT NULL,
-                resolved_at REAL,
-                FOREIGN KEY(room_id, topic_id)
-                    REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_interactions_v4
-            (id, room_id, topic_id, agent_id, run_id, kind, payload_json,
-             status, created_at, resolved_at)
-            SELECT interaction.id, interaction.room_id, run.topic_id,
-                   interaction.agent_id, interaction.run_id, interaction.kind,
-                   interaction.payload_json, interaction.status,
-                   interaction.created_at, interaction.resolved_at
-            FROM group_interactions AS interaction
-            JOIN group_agent_runs_v4 AS run ON run.id = interaction.run_id"""
-        )
-        connection.execute("DROP TABLE group_interactions")
-        connection.execute("DROP TABLE group_agent_runs")
-        connection.execute("DROP TABLE group_messages")
-        connection.execute("ALTER TABLE group_messages_v4 RENAME TO group_messages")
-        connection.execute(
-            "ALTER TABLE group_agent_runs_v4 RENAME TO group_agent_runs"
-        )
-        connection.execute(
-            "ALTER TABLE group_interactions_v4 RENAME TO group_interactions"
-        )
-        connection.execute(
-            """CREATE TABLE group_agent_topic_state (
-                agent_id TEXT NOT NULL REFERENCES group_agents(id) ON DELETE CASCADE,
-                topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
-                last_context_message_seq INTEGER NOT NULL DEFAULT 0,
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL,
-                PRIMARY KEY(agent_id, topic_id)
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_agent_topic_state
-            (agent_id, topic_id, last_context_message_seq, created_at, updated_at)
-            SELECT agent.id, topic.id,
-                   COALESCE((
-                     SELECT MAX(message.seq) FROM group_messages AS message
-                     WHERE message.topic_id = topic.id
-                       AND message.seq <= agent.last_context_message_seq
-                   ), 0),
-                   topic.created_at,
-                   CASE WHEN agent.updated_at > topic.updated_at
-                        THEN agent.updated_at ELSE topic.updated_at END
-            FROM group_agents AS agent
-            JOIN group_topics AS topic ON topic.room_id = agent.room_id"""
-        )
-
-        def add_topic_ids(value: object) -> object:
-            if isinstance(value, list):
-                return [add_topic_ids(item) for item in value]
-            if not isinstance(value, dict):
-                return value
-            rewritten = {key: add_topic_ids(item) for key, item in value.items()}
-            identity = rewritten.get("id")
-            table: str | None = None
-            if isinstance(identity, str):
-                if "senderKind" in rewritten:
-                    table = "group_messages"
-                elif "triggerMessageId" in rewritten:
-                    table = "group_agent_runs"
-                elif "runId" in rewritten and "kind" in rewritten:
-                    table = "group_interactions"
-            if table is not None and "topicId" not in rewritten:
-                row = connection.execute(
-                    f"SELECT topic_id FROM {table} WHERE id = ?", (identity,)
-                ).fetchone()
-                if row is not None:
-                    rewritten["topicId"] = row["topic_id"]
-            return rewritten
-
-        for ledger in connection.execute(
-            "SELECT request_id, operation, response_json FROM group_idempotency"
-        ).fetchall():
-            try:
-                response = json.loads(ledger["response_json"])
-            except (TypeError, ValueError, json.JSONDecodeError) as error:
-                raise GroupStoreError("Stored idempotency response is corrupt") from error
-            rewritten_value = add_topic_ids(response)
-            if (
-                GroupStore._interaction_response_operation(ledger["operation"])
-                is not None
-                and isinstance(rewritten_value, dict)
-                and rewritten_value.get("state") == "failed"
-                and isinstance(rewritten_value.get("run"), dict)
-            ):
-                rewritten_value["run"].pop("topicId", None)
-            rewritten = GroupStore._canonical_json(rewritten_value)
-            if rewritten != ledger["response_json"]:
-                connection.execute(
-                    "UPDATE group_idempotency SET response_json = ? WHERE request_id = ?",
-                    (rewritten, ledger["request_id"]),
-                )
-        for event in connection.execute(
-            """SELECT cursor, payload_json FROM group_events
-            WHERE event_type IN ('message.upsert', 'run.updated',
-                                 'interaction.requested', 'interaction.resolved')"""
-        ).fetchall():
-            try:
-                payload = json.loads(event["payload_json"])
-            except (TypeError, ValueError, json.JSONDecodeError) as error:
-                raise GroupStoreError("Stored event is corrupt") from error
-            rewritten = GroupStore._canonical_json(add_topic_ids(payload))
-            if rewritten != event["payload_json"]:
-                connection.execute(
-                    "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
-                    (rewritten, event["cursor"]),
-                )
-        connection.execute(
-            "UPDATE group_meta SET value = '4' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _topic_foreign_key_kind(
-        connection: sqlite3.Connection, table: str
-    ) -> str:
-        foreign_keys = list(connection.execute(f"PRAGMA foreign_key_list({table})"))
-        grouped: dict[int, list[sqlite3.Row]] = {}
-        for foreign_key in foreign_keys:
-            grouped.setdefault(int(foreign_key["id"]), []).append(foreign_key)
-        for foreign_key_rows in grouped.values():
-            if foreign_key_rows[0]["table"] != "group_topics" or not all(
-                row["on_delete"] == "CASCADE" for row in foreign_key_rows
-            ):
-                continue
-            columns = [
-                (row["from"], row["to"])
-                for row in sorted(foreign_key_rows, key=lambda item: item["seq"])
-            ]
-            if columns == [("room_id", "room_id"), ("topic_id", "id")]:
-                return "final"
-            if columns == [("topic_id", "id")]:
-                return "early"
-        return "invalid"
-
-    @classmethod
-    def _repair_early_v4(cls, connection: sqlite3.Connection) -> None:
-        """Upgrade the unpublished single-topic-FK v4 draft in one transaction."""
-        tables = ("group_messages", "group_agent_runs", "group_interactions")
-        foreign_key_kinds = {
-            table: cls._topic_foreign_key_kind(connection, table) for table in tables
-        }
-        if all(kind == "final" for kind in foreign_key_kinds.values()):
-            return
-        if any(kind not in {"early", "final"} for kind in foreign_key_kinds.values()):
-            raise GroupStoreError("GroupStore early v4 topic ownership is corrupt")
-
-        invalid_queries = (
-            """SELECT message.id FROM group_messages AS message
-               LEFT JOIN group_topics AS topic ON topic.id = message.topic_id
-               WHERE topic.id IS NULL OR topic.room_id != message.room_id LIMIT 1""",
-            """SELECT run.id FROM group_agent_runs AS run
-               LEFT JOIN group_topics AS topic ON topic.id = run.topic_id
-               LEFT JOIN group_messages AS trigger
-                 ON trigger.id = run.trigger_message_id
-               LEFT JOIN group_messages AS response
-                 ON response.id = run.response_message_id
-               WHERE topic.id IS NULL OR topic.room_id != run.room_id
-                  OR trigger.id IS NULL OR response.id IS NULL
-                  OR trigger.room_id != run.room_id
-                  OR response.room_id != run.room_id
-                  OR trigger.topic_id != run.topic_id
-                  OR response.topic_id != run.topic_id
-               LIMIT 1""",
-            """SELECT interaction.id FROM group_interactions AS interaction
-               LEFT JOIN group_topics AS topic ON topic.id = interaction.topic_id
-               LEFT JOIN group_agent_runs AS run ON run.id = interaction.run_id
-               WHERE topic.id IS NULL OR topic.room_id != interaction.room_id
-                  OR run.id IS NULL OR run.room_id != interaction.room_id
-                  OR run.topic_id != interaction.topic_id
-               LIMIT 1""",
-        )
-        if any(connection.execute(query).fetchone() is not None for query in invalid_queries):
-            raise GroupStoreError("GroupStore early v4 ownership is corrupt")
-
-        counts = {
-            table: int(connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0])
-            for table in tables
-        }
-        connection.execute(
-            """CREATE TABLE group_messages_v4_repair (
-                seq INTEGER PRIMARY KEY AUTOINCREMENT,
-                id TEXT NOT NULL UNIQUE,
-                room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-                topic_id TEXT NOT NULL,
-                sender_kind TEXT NOT NULL,
-                sender_id TEXT NOT NULL,
-                sender_name TEXT NOT NULL,
-                root_message_id TEXT NOT NULL,
-                reply_to_message_id TEXT,
-                client_message_id TEXT UNIQUE,
-                content TEXT NOT NULL DEFAULT '',
-                reasoning TEXT NOT NULL DEFAULT '',
-                tool_state_json TEXT NOT NULL DEFAULT '[]',
-                status TEXT NOT NULL,
-                error TEXT NOT NULL DEFAULT '',
-                visible INTEGER NOT NULL DEFAULT 1,
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL,
-                FOREIGN KEY(room_id, topic_id)
-                    REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_messages_v4_repair
-            (seq, id, room_id, topic_id, sender_kind, sender_id, sender_name,
-             root_message_id, reply_to_message_id, client_message_id, content,
-             reasoning, tool_state_json, status, error, visible, created_at, updated_at)
-            SELECT seq, id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                   root_message_id, reply_to_message_id, client_message_id, content,
-                   reasoning, tool_state_json, status, error, visible,
-                   created_at, updated_at
-            FROM group_messages ORDER BY seq ASC"""
-        )
-        connection.execute(
-            """CREATE TABLE group_agent_runs_v4_repair (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL,
-                topic_id TEXT NOT NULL,
-                agent_id TEXT NOT NULL,
-                trigger_message_id TEXT NOT NULL,
-                response_message_id TEXT NOT NULL,
-                root_message_id TEXT NOT NULL,
-                depth INTEGER NOT NULL,
-                reply_mode TEXT NOT NULL DEFAULT 'mentioned',
-                status TEXT NOT NULL,
-                runtime_session_id TEXT,
-                error TEXT NOT NULL DEFAULT '',
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL,
-                FOREIGN KEY(room_id, topic_id)
-                    REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_agent_runs_v4_repair
-            (id, room_id, topic_id, agent_id, trigger_message_id,
-             response_message_id, root_message_id, depth, reply_mode, status,
-             runtime_session_id, error, created_at, updated_at)
-            SELECT id, room_id, topic_id, agent_id, trigger_message_id,
-                   response_message_id, root_message_id, depth, reply_mode,
-                   status, runtime_session_id, error, created_at, updated_at
-            FROM group_agent_runs"""
-        )
-        connection.execute(
-            """CREATE TABLE group_interactions_v4_repair (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL,
-                topic_id TEXT NOT NULL,
-                agent_id TEXT NOT NULL,
-                run_id TEXT NOT NULL,
-                kind TEXT NOT NULL,
-                payload_json TEXT NOT NULL,
-                status TEXT NOT NULL,
-                created_at REAL NOT NULL,
-                resolved_at REAL,
-                FOREIGN KEY(room_id, topic_id)
-                    REFERENCES group_topics(room_id, id) ON DELETE CASCADE
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_interactions_v4_repair
-            (id, room_id, topic_id, agent_id, run_id, kind, payload_json,
-             status, created_at, resolved_at)
-            SELECT id, room_id, topic_id, agent_id, run_id, kind, payload_json,
-                   status, created_at, resolved_at
-            FROM group_interactions"""
-        )
-        connection.execute("DROP TABLE group_interactions")
-        connection.execute("DROP TABLE group_agent_runs")
-        connection.execute("DROP TABLE group_messages")
-        connection.execute(
-            "ALTER TABLE group_messages_v4_repair RENAME TO group_messages"
-        )
-        connection.execute(
-            "ALTER TABLE group_agent_runs_v4_repair RENAME TO group_agent_runs"
-        )
-        connection.execute(
-            "ALTER TABLE group_interactions_v4_repair RENAME TO group_interactions"
-        )
-        repaired_counts = {
-            table: int(connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0])
-            for table in tables
-        }
-        if repaired_counts != counts:
-            raise GroupStoreError("GroupStore early v4 repair lost rows")
-
-        for event in connection.execute(
-            """SELECT cursor, payload_json FROM group_events
-            WHERE event_type = 'agent.status'"""
-        ).fetchall():
-            try:
-                payload = cls._load_json(event["payload_json"])
-            except (TypeError, ValueError, json.JSONDecodeError) as error:
-                raise GroupStoreError("Stored event is corrupt") from error
-            if not isinstance(payload, dict):
-                raise GroupStoreError("Stored event is corrupt")
-            payload.pop("topicId", None)
-            encoded = cls._canonical_json(payload)
-            if encoded != event["payload_json"]:
-                connection.execute(
-                    "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
-                    (encoded, event["cursor"]),
-                )
-        for ledger in connection.execute(
-            "SELECT request_id, operation, response_json FROM group_idempotency"
-        ).fetchall():
-            if cls._interaction_response_operation(ledger["operation"]) is None:
-                continue
-            try:
-                response = cls._load_json(ledger["response_json"])
-            except (TypeError, ValueError, json.JSONDecodeError) as error:
-                raise GroupStoreError("Stored interaction response is corrupt") from error
-            if not isinstance(response, dict):
-                raise GroupStoreError("Stored interaction response is corrupt")
-            run = response.get("run")
-            if response.get("state") != "failed" or not isinstance(run, dict):
-                continue
-            run.pop("topicId", None)
-            encoded = cls._canonical_json(response)
-            if encoded != ledger["response_json"]:
-                connection.execute(
-                    """UPDATE group_idempotency SET response_json = ?
-                    WHERE request_id = ?""",
-                    (encoded, ledger["request_id"]),
-                )
-        connection.execute(
-            """UPDATE group_topics AS topic
-            SET updated_at = COALESCE(
-                (SELECT MAX(message.updated_at) FROM group_messages AS message
-                 WHERE message.room_id = topic.room_id
-                   AND message.topic_id = topic.id AND message.visible = 1),
-                (SELECT MAX(message.updated_at) FROM group_messages AS message
-                 WHERE message.room_id = topic.room_id
-                   AND message.topic_id = topic.id),
-                topic.created_at
-            )"""
-        )
-
-    @classmethod
-    def _migrate_v4_to_v5(cls, connection: sqlite3.Connection) -> None:
-        """Assign one durable host per room and freeze required-reply run state."""
-        connection.execute(
-            "ALTER TABLE group_agents ADD COLUMN is_host INTEGER NOT NULL DEFAULT 0"
-        )
-        connection.execute(
-            """ALTER TABLE group_agent_runs
-            ADD COLUMN required_reply INTEGER NOT NULL DEFAULT 0"""
-        )
-        for room in connection.execute(
-            "SELECT id FROM group_rooms ORDER BY created_at ASC, id ASC"
-        ).fetchall():
-            host = connection.execute(
-                """SELECT id FROM group_agents WHERE room_id = ?
-                ORDER BY CASE
-                    WHEN enabled = 1 AND reply_without_mention = 1 THEN 0
-                    WHEN enabled = 1 THEN 1
-                    ELSE 2
-                END, created_at ASC, id ASC
-                LIMIT 1""",
-                (room["id"],),
-            ).fetchone()
-            if host is None:
-                raise GroupStoreError("GroupStore room has no administrator candidate")
-            connection.execute(
-                "UPDATE group_agents SET is_host = 1 WHERE id = ? AND room_id = ?",
-                (host["id"], room["id"]),
-            )
-
-        def add_host_flags(value: object) -> object:
-            if isinstance(value, list):
-                return [add_host_flags(item) for item in value]
-            if not isinstance(value, dict):
-                return value
-            rewritten = {key: add_host_flags(item) for key, item in value.items()}
-            identity = rewritten.get("id")
-            room_id = rewritten.get("roomId")
-            if (
-                isinstance(identity, str)
-                and isinstance(room_id, str)
-                and {"profile", "displayName", "replyWithoutMention"}
-                <= rewritten.keys()
-            ):
-                agent = connection.execute(
-                    "SELECT is_host FROM group_agents WHERE id = ? AND room_id = ?",
-                    (identity, room_id),
-                ).fetchone()
-                rewritten["isHost"] = bool(agent["is_host"]) if agent else False
-            return rewritten
-
-        for ledger in connection.execute(
-            "SELECT request_id, response_json FROM group_idempotency"
-        ).fetchall():
-            try:
-                response = cls._load_json(ledger["response_json"])
-            except (TypeError, ValueError, json.JSONDecodeError) as error:
-                raise GroupStoreError("Stored idempotency response is corrupt") from error
-            rewritten = cls._canonical_json(add_host_flags(response))
-            if rewritten != ledger["response_json"]:
-                connection.execute(
-                    """UPDATE group_idempotency SET response_json = ?
-                    WHERE request_id = ?""",
-                    (rewritten, ledger["request_id"]),
-                )
-        for event in connection.execute(
-            "SELECT cursor, payload_json FROM group_events"
-        ).fetchall():
-            try:
-                payload = cls._load_json(event["payload_json"])
-            except (TypeError, ValueError, json.JSONDecodeError) as error:
-                raise GroupStoreError("Stored event is corrupt") from error
-            rewritten = cls._canonical_json(add_host_flags(payload))
-            if rewritten != event["payload_json"]:
-                connection.execute(
-                    "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
-                    (rewritten, event["cursor"]),
-                )
-        connection.execute(
-            "UPDATE group_meta SET value = '5' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v5_to_v6(connection: sqlite3.Connection) -> None:
-        """Add immutable configured and terminal effective model attribution."""
-        for column in (
-            "requested_model",
-            "requested_provider",
-            "actual_model",
-            "actual_provider",
-        ):
-            connection.execute(
-                f"ALTER TABLE group_agent_runs ADD COLUMN {column} TEXT"
-            )
-        connection.execute(
-            "UPDATE group_meta SET value = '6' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v6_to_v7(connection: sqlite3.Connection) -> None:
-        """Add requested and effective reasoning/fast execution attribution."""
-        for definition in (
-            "requested_reasoning_effort TEXT",
-            "requested_fast_mode INTEGER",
-            "actual_reasoning_effort TEXT",
-            "actual_fast_mode INTEGER",
-        ):
-            connection.execute(
-                f"ALTER TABLE group_agent_runs ADD COLUMN {definition}"
-            )
-        connection.execute(
-            "UPDATE group_meta SET value = '7' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v7_to_v8(connection: sqlite3.Connection) -> None:
-        """Add one monotonic human-read watermark to every topic."""
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_topics)")
-        }
-        if "last_read_message_seq" not in columns:
-            connection.execute(
-                """ALTER TABLE group_topics ADD COLUMN
-                last_read_message_seq INTEGER NOT NULL DEFAULT 0"""
-            )
-        connection.execute(
-            """UPDATE group_topics
-            SET last_read_message_seq = COALESCE((
-                SELECT MAX(message.seq) FROM group_messages AS message
-                WHERE message.topic_id = group_topics.id
-                  AND message.visible = 1
-            ), 0)"""
-        )
-        connection.execute(
-            "UPDATE group_meta SET value = '8' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v8_to_v9(connection: sqlite3.Connection) -> None:
-        """Make topics independently archivable without removing history."""
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_topics)")
-        }
-        if "archived" not in columns:
-            connection.execute(
-                "ALTER TABLE group_topics ADD COLUMN archived INTEGER NOT NULL DEFAULT 0"
-            )
-        connection.execute("DROP INDEX IF EXISTS idx_group_topics_room_ordering")
-        connection.execute(
-            "CREATE INDEX IF NOT EXISTS idx_group_topics_room_ordering "
-            "ON group_topics(room_id, archived, updated_at DESC, id DESC)"
-        )
-        connection.execute(
-            "UPDATE group_meta SET value = '9' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v9_to_v10(connection: sqlite3.Connection) -> None:
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_topics)")
-        }
-        if "pinned" not in columns:
-            connection.execute(
-                "ALTER TABLE group_topics ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0"
-            )
-        connection.execute("DROP INDEX IF EXISTS idx_group_topics_room_ordering")
-        connection.execute(
-            "CREATE INDEX IF NOT EXISTS idx_group_topics_room_ordering "
-            "ON group_topics(room_id, archived, pinned DESC, updated_at DESC, id DESC)"
-        )
-        connection.execute(
-            "UPDATE group_meta SET value = '10' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v10_to_v11(connection: sqlite3.Connection) -> None:
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_rooms)")
-        }
-        if "orchestration_mode" not in columns:
-            connection.execute(
-                "ALTER TABLE group_rooms ADD COLUMN orchestration_mode "
-                "TEXT NOT NULL DEFAULT 'free'"
-            )
-        connection.execute(
-            "UPDATE group_meta SET value = '11' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v11_to_v12(connection: sqlite3.Connection) -> None:
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_rooms)")
-        }
-        if "instructions" not in columns:
-            connection.execute(
-                "ALTER TABLE group_rooms ADD COLUMN instructions "
-                "TEXT NOT NULL DEFAULT ''"
-            )
-        connection.execute(
-            "UPDATE group_meta SET value = '12' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v12_to_v13(connection: sqlite3.Connection) -> None:
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_agents)")
-        }
-        if "node_id" not in columns:
-            connection.execute(
-                "ALTER TABLE group_agents ADD COLUMN node_id "
-                "TEXT NOT NULL DEFAULT 'local'"
-            )
-        if "execution_profile" not in columns:
-            connection.execute(
-                "ALTER TABLE group_agents ADD COLUMN execution_profile TEXT"
-            )
-        if "node_label" not in columns:
-            connection.execute(
-                "ALTER TABLE group_agents ADD COLUMN node_label "
-                "TEXT NOT NULL DEFAULT ''"
-            )
-        connection.execute(
-            "UPDATE group_meta SET value = '13' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _migrate_v13_to_v14(connection: sqlite3.Connection) -> None:
-        columns = {
-            str(row["name"])
-            for row in connection.execute("PRAGMA table_info(group_rooms)")
-        }
-        if "avatar_data_url" not in columns:
-            connection.execute(
-                "ALTER TABLE group_rooms ADD COLUMN avatar_data_url "
-                "TEXT NOT NULL DEFAULT ''"
-            )
-        connection.execute(
-            "UPDATE group_meta SET value = '14' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _validate_v8_columns(connection: sqlite3.Connection) -> None:
-        expected_columns = {
-            "group_meta": {"key", "value"},
-            "group_rooms": {"id", "name", "cwd", "instructions", "avatar_data_url", "max_reply_rounds", "orchestration_mode", "created_at", "updated_at", "archived"},
-            "group_topics": {"id", "room_id", "title", "last_read_message_seq", "created_at", "updated_at", "archived", "pinned"},
-            "group_agents": {"id", "room_id", "profile", "node_id", "node_label", "execution_profile", "display_name", "display_name_key", "description", "stored_session_id", "last_context_message_seq", "enabled", "reply_without_mention", "is_host", "model_override", "provider_override", "reasoning_effort_override", "fast_mode_override", "session_config_json", "created_at", "updated_at"},
-            "group_agent_topic_state": {"agent_id", "topic_id", "last_context_message_seq", "created_at", "updated_at"},
-            "group_messages": {"seq", "id", "room_id", "topic_id", "sender_kind", "sender_id", "sender_name", "root_message_id", "reply_to_message_id", "client_message_id", "content", "reasoning", "tool_state_json", "status", "error", "visible", "created_at", "updated_at"},
-            "group_agent_runs": {"id", "room_id", "topic_id", "agent_id", "trigger_message_id", "response_message_id", "root_message_id", "depth", "reply_mode", "required_reply", "status", "runtime_session_id", "requested_model", "requested_provider", "requested_reasoning_effort", "requested_fast_mode", "actual_model", "actual_provider", "actual_reasoning_effort", "actual_fast_mode", "error", "created_at", "updated_at"},
-            "group_interactions": {"id", "room_id", "topic_id", "agent_id", "run_id", "kind", "payload_json", "status", "created_at", "resolved_at"},
-            "group_events": {"cursor", "epoch", "room_id", "event_type", "payload_json", "created_at"},
-            "group_idempotency": {"request_id", "operation", "request_hash", "response_json", "created_at"},
-        }
-        exact_specs = {
-            ("group_rooms", "max_reply_rounds"): ("INTEGER", 1, "3"),
-            ("group_rooms", "orchestration_mode"): ("TEXT", 1, "'free'"),
-            ("group_rooms", "instructions"): ("TEXT", 1, "''"),
-            ("group_rooms", "avatar_data_url"): ("TEXT", 1, "''"),
-            ("group_agents", "reply_without_mention"): ("INTEGER", 1, "0"),
-            ("group_agents", "is_host"): ("INTEGER", 1, "0"),
-            ("group_agents", "node_id"): ("TEXT", 1, "'local'"),
-            ("group_agents", "node_label"): ("TEXT", 1, "''"),
-            ("group_messages", "visible"): ("INTEGER", 1, "1"),
-            ("group_agent_runs", "reply_mode"): ("TEXT", 1, "'mentioned'"),
-            ("group_agent_runs", "required_reply"): ("INTEGER", 1, "0"),
-            ("group_messages", "topic_id"): ("TEXT", 1, None),
-            ("group_agent_runs", "topic_id"): ("TEXT", 1, None),
-            ("group_interactions", "topic_id"): ("TEXT", 1, None),
-            ("group_agent_topic_state", "last_context_message_seq"): ("INTEGER", 1, "0"),
-            ("group_topics", "last_read_message_seq"): ("INTEGER", 1, "0"),
-            ("group_topics", "archived"): ("INTEGER", 1, "0"),
-            ("group_topics", "pinned"): ("INTEGER", 1, "0"),
-        }
-        for table, required in expected_columns.items():
-            rows = list(connection.execute(f"PRAGMA table_info({table})"))
-            columns = {row["name"]: row for row in rows}
-            if set(columns) != required:
-                raise GroupStoreError("GroupStore schema is partial or corrupt")
-            for (target_table, name), spec in exact_specs.items():
-                if target_table != table:
-                    continue
-                row = columns[name]
-                actual = (str(row["type"]).upper(), int(row["notnull"]), row["dflt_value"])
-                if actual != spec:
-                    raise GroupStoreError("GroupStore schema is partial or corrupt")
-        for table in ("group_messages", "group_agent_runs", "group_interactions"):
-            if GroupStore._topic_foreign_key_kind(connection, table) != "final":
-                raise GroupStoreError("GroupStore schema is partial or corrupt")
-
-    @staticmethod
-    def _validate_v7_values(connection: sqlite3.Connection) -> None:
-        invalid_value_queries = (
-            f"""SELECT 1 FROM group_rooms
-                WHERE typeof(max_reply_rounds) != 'integer'
-                   OR (max_reply_rounds != -1 AND
-                       (max_reply_rounds < 1 OR
-                        max_reply_rounds > {MAX_FINITE_REPLY_ROUNDS}))
-                LIMIT 1""",
-            """SELECT 1 FROM group_rooms
-                WHERE typeof(orchestration_mode) != 'text'
-                   OR orchestration_mode NOT IN ('free', 'host')
-                LIMIT 1""",
-            f"""SELECT 1 FROM group_rooms
-                WHERE typeof(instructions) != 'text'
-                   OR length(instructions) > {MAX_ROOM_INSTRUCTIONS_LENGTH}
-                   OR instr(instructions, char(13)) > 0
-                LIMIT 1""",
-            """SELECT 1 FROM group_agents
-                WHERE typeof(reply_without_mention) != 'integer'
-                   OR reply_without_mention NOT IN (0, 1)
-                LIMIT 1""",
-            """SELECT 1 FROM group_agents
-                WHERE typeof(is_host) != 'integer' OR is_host NOT IN (0, 1)
-                LIMIT 1""",
-            """SELECT 1 FROM group_agents
-                WHERE typeof(node_id) != 'text'
-                   OR typeof(node_label) != 'text'
-                   OR length(node_label) > 100
-                   OR (node_id = 'local' AND execution_profile IS NOT NULL)
-                   OR (node_id != 'local' AND
-                       (execution_profile IS NULL
-                        OR profile != 'node:' || node_id || ':' || execution_profile))
-                LIMIT 1""",
-            """SELECT 1 FROM group_rooms AS room
-                LEFT JOIN group_agents AS agent ON agent.room_id = room.id
-                GROUP BY room.id
-                HAVING SUM(CASE WHEN agent.is_host = 1 THEN 1 ELSE 0 END) != 1
-                LIMIT 1""",
-            """SELECT 1 FROM group_agents AS host
-                WHERE host.is_host = 1 AND host.enabled = 0
-                  AND EXISTS (
-                    SELECT 1 FROM group_agents AS candidate
-                    WHERE candidate.room_id = host.room_id
-                      AND candidate.enabled = 1 AND candidate.id != host.id
-                  )
-                LIMIT 1""",
-            """SELECT 1 FROM group_agents
-                WHERE fast_mode_override IS NOT NULL
-                  AND (typeof(fast_mode_override) != 'integer'
-                       OR fast_mode_override NOT IN (0, 1))
-                LIMIT 1""",
-            """SELECT 1 FROM group_agents
-                WHERE reasoning_effort_override IS NOT NULL
-                  AND reasoning_effort_override NOT IN
-                    ('none','minimal','low','medium','high','xhigh','max','ultra')
-                LIMIT 1""",
-            """SELECT 1 FROM group_messages
-                WHERE typeof(visible) != 'integer'
-                   OR visible NOT IN (0, 1)
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_runs
-                WHERE typeof(reply_mode) != 'text'
-                   OR reply_mode NOT IN ('mentioned', 'automatic')
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_runs
-                WHERE typeof(required_reply) != 'integer'
-                   OR required_reply NOT IN (0, 1)
-                   OR (required_reply = 1 AND reply_mode != 'automatic')
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_runs
-                WHERE (requested_model IS NULL) != (requested_provider IS NULL)
-                   OR (actual_model IS NULL) != (actual_provider IS NULL)
-                   OR length(COALESCE(requested_model, '')) > 4096
-                   OR length(COALESCE(requested_provider, '')) > 4096
-                   OR length(COALESCE(actual_model, '')) > 4096
-                   OR length(COALESCE(actual_provider, '')) > 4096
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_runs
-                WHERE (requested_reasoning_effort IS NOT NULL
-                       AND requested_reasoning_effort NOT IN
-                         ('none','minimal','low','medium','high','xhigh','max','ultra'))
-                   OR (actual_reasoning_effort IS NOT NULL
-                       AND actual_reasoning_effort NOT IN
-                         ('none','minimal','low','medium','high','xhigh','max','ultra'))
-                   OR (requested_fast_mode IS NOT NULL
-                       AND (typeof(requested_fast_mode) != 'integer'
-                            OR requested_fast_mode NOT IN (0, 1)))
-                   OR (actual_fast_mode IS NOT NULL
-                       AND (typeof(actual_fast_mode) != 'integer'
-                            OR actual_fast_mode NOT IN (0, 1)))
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_runs AS run
-                JOIN group_messages AS response
-                  ON response.id = run.response_message_id
-                WHERE run.required_reply = 1 AND response.visible != 1
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_topic_state
-                WHERE typeof(last_context_message_seq) != 'integer'
-                   OR last_context_message_seq < 0
-                LIMIT 1""",
-            """SELECT 1 FROM group_topics AS topic
-                WHERE typeof(topic.last_read_message_seq) != 'integer'
-                   OR topic.last_read_message_seq < 0
-                   OR topic.last_read_message_seq > COALESCE((
-                       SELECT MAX(message.seq) FROM group_messages AS message
-                       WHERE message.topic_id = topic.id
-                         AND message.visible = 1
-                   ), 0)
-                LIMIT 1""",
-            """SELECT 1 FROM group_messages AS message
-                LEFT JOIN group_topics AS topic ON topic.id = message.topic_id
-                WHERE topic.id IS NULL OR topic.room_id != message.room_id
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_runs AS run
-                LEFT JOIN group_topics AS topic ON topic.id = run.topic_id
-                LEFT JOIN group_messages AS trigger ON trigger.id = run.trigger_message_id
-                LEFT JOIN group_messages AS response ON response.id = run.response_message_id
-                WHERE topic.id IS NULL OR topic.room_id != run.room_id
-                   OR trigger.id IS NULL OR response.id IS NULL
-                   OR trigger.topic_id != run.topic_id
-                   OR response.topic_id != run.topic_id
-                LIMIT 1""",
-            """SELECT 1 FROM group_interactions AS interaction
-                LEFT JOIN group_agent_runs AS run ON run.id = interaction.run_id
-                WHERE run.id IS NULL OR interaction.topic_id != run.topic_id
-                   OR interaction.room_id != run.room_id
-                LIMIT 1""",
-            """SELECT 1 FROM group_agent_topic_state AS state
-                LEFT JOIN group_agents AS agent ON agent.id = state.agent_id
-                LEFT JOIN group_topics AS topic ON topic.id = state.topic_id
-                WHERE agent.id IS NULL OR topic.id IS NULL
-                   OR agent.room_id != topic.room_id
-                LIMIT 1""",
-        )
-        for query in invalid_value_queries:
-            if connection.execute(query).fetchone() is not None:
-                raise GroupStoreError("GroupStore stored values are corrupt")
-        for table, column in (
-            ("group_topics", "id"),
-            ("group_topics", "room_id"),
-            ("group_messages", "topic_id"),
-            ("group_agent_runs", "topic_id"),
-            ("group_interactions", "topic_id"),
-        ):
-            for row in connection.execute(f"SELECT {column} AS value FROM {table}"):
-                try:
-                    canonical = str(uuid.UUID(row["value"]))
-                except (TypeError, ValueError, AttributeError) as error:
-                    raise GroupStoreError("GroupStore stored values are corrupt") from error
-                if row["value"] != canonical:
-                    raise GroupStoreError("GroupStore stored values are corrupt")
-
-    @staticmethod
-    def _ensure_indexes(connection: sqlite3.Connection) -> None:
-        """Repair v1 operational indexes without a schema-version migration."""
-
-        def canonical_index_sql(value: str) -> str:
-            without_guard = re.sub(
-                r"\bIF\s+NOT\s+EXISTS\b", "", value, flags=re.IGNORECASE
-            )
-            return " ".join(without_guard.split()).casefold()
-
-        indexes = {
-            "idx_group_rooms_ordering": (
-                [("archived", 0), ("updated_at", 1), ("id", 1)],
-                "group_rooms(archived, updated_at DESC, id DESC)",
-            ),
-            "idx_group_topics_room_ordering": (
-                [("room_id", 0), ("archived", 0), ("pinned", 1), ("updated_at", 1), ("id", 1)],
-                "group_topics(room_id, archived, pinned DESC, updated_at DESC, id DESC)",
-            ),
-            "idx_group_messages_room_seq": (
-                [("room_id", 0), ("seq", 0)],
-                "group_messages(room_id, seq)",
-            ),
-            "idx_group_messages_topic_seq": (
-                [("topic_id", 0), ("seq", 0)],
-                "group_messages(topic_id, seq)",
-            ),
-            "idx_group_agent_runs_room": (
-                [("room_id", 0)],
-                "group_agent_runs(room_id)",
-            ),
-            "idx_group_agent_runs_topic": (
-                [("topic_id", 0)],
-                "group_agent_runs(topic_id)",
-            ),
-            "idx_group_agent_runs_agent_status": (
-                [("agent_id", 0), ("status", 0)],
-                "group_agent_runs(agent_id, status)",
-            ),
-            "idx_group_agent_runs_room_status": (
-                [("room_id", 0), ("status", 0)],
-                "group_agent_runs(room_id, status)",
-            ),
-            "idx_group_agent_runs_status_order": (
-                [("status", 0), ("created_at", 0), ("id", 0)],
-                "group_agent_runs(status, created_at, id)",
-            ),
-            "idx_group_idempotency_operation": (
-                [("operation", 0)],
-                "group_idempotency(operation)",
-            ),
-            "idx_group_interactions_run_status_kind": (
-                [("run_id", 0), ("status", 0), ("kind", 0)],
-                "group_interactions(run_id, status, kind)",
-            ),
-            "idx_group_interactions_room_agent": (
-                [("room_id", 0), ("agent_id", 0)],
-                "group_interactions(room_id, agent_id)",
-            ),
-            "idx_group_interactions_topic": (
-                [("topic_id", 0)],
-                "group_interactions(topic_id)",
-            ),
-        }
-        for name, (expected, definition) in indexes.items():
-            columns = [
-                (row["name"], row["desc"])
-                for row in connection.execute(f"PRAGMA index_xinfo({name})")
-                if row["key"]
-            ]
-            stored = connection.execute(
-                """SELECT sql FROM sqlite_master
-                WHERE type = 'index' AND name = ?""",
-                (name,),
-            ).fetchone()
-            expected_sql = canonical_index_sql(f"CREATE INDEX {name} ON {definition}")
-            stored_sql = (
-                None
-                if stored is None or stored["sql"] is None
-                else canonical_index_sql(stored["sql"])
-            )
-            if columns == expected and stored_sql == expected_sql:
-                continue
-            connection.execute(f"DROP INDEX IF EXISTS {name}")
-            connection.execute(f"CREATE INDEX {name} ON {definition}")
-        host_definition = """CREATE UNIQUE INDEX idx_group_agents_room_host
-            ON group_agents(room_id) WHERE is_host = 1"""
-        stored = connection.execute(
-            """SELECT sql FROM sqlite_master
-            WHERE type = 'index' AND name = ?""",
-            ("idx_group_agents_room_host",),
-        ).fetchone()
-        expected_sql = canonical_index_sql(host_definition)
-        stored_sql = (
-            None
-            if stored is None or stored["sql"] is None
-            else canonical_index_sql(stored["sql"])
-        )
-        if stored_sql != expected_sql:
-            connection.execute("DROP INDEX IF EXISTS idx_group_agents_room_host")
-            try:
-                connection.execute(host_definition)
-            except sqlite3.IntegrityError as error:
-                raise GroupStoreError("Room administrators are not unique") from error
-        active_runtime_definition = """CREATE UNIQUE INDEX
-            idx_group_agent_runs_active_runtime
-            ON group_agent_runs(runtime_session_id)
-            WHERE runtime_session_id IS NOT NULL
-              AND status IN ('running', 'awaiting_input')"""
-        stored = connection.execute(
-            """SELECT sql FROM sqlite_master
-            WHERE type = 'index' AND name = ?""",
-            ("idx_group_agent_runs_active_runtime",),
-        ).fetchone()
-        expected_sql = canonical_index_sql(active_runtime_definition)
-        stored_sql = (
-            None
-            if stored is None or stored["sql"] is None
-            else canonical_index_sql(stored["sql"])
-        )
-        if stored_sql == expected_sql:
-            return
-        connection.execute("DROP INDEX IF EXISTS idx_group_agent_runs_active_runtime")
-        try:
-            connection.execute(active_runtime_definition)
-        except sqlite3.IntegrityError as error:
-            raise GroupStoreError("Active runtime sessions are not unique") from error
-
-    @staticmethod
-    def _user_table_names(connection: sqlite3.Connection) -> set[str]:
-        return {
-            row["name"]
-            for row in connection.execute(
-                """SELECT name FROM sqlite_master
-                WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
-            )
-        }
-
-    @staticmethod
-    def _is_busy_or_locked(error: sqlite3.OperationalError) -> bool:
-        message = str(error).lower()
-        return "locked" in message or "busy" in message
-
-    @staticmethod
-    def _validated_schema_version(value: str) -> int:
-        try:
-            version = int(value)
-        except (TypeError, ValueError) as error:
-            raise GroupStoreError("GroupStore schema_version is corrupt") from error
-        if value != str(SCHEMA_VERSION) or version != SCHEMA_VERSION:
-            raise GroupStoreError("Unsupported or corrupt GroupStore schema_version")
-        return version
-
-    def _metadata_value(self, key: str) -> str:
-        try:
-            with self.connection() as connection:
-                return self._metadata_value_from_connection(connection, key)
-        except sqlite3.OperationalError as error:
-            raise GroupStoreError("GroupStore is not initialized") from error
-
-    @staticmethod
-    def _metadata_value_from_connection(
-        connection: sqlite3.Connection, key: str
-    ) -> str:
-        row = connection.execute(
-            "SELECT value FROM group_meta WHERE key = ?", (key,)
-        ).fetchone()
-        if row is None:
-            raise GroupStoreError(f"GroupStore metadata is missing {key}")
-        return row["value"]
-
-    @staticmethod
-    def _validated_epoch(value: str) -> str:
-        try:
-            canonical = str(uuid.UUID(value))
-        except (ValueError, AttributeError) as error:
-            raise GroupStoreError("GroupStore journal_epoch is corrupt") from error
-        if value != canonical:
-            raise GroupStoreError("GroupStore journal_epoch is corrupt")
-        return canonical
-
-    @contextmanager
-    def read_transaction(self) -> Iterator[sqlite3.Connection]:
-        """Yield one consistent read snapshot and always close its connection."""
-        with self.connection() as connection:
-            connection.execute("BEGIN")
-            try:
-                yield connection
-            except Exception:
-                connection.execute("ROLLBACK")
-                raise
-            else:
-                connection.execute("COMMIT")
-
-    @contextmanager
-    def write_transaction(self) -> Iterator[sqlite3.Connection]:
-        """Yield one immediately-locked write transaction and always close it."""
-        with self.connection() as connection:
-            connection.execute("BEGIN IMMEDIATE")
-            try:
-                yield connection
-            except Exception:
-                connection.execute("ROLLBACK")
-                raise
-            else:
-                connection.execute("COMMIT")
-
-    def execute_idempotent(
-        self,
-        operation: str,
-        request_id: str,
-        payload: Mapping[str, object],
-        action: Callable[[sqlite3.Connection], dict[str, object]],
-    ) -> dict[str, object]:
-        """Execute a mutation exactly once for the canonical request and payload."""
-        canonical_request_id = self._canonical_uuid(request_id, "requestId")
-        request_hash = hashlib.sha256(
-            self._canonical_json(payload).encode()
-        ).hexdigest()
-        try:
-            with self.write_transaction() as connection:
-                existing = connection.execute(
-                    """SELECT operation, request_hash, response_json FROM group_idempotency
-                    WHERE request_id = ?""",
-                    (canonical_request_id,),
-                ).fetchone()
-                if existing is not None:
-                    if (
-                        existing["operation"] != operation
-                        or existing["request_hash"] != request_hash
-                    ):
-                        raise IdempotencyConflict(
-                            "requestId was already used for a different request"
-                        )
-                    stored_response = existing["response_json"]
-                    try:
-                        response = self._load_json(stored_response)
-                    except (ValueError, json.JSONDecodeError, TypeError) as error:
-                        raise GroupStoreError(
-                            "Stored idempotency response is corrupt"
-                        ) from error
-                    if (
-                        not isinstance(response, dict)
-                        or self._canonical_json(response) != stored_response
-                    ):
-                        raise GroupStoreError("Stored idempotency response is corrupt")
-                    return response
-                response = action(connection)
-                response_json = self._canonical_json(response)
-                connection.execute(
-                    """INSERT INTO group_idempotency
-                    (request_id, operation, request_hash, response_json, created_at)
-                    VALUES (?, ?, ?, ?, ?)""",
-                    (
-                        canonical_request_id,
-                        operation,
-                        request_hash,
-                        response_json,
-                        self._now(),
-                    ),
-                )
-                return response
-        except sqlite3.IntegrityError as error:
-            raise self._integrity_conflict(error) from error
-
-    def create_room(self, command: Mapping[str, object]) -> dict[str, object]:
-        command = self._command(
-            command,
-            {
-                "requestId",
-                "name",
-                "cwd",
-                "instructions",
-                "avatar",
-                "maxReplyRounds",
-                "orchestrationMode",
-                "agents",
-            },
-        )
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            name = normalize_room_name(self._string(command, "name"))
-            cwd = normalize_room_cwd(self._string(command, "cwd"))
-            instructions = normalize_room_instructions(
-                command.get("instructions", "")
-            )
-            avatar = normalize_room_avatar(command.get("avatar", ""))
-            max_reply_rounds = normalize_max_reply_rounds(
-                command.get("maxReplyRounds", DEFAULT_MAX_REPLY_ROUNDS)
-            )
-            orchestration_mode = self._orchestration_mode(
-                command.get("orchestrationMode", "free")
-            )
-            agents = self._new_agents(command.get("agents"))
-            now = self._now()
-            room_id = str(uuid.uuid4())
-            connection.execute(
-                """INSERT INTO group_rooms
-                (id, name, cwd, instructions, avatar_data_url, max_reply_rounds, orchestration_mode,
-                 created_at, updated_at, archived)
-                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0)""",
-                (
-                    room_id, name, cwd, instructions, avatar, max_reply_rounds,
-                    orchestration_mode, now, now,
-                ),
-            )
-            for agent in agents:
-                self._insert_agent(connection, room_id, agent, now)
-            room = self._room_detail(connection, room_id, include_archived=True)
-            self._append_event(
-                connection, room_id, "room.created", room, created_at=now
-            )
-            return room
-
-        return self.execute_idempotent("room.created", request_id, command, action)
-
-    def get_room(
-        self, room_id: str, *, include_archived: bool = False
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        with self.read_transaction() as connection:
-            return self._room_detail(
-                connection, canonical_room_id, include_archived=include_archived
-            )
-
-    def room_snapshot(self, room_id: str) -> dict[str, object]:
-        """Read all state needed to recover one active room in one snapshot."""
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        with self.read_transaction() as connection:
-            result = self._room_detail(
-                connection, canonical_room_id, include_archived=False
-            )
-            run_rows = connection.execute(
-                """SELECT * FROM group_agent_runs
-                WHERE room_id = ? AND status IN ('queued', 'running', 'awaiting_input')
-                ORDER BY created_at ASC, id ASC""",
-                (canonical_room_id,),
-            ).fetchall()
-            interaction_rows = connection.execute(
-                """SELECT * FROM group_interactions
-                WHERE room_id = ? AND status = 'pending'
-                ORDER BY created_at ASC, id ASC""",
-                (canonical_room_id,),
-            ).fetchall()
-            cursor_row = connection.execute(
-                "SELECT COALESCE(MAX(cursor), 0) AS cursor FROM group_events"
-            ).fetchone()
-
-            status_priority = {
-                "queued": 1,
-                "running": 2,
-                "awaiting_input": 3,
-            }
-            statuses: dict[str, str] = {}
-            for run in run_rows:
-                previous = statuses.get(run["agent_id"], "idle")
-                if status_priority[run["status"]] > status_priority.get(previous, 0):
-                    statuses[run["agent_id"]] = run["status"]
-            for agent in result["agents"]:
-                agent["status"] = statuses.get(agent["id"], "idle")
-
-            result["runs"] = [self._run_wire(row) for row in run_rows]
-            result["pendingInteractions"] = [
-                self._interaction_wire(row) for row in interaction_rows
-            ]
-            result["latestCursor"] = int(cursor_row["cursor"])
-            return result
-
-    def list_rooms(
-        self, *, limit: int, cursor: str | None, archived: bool = False
-    ) -> CursorPage:
-        if (
-            not isinstance(limit, int)
-            or isinstance(limit, bool)
-            or not 1 <= limit <= 100
-        ):
-            raise ValueError("limit must be an integer from 1 to 100")
-        cursor_values = self._decode_cursor(cursor) if cursor is not None else None
-        query = """SELECT id, name, cwd, instructions, avatar_data_url, max_reply_rounds, orchestration_mode,
-            created_at, updated_at, archived,
-            (SELECT COUNT(*) FROM group_agents WHERE room_id = group_rooms.id) AS agent_count,
-            (SELECT COUNT(*) FROM group_topics WHERE room_id = group_rooms.id) AS topic_count
-            FROM group_rooms WHERE archived = ?"""
-        params: list[object] = [int(archived)]
-        if cursor_values is not None:
-            query += " AND ((updated_at < ?) OR (updated_at = ? AND id < ?))"
-            params.extend((cursor_values[0], cursor_values[0], cursor_values[1]))
-        query += " ORDER BY updated_at DESC, id DESC LIMIT ?"
-        params.append(limit + 1)
-        with self.connection() as connection:
-            rows = connection.execute(query, params).fetchall()
-            items = []
-            for row in rows[:limit]:
-                summary = self._room_summary(
-                    row, self._room_avatar_members(connection, str(row["id"]))
-                )
-                activity = self._room_activity_from_connection(
-                    connection, str(row["id"])
-                )
-                summary.update({
-                    "activeRunCount": activity["activeRunCount"],
-                    "unreadCount": activity["unreadCount"],
-                    "lastMessage": activity["lastMessage"],
-                })
-                items.append(summary)
-        has_more = len(rows) > limit
-        next_cursor = None
-        if has_more and items:
-            last = rows[limit - 1]
-            next_cursor = self._encode_cursor(last["updated_at"], last["id"])
-        return CursorPage(items=items, next_cursor=next_cursor)
-
-    def list_topics(
-        self, room_id: str, *, limit: int, cursor: str | None,
-        archived: bool = False,
-    ) -> CursorPage:
-        """Return one room's topics in stable most-recently-active order."""
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        if (
-            not isinstance(limit, int)
-            or isinstance(limit, bool)
-            or not 1 <= limit <= 100
-        ):
-            raise ValueError("limit must be an integer from 1 to 100")
-        cursor_values = (
-            self._decode_topic_cursor(cursor, canonical_room_id)
-            if cursor is not None
-            else None
-        )
-        query = """SELECT topic.*,
-            (SELECT COUNT(*) FROM group_messages AS counted
-             WHERE counted.topic_id = topic.id AND counted.visible = 1)
-                AS message_count,
-            COALESCE((SELECT CASE WHEN TRIM(latest.content) != ''
-                                  THEN latest.content ELSE latest.error END
-             FROM group_messages AS latest
-             WHERE latest.topic_id = topic.id AND latest.visible = 1
-               AND (TRIM(latest.content) != '' OR TRIM(latest.error) != '')
-             ORDER BY latest.seq DESC LIMIT 1), '') AS preview,
-            (SELECT COUNT(*) FROM group_messages AS unread
-             WHERE unread.topic_id = topic.id AND unread.visible = 1
-               AND unread.sender_kind = 'agent'
-               AND (TRIM(unread.content) != '' OR TRIM(unread.error) != '')
-               AND unread.seq > topic.last_read_message_seq) AS unread_count,
-            COALESCE((SELECT MAX(visible_message.seq)
-             FROM group_messages AS visible_message
-             WHERE visible_message.topic_id = topic.id
-               AND visible_message.visible = 1), 0) AS latest_message_seq
-            FROM group_topics AS topic
-            WHERE topic.room_id = ? AND topic.archived = ?"""
-        params: list[object] = [canonical_room_id, int(archived)]
-        if cursor_values is not None:
-            query += " AND ((topic.updated_at < ?) OR (topic.updated_at = ? AND topic.id < ?))"
-            params.extend((cursor_values[0], cursor_values[0], cursor_values[1]))
-        query += " ORDER BY topic.pinned DESC, topic.updated_at DESC, topic.id DESC LIMIT ?"
-        params.append(limit + 1)
-        with self.read_transaction() as connection:
-            self._room_detail(connection, canonical_room_id, include_archived=True)
-            rows = connection.execute(query, params).fetchall()
-        has_more = len(rows) > limit
-        items = [self._topic_summary(row) for row in rows[:limit]]
-        next_cursor = None
-        if has_more and items:
-            last = rows[limit - 1]
-            next_cursor = self._encode_topic_cursor(
-                canonical_room_id, last["updated_at"], last["id"]
-            )
-        return CursorPage(items=items, next_cursor=next_cursor)
-
-    def list_global_topics(
-        self, *, limit: int, cursor: str | None
-    ) -> CursorPage:
-        """Return active topics across active rooms in stable professional order."""
-        if (
-            not isinstance(limit, int)
-            or isinstance(limit, bool)
-            or not 1 <= limit <= 100
-        ):
-            raise ValueError("limit must be an integer from 1 to 100")
-        cursor_values = (
-            self._decode_global_topic_cursor(cursor)
-            if cursor is not None
-            else None
-        )
-        query = """SELECT topic.*,
-            (SELECT COUNT(*) FROM group_messages AS counted
-             WHERE counted.topic_id = topic.id AND counted.visible = 1)
-                AS message_count,
-            COALESCE((SELECT CASE WHEN TRIM(latest.content) != ''
-                                  THEN latest.content ELSE latest.error END
-             FROM group_messages AS latest
-             WHERE latest.topic_id = topic.id AND latest.visible = 1
-               AND (TRIM(latest.content) != '' OR TRIM(latest.error) != '')
-             ORDER BY latest.seq DESC LIMIT 1), '') AS preview,
-            (SELECT COUNT(*) FROM group_messages AS unread
-             WHERE unread.topic_id = topic.id AND unread.visible = 1
-               AND unread.sender_kind = 'agent'
-               AND (TRIM(unread.content) != '' OR TRIM(unread.error) != '')
-               AND unread.seq > topic.last_read_message_seq) AS unread_count,
-            COALESCE((SELECT MAX(visible_message.seq)
-             FROM group_messages AS visible_message
-             WHERE visible_message.topic_id = topic.id
-               AND visible_message.visible = 1), 0) AS latest_message_seq
-            FROM group_topics AS topic
-            INNER JOIN group_rooms AS room ON room.id = topic.room_id
-            WHERE topic.archived = 0 AND room.archived = 0"""
-        params: list[object] = []
-        if cursor_values is not None:
-            pinned, updated_at, topic_id = cursor_values
-            query += """ AND (
-                topic.pinned < ? OR (
-                    topic.pinned = ? AND (
-                        topic.updated_at < ? OR (
-                            topic.updated_at = ? AND topic.id < ?
-                        )
-                    )
-                )
-            )"""
-            params.extend((pinned, pinned, updated_at, updated_at, topic_id))
-        query += " ORDER BY topic.pinned DESC, topic.updated_at DESC, topic.id DESC LIMIT ?"
-        params.append(limit + 1)
-        with self.read_transaction() as connection:
-            rows = connection.execute(query, params).fetchall()
-        has_more = len(rows) > limit
-        items = [self._topic_summary(row) for row in rows[:limit]]
-        next_cursor = None
-        if has_more and items:
-            last = rows[limit - 1]
-            next_cursor = self._encode_global_topic_cursor(
-                bool(last["pinned"]), last["updated_at"], last["id"]
-            )
-        return CursorPage(items=items, next_cursor=next_cursor)
-
-    def list_pinned_topics(self, *, limit: int) -> CursorPage:
-        if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 100:
-            raise ValueError("limit must be an integer from 1 to 100")
-        with self.read_transaction() as connection:
-            rows = connection.execute(
-                """SELECT id, room_id FROM group_topics
-                WHERE archived = 0 AND pinned = 1
-                ORDER BY updated_at DESC, id DESC LIMIT ?""",
-                (limit,),
-            ).fetchall()
-            items = [self._topic_summary_by_id(connection, row["room_id"], row["id"])
-                     for row in rows]
-        return CursorPage(items=items, next_cursor=None)
-
-    def room_activity(self, room_id: str) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        with self.read_transaction() as connection:
-            self._room_detail(connection, canonical_room_id, include_archived=True)
-            return self._room_activity_from_connection(connection, canonical_room_id)
-
-    def _room_activity_from_connection(
-        self, connection: sqlite3.Connection, room_id: str
-    ) -> dict[str, object]:
-        counts = connection.execute(
-            """SELECT
-              (SELECT COUNT(*) FROM group_agent_runs AS run
-               WHERE run.room_id = ?
-                 AND run.status IN ('queued', 'running', 'awaiting_input'))
-                AS active_run_count,
-              (SELECT COUNT(*) FROM group_messages AS message
-               JOIN group_topics AS topic ON topic.id = message.topic_id
-               WHERE message.room_id = ? AND message.visible = 1
-                 AND message.sender_kind = 'agent'
-                 AND (TRIM(message.content) != '' OR TRIM(message.error) != '')
-                 AND message.seq > topic.last_read_message_seq)
-                AS unread_count""",
-            (room_id, room_id),
-        ).fetchone()
-        latest = connection.execute(
-            """SELECT id FROM group_messages
-            WHERE room_id = ? AND visible = 1
-            ORDER BY seq DESC LIMIT 1""",
-            (room_id,),
-        ).fetchone()
-        last_message = None
-        if latest is not None:
-            last_message = self._message_wire(
-                self._message_with_execution_row(connection, latest["id"])
-            )
-        return {
-            "roomId": room_id,
-            "activeRunCount": int(counts["active_run_count"]),
-            "unreadCount": int(counts["unread_count"]),
-            "lastMessage": last_message,
-        }
-
-    def update_room(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        command = self._command(
-            command,
-            {
-                "requestId", "name", "cwd", "instructions", "avatar",
-                "maxReplyRounds", "orchestrationMode",
-            },
-        )
-        request_id = self._command_request_id(command)
-        changes = {
-            key
-            for key in (
-                "name", "cwd", "instructions", "avatar", "maxReplyRounds", "orchestrationMode"
-            )
-            if key in command
-        }
-        if not changes:
-            raise ValueError(
-                "Room update requires name, cwd, instructions, avatar, maxReplyRounds, or orchestrationMode"
-            )
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            current_room = self._active_room(connection, canonical_room_id)
-            values: list[object] = []
-            assignments: list[str] = []
-            if "name" in changes:
-                assignments.append("name = ?")
-                values.append(normalize_room_name(self._string(command, "name")))
-            if "cwd" in changes:
-                assignments.append("cwd = ?")
-                values.append(normalize_room_cwd(self._string(command, "cwd")))
-            if "instructions" in changes:
-                assignments.append("instructions = ?")
-                values.append(normalize_room_instructions(command["instructions"]))
-            if "avatar" in changes:
-                assignments.append("avatar_data_url = ?")
-                values.append(normalize_room_avatar(command["avatar"]))
-            if "maxReplyRounds" in changes:
-                assignments.append("max_reply_rounds = ?")
-                values.append(normalize_max_reply_rounds(command["maxReplyRounds"]))
-            if "orchestrationMode" in changes:
-                next_mode = self._orchestration_mode(command["orchestrationMode"])
-                if next_mode != current_room["orchestration_mode"]:
-                    active = connection.execute(
-                        """SELECT 1 FROM group_agent_runs AS run
-                        LEFT JOIN group_idempotency AS cascade
-                          ON cascade.request_id = 'internal:cascade:' || run.id
-                        WHERE run.room_id = ?
-                          AND (
-                            run.status IN ('queued', 'running', 'awaiting_input')
-                            OR cascade.operation = ?
-                          )
-                        LIMIT 1""",
-                        (canonical_room_id, _CASCADE_PENDING_OPERATION),
-                    ).fetchone()
-                    if active is not None:
-                        raise GroupConflictError(
-                            "Cannot change orchestration mode while runs are active"
-                        )
-                assignments.append("orchestration_mode = ?")
-                values.append(next_mode)
-            assignments.append("updated_at = ?")
-            values.extend((self._now(), canonical_room_id))
-            connection.execute(
-                f"UPDATE group_rooms SET {', '.join(assignments)} WHERE id = ?", values
-            )
-            room = self._room_detail(
-                connection, canonical_room_id, include_archived=True
-            )
-            self._append_event(connection, canonical_room_id, "room.updated", room)
-            return room
-
-        return self.execute_idempotent(
-            "room.updated",
-            request_id,
-            self._scoped_payload(command, canonical_room_id),
-            action,
-        )
-
-    def update_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
-        command = self._command(command, {"requestId", "title", "pinned"})
-        request_id = self._command_request_id(command)
-        if not ({"title", "pinned"} & set(command)):
-            raise ValueError("Topic update requires title or pinned")
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            self._active_topic(connection, canonical_room_id, canonical_topic_id)
-            assignments: list[str] = []
-            values: list[object] = []
-            if "title" in command:
-                assignments.append("title = ?")
-                values.append(self._topic_title(self._string(command, "title")))
-            if "pinned" in command:
-                if not isinstance(command["pinned"], bool):
-                    raise ValueError("pinned must be a boolean")
-                assignments.append("pinned = ?")
-                values.append(int(command["pinned"]))
-            now = self._now()
-            assignments.append("updated_at = ?")
-            values.extend((now, canonical_topic_id, canonical_room_id))
-            connection.execute(
-                f"UPDATE group_topics SET {', '.join(assignments)} "
-                "WHERE id = ? AND room_id = ?",
-                values,
-            )
-            topic = self._topic_summary_by_id(
-                connection, canonical_room_id, canonical_topic_id
-            )
-            self._append_event(
-                connection, canonical_room_id, "topic.updated", topic,
-                created_at=now,
-            )
-            return topic
-
-        return self.execute_idempotent(
-            "topic.updated",
-            request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_topic_id),
-            action,
-        )
-
-    def archive_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
-        command = self._command(command, {"requestId"})
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            self._active_topic(connection, canonical_room_id, canonical_topic_id)
-            now = self._now()
-            self._interrupt_runs_for_scope(
-                connection, room_id=canonical_room_id, topic_id=canonical_topic_id,
-                reason="Topic archived", now=now,
-            )
-            connection.execute(
-                "UPDATE group_topics SET archived = 1, updated_at = ? "
-                "WHERE id = ? AND room_id = ?",
-                (now, canonical_topic_id, canonical_room_id),
-            )
-            topic = self._topic_summary_by_id(
-                connection, canonical_room_id, canonical_topic_id
-            )
-            self._append_event(
-                connection, canonical_room_id, "topic.archived", topic,
-                created_at=now,
-            )
-            return topic
-
-        return self.execute_idempotent(
-            "topic.archived", request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_topic_id),
-            action,
-        )
-
-    def restore_topic(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
-        command = self._command(command, {"requestId"})
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            topic_row = self._topic_row(
-                connection, canonical_room_id, canonical_topic_id
-            )
-            if not topic_row["archived"]:
-                raise GroupConflictError("Topic is already active")
-            now = self._now()
-            connection.execute(
-                "UPDATE group_topics SET archived = 0, updated_at = ? "
-                "WHERE id = ? AND room_id = ?",
-                (now, canonical_topic_id, canonical_room_id),
-            )
-            topic = self._topic_summary_by_id(
-                connection, canonical_room_id, canonical_topic_id
-            )
-            self._append_event(
-                connection, canonical_room_id, "topic.restored", topic,
-                created_at=now,
-            )
-            return topic
-
-        return self.execute_idempotent(
-            "topic.restored", request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_topic_id),
-            action,
-        )
-
-    def mark_topic_read(
-        self, room_id: str, topic_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_topic_id = self._canonical_uuid(topic_id, "topicId")
-        command = self._command(command, {"requestId", "throughSeq"})
-        request_id = self._command_request_id(command)
-        through_seq = self._nonnegative_int(command.get("throughSeq"), "throughSeq")
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            topic_row = self._topic_row(
-                connection, canonical_room_id, canonical_topic_id
-            )
-            maximum = int(connection.execute(
-                """SELECT COALESCE(MAX(seq), 0) FROM group_messages
-                WHERE room_id = ? AND topic_id = ? AND visible = 1""",
-                (canonical_room_id, canonical_topic_id),
-            ).fetchone()[0])
-            if through_seq > maximum:
-                raise ValueError("throughSeq exceeds the latest visible message")
-            changed = through_seq > int(topic_row["last_read_message_seq"])
-            if changed:
-                connection.execute(
-                    """UPDATE group_topics SET last_read_message_seq = ?
-                    WHERE id = ? AND room_id = ?""",
-                    (through_seq, canonical_topic_id, canonical_room_id),
-                )
-            topic = self._topic_summary_by_id(
-                connection, canonical_room_id, canonical_topic_id
-            )
-            room = self._room_activity_from_connection(
-                connection, canonical_room_id
-            )
-            if changed:
-                now = self._now()
-                self._append_event(
-                    connection, canonical_room_id, "topic.updated", topic,
-                    created_at=now,
-                )
-                self._append_event(
-                    connection, canonical_room_id, "room.activity", room,
-                    created_at=now,
-                )
-            return {"topic": topic, "room": room}
-
-        return self.execute_idempotent(
-            "topic.read",
-            request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_topic_id),
-            action,
-        )
-
-    def archive_room(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        return self.archive_room_with_runtime_targets(room_id, command)["result"]
-
-    def archive_room_with_runtime_targets(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        command = self._command(command, {"requestId"})
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            now = self._now()
-            interrupted = self._interrupt_runs_for_scope(
-                connection,
-                room_id=canonical_room_id,
-                reason="Room archived",
-                now=now,
-            )
-            connection.execute(
-                "UPDATE group_rooms SET archived = 1, updated_at = ? WHERE id = ?",
-                (now, canonical_room_id),
-            )
-            room = self._room_detail(
-                connection, canonical_room_id, include_archived=True
-            )
-            self._append_event(
-                connection, canonical_room_id, "room.deleted", room, created_at=now
-            )
-            return {
-                "result": room,
-                "runtimeSessionIds": interrupted["runtimeSessionIds"],
-            }
-
-        response = self.execute_idempotent(
-            "room.deleted",
-            request_id,
-            self._scoped_payload(command, canonical_room_id),
-            action,
-        )
-        return self._runtime_envelope(response)
-
-    def restore_room(self, room_id: str, command: Mapping[str, object]) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        command = self._command(command, {"requestId"})
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            room = self._room_detail(
-                connection, canonical_room_id, include_archived=True
-            )
-            if not room["archived"]:
-                raise GroupConflictError("Room is already active")
-            now = self._now()
-            connection.execute(
-                "UPDATE group_rooms SET archived = 0, updated_at = ? WHERE id = ?",
-                (now, canonical_room_id),
-            )
-            restored = self._room_detail(
-                connection, canonical_room_id, include_archived=True
-            )
-            self._append_event(
-                connection, canonical_room_id, "room.restored", restored,
-                created_at=now,
-            )
-            return restored
-
-        return self.execute_idempotent(
-            "room.restored", request_id,
-            self._scoped_payload(command, canonical_room_id), action,
-        )
-
-    def add_agent(
-        self, room_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        command = self._command(
-            command,
-            {
-                "requestId",
-                "profile",
-                "nodeId",
-                "nodeLabel",
-                "displayName",
-                "description",
-                "replyWithoutMention",
-                "isHost",
-                "model",
-                "provider",
-                "reasoningEffort",
-                "fastMode",
-            },
-        )
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            count = connection.execute(
-                "SELECT COUNT(*) FROM group_agents WHERE room_id = ?",
-                (canonical_room_id,),
-            ).fetchone()[0]
-            if count >= MAX_AGENTS_PER_ROOM:
-                raise GroupConflictError(
-                    "Room has reached the maximum number of agents"
-                )
-            agent = self._new_agent(
-                {
-                    key: command[key]
-                    for key in (
-                        "profile",
-                        "nodeId",
-                        "nodeLabel",
-                        "displayName",
-                        "description",
-                        "replyWithoutMention",
-                        "isHost",
-                        "model",
-                        "provider",
-                        "reasoningEffort",
-                        "fastMode",
-                    )
-                    if key in command
-                }
-            )
-            now = self._now()
-            requested_host = bool(agent["is_host"])
-            agent["is_host"] = False
-            agent_id = self._insert_agent(connection, canonical_room_id, agent, now)
-            current_host = self._room_host(connection, canonical_room_id)
-            switched: tuple[dict[str, object], dict[str, object]] | None = None
-            if requested_host or not bool(current_host["enabled"]):
-                switched = self._switch_host(
-                    connection, canonical_room_id, agent_id, now=now
-                )
-            result = self._agent_detail(connection, canonical_room_id, agent_id)
-            connection.execute(
-                "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
-                (now, canonical_room_id),
-            )
-            if switched is not None:
-                self._append_event(
-                    connection,
-                    canonical_room_id,
-                    "agent.updated",
-                    switched[0],
-                    created_at=now,
-                )
-            self._append_event(
-                connection,
-                canonical_room_id,
-                "agent.created",
-                result,
-                created_at=now,
-            )
-            self._append_room_updated_summary(
-                connection, canonical_room_id, created_at=now
-            )
-            return result
-
-        return self.execute_idempotent(
-            "agent.created",
-            request_id,
-            self._scoped_payload(command, canonical_room_id),
-            action,
-        )
-
-    def update_agent(
-        self, room_id: str, agent_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        return self.update_agent_with_runtime_targets(room_id, agent_id, command)[
-            "result"
-        ]
-
-    def update_agent_with_runtime_targets(
-        self, room_id: str, agent_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
-        command = self._command(
-            command,
-            {
-                "requestId",
-                "displayName",
-                "description",
-                "enabled",
-                "replyWithoutMention",
-                "isHost",
-                "model",
-                "provider",
-                "reasoningEffort",
-                "fastMode",
-            },
-        )
-        request_id = self._command_request_id(command)
-        changes = {
-            key
-            for key in (
-                "displayName",
-                "description",
-                "enabled",
-                "replyWithoutMention",
-                "isHost",
-                "model",
-                "provider",
-                "reasoningEffort",
-                "fastMode",
-            )
-            if key in command
-        }
-        if not changes:
-            raise ValueError(
-                "Agent update requires a mutable agent field"
-            )
-        model_changes = changes & {"model", "provider"}
-        if model_changes and model_changes != {"model", "provider"}:
-            raise ValueError("model and provider must be updated together")
-        if model_changes and (
-            (command["model"] is None) != (command["provider"] is None)
-        ):
-            raise ValueError("model and provider must both be set or both be null")
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            previous = self._owned_agent(
-                connection, canonical_room_id, canonical_agent_id
-            )
-            requested_host = command.get("isHost")
-            if requested_host is not None and not isinstance(requested_host, bool):
-                raise ValueError("isHost must be a boolean")
-            if requested_host is False and bool(previous["is_host"]):
-                raise GroupConflictError(
-                    "Current administrator cannot be cleared without selecting a replacement"
-                )
-            if requested_host is True and command.get("enabled") is False:
-                raise GroupConflictError("Administrator Agent must be enabled")
-            replacement_id: str | None = None
-            if (
-                bool(previous["is_host"])
-                and command.get("enabled") is False
-                and bool(previous["enabled"])
-            ):
-                replacement = self._first_enabled_host_candidate(
-                    connection,
-                    canonical_room_id,
-                    exclude_agent_id=canonical_agent_id,
-                )
-                if replacement is None:
-                    raise GroupConflictError(
-                        "Administrator Agent cannot be disabled without an enabled replacement"
-                    )
-                replacement_id = str(replacement["id"])
-            assignments: list[str] = []
-            values: list[object] = []
-            if "displayName" in changes:
-                raw_name = command.get("displayName")
-                configured = self._resolved_agent_name(previous["profile"])
-                effective = (
-                    raw_name.strip()
-                    if isinstance(raw_name, str) and raw_name.strip()
-                    else configured or previous["profile"]
-                )
-                display_name, display_key = normalize_display_name(effective)
-                self._check_agent_conflicts(
-                    connection,
-                    canonical_room_id,
-                    display_key,
-                    exclude_agent_id=canonical_agent_id,
-                )
-                assignments.extend(("display_name = ?", "display_name_key = ?"))
-                values.extend((display_name, display_key))
-            if "description" in changes:
-                assignments.append("description = ?")
-                values.append(self._description(command.get("description")))
-            if "enabled" in changes:
-                enabled = command["enabled"]
-                if not isinstance(enabled, bool):
-                    raise ValueError("enabled must be a boolean")
-                assignments.append("enabled = ?")
-                values.append(int(enabled))
-            if "replyWithoutMention" in changes:
-                reply_without_mention = command["replyWithoutMention"]
-                if not isinstance(reply_without_mention, bool):
-                    raise ValueError("replyWithoutMention must be a boolean")
-                assignments.append("reply_without_mention = ?")
-                values.append(int(reply_without_mention))
-            configuration_columns = {
-                "model": "model_override",
-                "provider": "provider_override",
-                "reasoningEffort": "reasoning_effort_override",
-            }
-            for key, column in configuration_columns.items():
-                if key in changes:
-                    assignments.append(f"{column} = ?")
-                    values.append(self._agent_configuration_value(command[key], key))
-            if "fastMode" in changes:
-                fast_mode = command["fastMode"]
-                if fast_mode is not None and not isinstance(fast_mode, bool):
-                    raise ValueError("fastMode must be a boolean or null")
-                assignments.append("fast_mode_override = ?")
-                values.append(None if fast_mode is None else int(fast_mode))
-            if changes & {"model", "provider", "reasoningEffort", "fastMode"}:
-                # The active run keeps its current session. The next scheduler
-                # pass sees this stale marker and rotates before submitting.
-                assignments.append("session_config_json = NULL")
-            now = self._now()
-            interrupted = {"runIds": [], "runtimeSessionIds": []}
-            if (
-                "enabled" in changes
-                and bool(previous["enabled"])
-                and command["enabled"] is False
-            ):
-                interrupted = self._interrupt_runs_for_scope(
-                    connection,
-                    room_id=canonical_room_id,
-                    agent_id=canonical_agent_id,
-                    reason="Agent disabled",
-                    now=now,
-                )
-            assignments.append("updated_at = ?")
-            values.extend((now, canonical_agent_id, canonical_room_id))
-            connection.execute(
-                f"UPDATE group_agents SET {', '.join(assignments)} WHERE id = ? AND room_id = ?",
-                values,
-            )
-            switched: tuple[dict[str, object], dict[str, object]] | None = None
-            if replacement_id is not None:
-                switched = self._switch_host(
-                    connection, canonical_room_id, replacement_id, now=now
-                )
-            elif requested_host is True:
-                switched = self._switch_host(
-                    connection, canonical_room_id, canonical_agent_id, now=now
-                )
-            elif command.get("enabled") is True:
-                current_host = self._room_host(connection, canonical_room_id)
-                if not bool(current_host["enabled"]):
-                    switched = self._switch_host(
-                        connection, canonical_room_id, canonical_agent_id, now=now
-                    )
-            connection.execute(
-                "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
-                (now, canonical_room_id),
-            )
-            result = self._agent_detail(
-                connection, canonical_room_id, canonical_agent_id
-            )
-            if switched is None:
-                self._append_event(
-                    connection,
-                    canonical_room_id,
-                    "agent.updated",
-                    result,
-                    created_at=now,
-                )
-            else:
-                self._append_event(
-                    connection,
-                    canonical_room_id,
-                    "agent.updated",
-                    switched[0],
-                    created_at=now,
-                )
-                self._append_event(
-                    connection,
-                    canonical_room_id,
-                    "agent.updated",
-                    switched[1],
-                    created_at=now,
-                )
-            self._append_room_updated_summary(
-                connection, canonical_room_id, created_at=now
-            )
-            if interrupted["runIds"]:
-                self._append_agent_status(
-                    connection, canonical_room_id, canonical_agent_id, now
-                )
-            return {
-                "result": result,
-                "runtimeSessionIds": interrupted["runtimeSessionIds"],
-            }
-
-        response = self.execute_idempotent(
-            "agent.updated",
-            request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_agent_id),
-            action,
-        )
-        return self._runtime_envelope(response)
-
-    def delete_agent(
-        self, room_id: str, agent_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        return self.delete_agent_with_runtime_targets(room_id, agent_id, command)[
-            "result"
-        ]
-
-    def delete_agent_with_runtime_targets(
-        self, room_id: str, agent_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
-        command = self._command(command, {"requestId"})
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            result = self._agent_detail(
-                connection, canonical_room_id, canonical_agent_id
-            )
-            agent_count = connection.execute(
-                "SELECT COUNT(*) FROM group_agents WHERE room_id = ?",
-                (canonical_room_id,),
-            ).fetchone()[0]
-            if agent_count <= 1:
-                raise GroupConflictError("Room must retain at least one agent")
-            now = self._now()
-            switched: tuple[dict[str, object], dict[str, object]] | None = None
-            if result["isHost"] is True:
-                replacement = self._first_enabled_host_candidate(
-                    connection,
-                    canonical_room_id,
-                    exclude_agent_id=canonical_agent_id,
-                )
-                if replacement is None:
-                    raise GroupConflictError(
-                        "Administrator Agent cannot be removed without an enabled replacement"
-                    )
-                switched = self._switch_host(
-                    connection,
-                    canonical_room_id,
-                    str(replacement["id"]),
-                    now=now,
-                )
-            interrupted = self._interrupt_runs_for_scope(
-                connection,
-                room_id=canonical_room_id,
-                agent_id=canonical_agent_id,
-                reason="Agent removed",
-                now=now,
-            )
-            connection.execute(
-                "DELETE FROM group_agents WHERE id = ? AND room_id = ?",
-                (canonical_agent_id, canonical_room_id),
-            )
-            connection.execute(
-                "UPDATE group_rooms SET updated_at = ? WHERE id = ?",
-                (now, canonical_room_id),
-            )
-            if switched is not None:
-                self._append_event(
-                    connection,
-                    canonical_room_id,
-                    "agent.updated",
-                    switched[1],
-                    created_at=now,
-                )
-            self._append_event(
-                connection, canonical_room_id, "agent.deleted", result, created_at=now
-            )
-            self._append_room_updated_summary(
-                connection, canonical_room_id, created_at=now
-            )
-            return {
-                "result": result,
-                "runtimeSessionIds": interrupted["runtimeSessionIds"],
-            }
-
-        response = self.execute_idempotent(
-            "agent.deleted",
-            request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_agent_id),
-            action,
-        )
-        return self._runtime_envelope(response)
-
-    def interrupt_agent_with_runtime_targets(
-        self, room_id: str, agent_id: str, command: Mapping[str, object]
-    ) -> dict[str, object]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_agent_id = self._canonical_uuid(agent_id, "agentId")
-        command = self._command(command, {"requestId"})
-        request_id = self._command_request_id(command)
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            self._active_room(connection, canonical_room_id)
-            self._owned_agent(connection, canonical_room_id, canonical_agent_id)
-            now = self._now()
-            interrupted = self._interrupt_runs_for_scope(
-                connection,
-                room_id=canonical_room_id,
-                agent_id=canonical_agent_id,
-                reason="Agent interrupted",
-                now=now,
-                include_queued=False,
-            )
-            if interrupted["runIds"]:
-                self._append_agent_status(
-                    connection, canonical_room_id, canonical_agent_id, now
-                )
-            return {
-                "result": {
-                    "roomId": canonical_room_id,
-                    "agentId": canonical_agent_id,
-                    "interruptedRunIds": interrupted["runIds"],
-                },
-                "runtimeSessionIds": interrupted["runtimeSessionIds"],
-            }
-
-        response = self.execute_idempotent(
-            "agent.interrupted",
-            request_id,
-            self._scoped_payload(command, canonical_room_id, canonical_agent_id),
-            action,
-        )
-        return self._runtime_envelope(response)
-
-    def create_human_message(
-        self,
-        room_id: str,
-        *,
-        request_id: str,
-        client_message_id: str,
-        content: str,
-        mention_agent_ids: object,
-        topic_id: str | None = None,
-    ) -> dict[str, object]:
-        """Persist one human turn and the deterministic agent work it starts."""
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_request_id = self._canonical_uuid(request_id, "requestId")
-        canonical_client_id = self._canonical_uuid(client_message_id, "clientMessageId")
-        canonical_topic_id = (
-            self._compatibility_topic_id(canonical_room_id)
-            if topic_id is None
-            else self._canonical_uuid(topic_id, "topicId")
-        )
-        message_content = self._message_text(
-            content, "content", max_bytes=MAX_MESSAGE_BYTES, nonblank=True
-        )
-        agent_ids = self._mention_agent_ids(mention_agent_ids)
-        payload = {
-            "roomId": canonical_room_id,
-            "clientMessageId": canonical_client_id,
-            "content": message_content,
-            "mentionAgentIds": agent_ids,
-        }
-        if topic_id is not None:
-            payload["topicId"] = canonical_topic_id
-
-        def action(connection: sqlite3.Connection) -> dict[str, object]:
-            room = self._active_room(connection, canonical_room_id)
-            agents: list[tuple[sqlite3.Row, str, bool]] = []
-            room_agents = connection.execute(
-                """SELECT * FROM group_agents WHERE room_id = ?
-                ORDER BY created_at ASC, id ASC""",
-                (canonical_room_id,),
-            ).fetchall()
-            parsed_ids, _warnings = self._plan_cascade_mentions(
-                message_content,
-                room_agents,
-                source_agent_id="human",
-                include_automatic=False,
-            )
-            agents_by_id = {str(agent["id"]): agent for agent in room_agents}
-            explicit_agent_ids = [
-                agent_id
-                for agent_id in dict.fromkeys([*agent_ids, *parsed_ids])
-                if agent_id in agents_by_id and agents_by_id[agent_id]["enabled"]
-            ]
-            if room["orchestration_mode"] == "host":
-                host = self._room_host(connection, canonical_room_id)
-                agents.append((host, "automatic", True))
-            elif explicit_agent_ids:
-                agents.extend(
-                    (agents_by_id[agent_id], "mentioned", False)
-                    for agent_id in explicit_agent_ids
-                )
-            else:
-                host = self._room_host(connection, canonical_room_id)
-                scheduled_ids: set[str] = set()
-                if host["enabled"]:
-                    agents.append((host, "automatic", True))
-                    scheduled_ids.add(str(host["id"]))
-                agents.extend(
-                    (agent, "automatic", False)
-                    for agent in room_agents
-                    if agent["enabled"]
-                    and agent["reply_without_mention"]
-                    and agent["id"] not in scheduled_ids
-                )
-            now = self._now()
-            self._ensure_topic(
-                connection,
-                canonical_room_id,
-                canonical_topic_id,
-                message_content,
-                now,
-            )
-            human_id = str(uuid.uuid4())
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, topic_id, sender_kind, sender_id, sender_name, root_message_id,
-                 reply_to_message_id, client_message_id, content, reasoning, tool_state_json,
-                 status, error, created_at, updated_at)
-                VALUES (?, ?, ?, 'human', 'human', '你', ?, NULL, ?, ?, '', '[]', 'completed', '', ?, ?)""",
-                (
-                    human_id,
-                    canonical_room_id,
-                    canonical_topic_id,
-                    human_id,
-                    canonical_client_id,
-                    message_content,
-                    now,
-                    now,
-                ),
-            )
-            message = self._message_wire(self._message_row(connection, human_id))
-            self._append_event(
-                connection, canonical_room_id, "message.upsert", message, created_at=now
-            )
-            runs: list[dict[str, object]] = []
-            for agent, reply_mode, required_reply in agents:
-                visible = reply_mode == "mentioned" or required_reply
-                response_id, run_id = str(uuid.uuid4()), str(uuid.uuid4())
-                connection.execute(
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name, root_message_id,
-                     reply_to_message_id, client_message_id, content, reasoning, tool_state_json,
-                     status, error, visible, created_at, updated_at)
-                    VALUES (?, ?, ?, 'agent', ?, ?, ?, ?, NULL, '', '', '[]', 'queued', '', ?, ?, ?)""",
-                    (
-                        response_id,
-                        canonical_room_id,
-                        canonical_topic_id,
-                        agent["id"],
-                        agent["display_name"],
-                        human_id,
-                        human_id,
-                        int(visible),
-                        now,
-                        now,
-                    ),
-                )
-                connection.execute(
-                    """INSERT INTO group_agent_runs
-                    (id, room_id, topic_id, agent_id, trigger_message_id, response_message_id, root_message_id,
-                     depth, reply_mode, required_reply, status, runtime_session_id,
-                     requested_model, requested_provider,
-                     requested_reasoning_effort, requested_fast_mode,
-                     actual_model, actual_provider, actual_reasoning_effort,
-                     actual_fast_mode, error, created_at, updated_at)
-                    VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, 'queued', NULL,
-                            ?, ?, ?, ?, NULL, NULL, NULL, NULL, '', ?, ?)""",
-                    (
-                        run_id,
-                        canonical_room_id,
-                        canonical_topic_id,
-                        agent["id"],
-                        human_id,
-                        response_id,
-                        human_id,
-                        reply_mode,
-                        int(required_reply),
-                        agent["model_override"],
-                        agent["provider_override"],
-                        agent["reasoning_effort_override"],
-                        agent["fast_mode_override"],
-                        now,
-                        now,
-                    ),
-                )
-                response = self._message_wire(
-                    self._message_row(connection, response_id)
-                )
-                run = self._run_wire(self._run_row(connection, run_id))
-                if visible:
-                    self._append_event(
-                        connection,
-                        canonical_room_id,
-                        "message.upsert",
-                        response,
-                        created_at=now,
-                    )
-                self._append_event(
-                    connection, canonical_room_id, "run.updated", run, created_at=now
-                )
-                runs.append(run)
-            return {"message": message, "runs": runs}
-
-        try:
-            return self.execute_idempotent(
-                "message.create", canonical_request_id, payload, action
-            )
-        except sqlite3.IntegrityError as error:
-            raise self._integrity_conflict(error) from error
-
-    def get_message(self, message_id: str) -> dict[str, object]:
-        canonical_message_id = self._canonical_uuid(message_id, "messageId")
-        with self.read_transaction() as connection:
-            return self._message_wire(
-                self._message_with_execution_row(connection, canonical_message_id)
-            )
-
-    def get_run(self, run_id: str) -> dict[str, object]:
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        with self.read_transaction() as connection:
-            return self._run_wire(self._run_row(connection, canonical_run_id))
-
-    def get_interaction(self, interaction_id: str) -> dict[str, object]:
-        canonical_interaction_id = self._interaction_id(interaction_id)
-        with self.read_transaction() as connection:
-            return self._interaction_wire(
-                self._interaction_row(connection, canonical_interaction_id)
-            )
-
-    def list_messages(
-        self,
-        room_id: str,
-        *,
-        topic_id: str | None = None,
-        before_seq: int | None = None,
-        after_seq: int | None = None,
-        limit: int = MAX_MESSAGE_PAGE_SIZE,
-    ) -> list[dict[str, object]]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        canonical_topic_id = (
-            None
-            if topic_id is None
-            else self._canonical_uuid(topic_id, "topicId")
-        )
-        self._page_limit(limit, MAX_MESSAGE_PAGE_SIZE, "limit")
-        if before_seq is not None and after_seq is not None:
-            raise ValueError("before_seq and after_seq are mutually exclusive")
-        before = (
-            self._positive_int(before_seq, "before_seq")
-            if before_seq is not None
-            else None
-        )
-        after = (
-            self._positive_int(after_seq, "after_seq")
-            if after_seq is not None
-            else None
-        )
-        with self.read_transaction() as connection:
-            self._room_detail(connection, canonical_room_id, include_archived=True)
-            if canonical_topic_id is not None:
-                self._topic_row(connection, canonical_room_id, canonical_topic_id)
-            scope = "message.room_id = ?"
-            scope_params: tuple[object, ...] = (canonical_room_id,)
-            if canonical_topic_id is not None:
-                scope += " AND message.topic_id = ?"
-                scope_params = (canonical_room_id, canonical_topic_id)
-            select = """SELECT message.*,
-                run.requested_model AS execution_requested_model,
-                run.requested_provider AS execution_requested_provider,
-                run.requested_reasoning_effort AS execution_requested_reasoning_effort,
-                run.requested_fast_mode AS execution_requested_fast_mode,
-                run.actual_model AS execution_actual_model,
-                run.actual_provider AS execution_actual_provider,
-                run.actual_reasoning_effort AS execution_actual_reasoning_effort,
-                run.actual_fast_mode AS execution_actual_fast_mode
-                FROM group_messages AS message
-                LEFT JOIN group_agent_runs AS run
-                  ON run.response_message_id = message.id"""
-            if before is not None:
-                rows = connection.execute(
-                    f"{select} WHERE {scope} AND message.visible = 1 AND message.seq < ? ORDER BY message.seq DESC LIMIT ?",
-                    (*scope_params, before, limit),
-                ).fetchall()
-                rows = list(reversed(rows))
-            elif after is not None:
-                rows = connection.execute(
-                    f"{select} WHERE {scope} AND message.visible = 1 AND message.seq > ? ORDER BY message.seq ASC LIMIT ?",
-                    (*scope_params, after, limit),
-                ).fetchall()
-            else:
-                rows = connection.execute(
-                    f"{select} WHERE {scope} AND message.visible = 1 ORDER BY message.seq DESC LIMIT ?",
-                    (*scope_params, limit),
-                ).fetchall()
-                rows = list(reversed(rows))
-            return [self._message_wire(row) for row in rows]
-
-    def claim_next_runnable_run(self) -> dict[str, object] | None:
-        """Atomically claim the oldest eligible queued run."""
-        with self.write_transaction() as connection:
-            active_count = int(
-                connection.execute(
-                    """SELECT COUNT(*) FROM group_agent_runs
-                    WHERE status IN ('running', 'awaiting_input')"""
-                ).fetchone()[0]
-            )
-            if active_count >= MAX_PLUGIN_CONCURRENCY:
-                return None
-            run = connection.execute(
-                """SELECT candidate.* FROM group_agent_runs AS candidate
-                JOIN group_rooms AS room ON room.id = candidate.room_id
-                JOIN group_agents AS agent
-                  ON agent.id = candidate.agent_id
-                 AND agent.room_id = candidate.room_id
-                JOIN group_messages AS trigger_message
-                  ON trigger_message.id = candidate.trigger_message_id
-                JOIN group_messages AS root_message
-                  ON root_message.id = candidate.root_message_id
-                WHERE candidate.status = 'queued'
-                  AND room.archived = 0
-                  AND agent.enabled = 1
-                  AND NOT EXISTS (
-                    SELECT 1 FROM group_agent_runs AS occupied_agent
-                    WHERE occupied_agent.agent_id = candidate.agent_id
-                      AND occupied_agent.status IN ('running', 'awaiting_input')
-                  )
-                  AND (
-                    SELECT COUNT(*) FROM group_agent_runs AS occupied_room
-                    WHERE occupied_room.room_id = candidate.room_id
-                      AND occupied_room.status IN ('running', 'awaiting_input')
-                  ) < ?
-                  AND (
-                    room.orchestration_mode != 'host'
-                    OR NOT EXISTS (
-                      SELECT 1 FROM group_agent_runs AS occupied_topic
-                      WHERE occupied_topic.topic_id = candidate.topic_id
-                        AND occupied_topic.status IN ('running', 'awaiting_input')
-                    )
-                    OR (
-                      agent.is_host = 0
-                      AND NOT EXISTS (
-                        SELECT 1 FROM group_agent_runs AS occupied_topic
-                        JOIN group_agents AS occupied_topic_agent
-                          ON occupied_topic_agent.id = occupied_topic.agent_id
-                        WHERE occupied_topic.topic_id = candidate.topic_id
-                          AND occupied_topic.status IN ('running', 'awaiting_input')
-                          AND (
-                            occupied_topic.root_message_id != candidate.root_message_id
-                            OR occupied_topic.trigger_message_id != candidate.trigger_message_id
-                            OR occupied_topic.depth != candidate.depth
-                            OR occupied_topic_agent.is_host = 1
-                          )
-                      )
-                    )
-                  )
-                ORDER BY CASE WHEN room.orchestration_mode = 'host'
-                              THEN root_message.seq ELSE trigger_message.seq END ASC,
-                         trigger_message.seq ASC,
-                         candidate.created_at ASC,
-                         candidate.id ASC
-                LIMIT 1""",
-                (MAX_ROOM_CONCURRENCY,),
-            ).fetchone()
-            if run is None:
-                return None
-            response = self._message_row(connection, run["response_message_id"])
-            self._validate_run_message_state(run, response)
-            now = self._now()
-            result = self._update_run(connection, run, "running", now, UNSET, UNSET)
-            self._append_event(
-                connection,
-                run["room_id"],
-                "run.updated",
-                result,
-                created_at=now,
-            )
-            self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
-            return result
-
-    def read_run_projection(self, run_id: str) -> dict[str, object]:
-        """Return a stable, bounded context projection for one claimed run."""
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        with self.read_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            if run["status"] not in {"running", "awaiting_input"}:
-                raise GroupConflictError("Run is not claimed")
-            room = self._active_room(connection, run["room_id"])
-            agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            trigger = self._message_row(connection, run["trigger_message_id"])
-            if (
-                trigger["room_id"] != run["room_id"]
-                or trigger["topic_id"] != run["topic_id"]
-            ):
-                raise GroupStoreError("Run trigger message is corrupt")
-            topic_state = self._agent_topic_state(
-                connection, run["agent_id"], run["topic_id"]
-            )
-            lower_seq = int(topic_state["last_context_message_seq"])
-            trigger_seq = int(trigger["seq"])
-            through_seq = self._safe_context_seq(
-                connection,
-                run["room_id"],
-                run["topic_id"],
-                lower_seq,
-                trigger_seq,
-            )
-            eligibility = """FROM group_messages
-                WHERE room_id = ? AND topic_id = ? AND seq > ? AND seq <= ?
-                  AND visible = 1
-                  AND status IN ('completed', 'failed', 'interrupted')
-                  AND NOT (sender_kind = 'agent' AND sender_id = ?)"""
-            parameters = (
-                run["room_id"],
-                run["topic_id"],
-                lower_seq,
-                trigger_seq,
-                run["agent_id"],
-            )
-            total = int(
-                connection.execute(
-                    f"SELECT COUNT(*) {eligibility}", parameters
-                ).fetchone()[0]
-            )
-            rows = connection.execute(
-                f"""SELECT * {eligibility}
-                ORDER BY seq DESC LIMIT ?""",
-                (*parameters, INITIAL_CONTEXT_MESSAGE_LIMIT),
-            ).fetchall()
-            rows = list(reversed(rows))
-            omitted = total - len(rows)
-            omitted_through_seq: int | None = None
-            if omitted:
-                omitted_through_seq = int(
-                    connection.execute(
-                        f"""SELECT MAX(seq) {eligibility}
-                        AND seq < ?""",
-                        (*parameters, rows[0]["seq"]),
-                    ).fetchone()[0]
-                )
-            initial = agent["stored_session_id"] is None
-            projected_agent = self._agent_wire(agent)
-            projected_agent["lastContextMessageSeq"] = lower_seq
-            messages = [self._projection_message(row) for row in rows]
-            messages, omitted, omitted_through_seq, omitted_summary = (
-                self._bound_projection_messages(
-                    messages,
-                    omitted_count=omitted,
-                    omitted_through_seq=omitted_through_seq,
-                )
-            )
-            projected_run = self._run_wire(run)
-            projected_run["requiredReply"] = bool(run["required_reply"])
-            return {
-                "run": projected_run,
-                "room": self._room_wire(room),
-                "agent": projected_agent,
-                "messages": messages,
-                "initial": initial,
-                "triggerSeq": trigger_seq,
-                "throughSeq": through_seq,
-                "omittedMessageCount": omitted,
-                "omittedThroughSeq": omitted_through_seq,
-                "omittedSummary": omitted_summary,
-                "characterBudget": CONTEXT_CHARACTER_BUDGET,
-            }
-
-    def bind_run_session(
-        self,
-        run_id: str,
-        *,
-        expected_stored_session_id: str | None,
-        stored_session_id: str,
-        runtime_session_id: str,
-    ) -> dict[str, object]:
-        """CAS-bind stored and runtime identities for the current generation."""
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        expected_stored = self._runtime_session_id(expected_stored_session_id)
-        stored = self._runtime_session_id(stored_session_id)
-        runtime = self._runtime_session_id(runtime_session_id)
-        if stored is None:
-            raise ValueError("storedSessionId is invalid")
-        if runtime is None:
-            raise ValueError("runtimeSessionId is invalid")
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            self._active_room(connection, run["room_id"])
-            agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            self._validate_run_message_state(run, response)
-            if run["status"] not in {"running", "awaiting_input"}:
-                raise GroupConflictError("Run does not accept a session binding")
-            if agent["stored_session_id"] != expected_stored:
-                raise GroupConflictError("stored session generation changed")
-            if run["runtime_session_id"] not in {None, runtime}:
-                raise GroupConflictError("Run runtime is already bound")
-            self._require_available_runtime(connection, runtime, canonical_run_id)
-            now = self._now()
-            if agent["stored_session_id"] != stored:
-                connection.execute(
-                    """UPDATE group_agents
-                    SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
-                    (stored, now, agent["id"]),
-                )
-                agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "agent.updated",
-                    self._agent_wire(agent),
-                    created_at=now,
-                )
-            if run["runtime_session_id"] != runtime:
-                changed = self._update_run(
-                    connection, run, run["status"], now, runtime, UNSET
-                )
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "run.updated",
-                    changed,
-                    created_at=now,
-                )
-            else:
-                changed = self._run_wire(run)
-            return {"run": changed, "agent": self._agent_wire(agent)}
-
-    def advance_run_context(
-        self,
-        run_id: str,
-        *,
-        runtime_session_id: str,
-        expected_context_seq: int,
-        through_seq: int,
-    ) -> dict[str, object]:
-        """Advance one Agent context watermark with generation and hole CAS checks."""
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        runtime = self._runtime_session_id(runtime_session_id)
-        if runtime is None:
-            raise ValueError("runtimeSessionId is invalid")
-        expected = self._nonnegative_int(expected_context_seq, "expectedContextSeq")
-        through = self._nonnegative_int(through_seq, "throughSeq")
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            self._active_room(connection, run["room_id"])
-            agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            if run["status"] not in {"running", "awaiting_input"}:
-                raise GroupConflictError("Run no longer accepts context")
-            if run["runtime_session_id"] != runtime:
-                raise GroupConflictError("Run runtime generation changed")
-            topic_state = self._agent_topic_state(
-                connection, run["agent_id"], run["topic_id"]
-            )
-            if int(topic_state["last_context_message_seq"]) != expected:
-                raise GroupConflictError("Agent context generation changed")
-            trigger = self._message_row(connection, run["trigger_message_id"])
-            safe = self._safe_context_seq(
-                connection,
-                run["room_id"],
-                run["topic_id"],
-                expected,
-                int(trigger["seq"]),
-            )
-            if through < expected or through > safe:
-                raise GroupConflictError("throughSeq exceeds safe projection")
-            now = self._now()
-            connection.execute(
-                """UPDATE group_agent_topic_state
-                SET last_context_message_seq = ?, updated_at = ?
-                WHERE agent_id = ? AND topic_id = ?""",
-                (through, now, agent["id"], run["topic_id"]),
-            )
-            changed = self._agent_wire(agent)
-            changed["lastContextMessageSeq"] = through
-            return changed
-
-    def commit_prompt_submission(
-        self,
-        run_id: str,
-        *,
-        expected_stored_session_id: str | None,
-        stored_session_id: str,
-        runtime_session_id: str,
-        expected_context_seq: int,
-        through_seq: int,
-    ) -> dict[str, object]:
-        """Commit a successful prompt submission and its durable context CAS."""
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        expected_stored = self._runtime_session_id(expected_stored_session_id)
-        stored = self._runtime_session_id(stored_session_id)
-        runtime = self._runtime_session_id(runtime_session_id)
-        expected = self._nonnegative_int(expected_context_seq, "expectedContextSeq")
-        through = self._nonnegative_int(through_seq, "throughSeq")
-        if stored is None:
-            raise ValueError("storedSessionId is invalid")
-        if runtime is None:
-            raise ValueError("runtimeSessionId is invalid")
-        operation = f"run.prompt.submitted:{canonical_run_id}"
-        legacy_ledger_id = str(
-            uuid.uuid5(
-                uuid.NAMESPACE_URL,
-                f"hermes://yaoyao-group/{canonical_run_id}/prompt-submission",
-            )
-        )
-        ledger_id = f"internal:prompt:{canonical_run_id}"
-        payload = {
-            "runId": canonical_run_id,
-            "expectedStoredSessionId": expected_stored,
-            "storedSessionId": stored,
-            "runtimeSessionId": runtime,
-            "expectedContextSeq": expected,
-            "throughSeq": through,
-        }
-        request_hash = hashlib.sha256(
-            self._canonical_json(payload).encode()
-        ).hexdigest()
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            self._active_room(connection, run["room_id"])
-            agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            self._validate_run_message_state(run, response)
-            if run["status"] != "running":
-                raise GroupConflictError("Run no longer accepts a prompt submission")
-            if run["runtime_session_id"] != runtime:
-                raise GroupConflictError("Run runtime generation changed")
-            current_stored = agent["stored_session_id"]
-            topic_state = self._agent_topic_state(
-                connection, run["agent_id"], run["topic_id"]
-            )
-            current_context = int(topic_state["last_context_message_seq"])
-            existing = connection.execute(
-                """SELECT request_id, operation, request_hash, response_json
-                FROM group_idempotency WHERE request_id = ?""",
-                (ledger_id,),
-            ).fetchone()
-            legacy_existing = None
-            if existing is None:
-                candidate = connection.execute(
-                    """SELECT operation, request_hash, response_json
-                    FROM group_idempotency WHERE request_id = ?""",
-                    (legacy_ledger_id,),
-                ).fetchone()
-                if candidate is not None and candidate["operation"] == operation:
-                    existing = candidate
-                    legacy_existing = candidate
-            if existing is not None:
-                if (
-                    existing["operation"] != operation
-                    or existing["request_hash"] != request_hash
-                ):
-                    raise GroupConflictError("Prompt submission generation changed")
-                if current_stored != stored or current_context != through:
-                    raise GroupConflictError("Prompt submission generation changed")
-                stored_response = existing["response_json"]
-                try:
-                    replay = self._load_json(stored_response)
-                except (TypeError, ValueError, json.JSONDecodeError) as error:
-                    raise GroupStoreError(
-                        "Stored prompt submission is corrupt"
-                    ) from error
-                if (
-                    not isinstance(replay, dict)
-                    or self._canonical_json(replay) != stored_response
-                ):
-                    raise GroupStoreError("Stored prompt submission is corrupt")
-                if legacy_existing is not None:
-                    connection.execute(
-                        """UPDATE group_idempotency SET request_id = ?
-                        WHERE request_id = ?""",
-                        (ledger_id, legacy_ledger_id),
-                    )
-                return replay
-            if current_stored != expected_stored:
-                raise GroupConflictError("stored session generation changed")
-            if current_context != expected:
-                raise GroupConflictError("Agent context generation changed")
-            trigger = self._message_row(connection, run["trigger_message_id"])
-            safe = self._safe_context_seq(
-                connection,
-                run["room_id"],
-                run["topic_id"],
-                expected,
-                int(trigger["seq"]),
-            )
-            if through < expected or through > safe:
-                raise GroupConflictError("throughSeq exceeds safe projection")
-            now = self._now()
-            if current_stored != stored:
-                connection.execute(
-                    """UPDATE group_agents
-                    SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
-                    (stored, now, agent["id"]),
-                )
-                agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "agent.updated",
-                    self._agent_wire(agent),
-                    created_at=now,
-                )
-            if current_context != through:
-                connection.execute(
-                    """UPDATE group_agent_topic_state
-                    SET last_context_message_seq = ?, updated_at = ?
-                    WHERE agent_id = ? AND topic_id = ?""",
-                    (through, now, agent["id"], run["topic_id"]),
-                )
-            result_agent = self._agent_wire(agent)
-            result_agent["lastContextMessageSeq"] = through
-            result = {
-                "run": self._run_wire(run),
-                "agent": result_agent,
-            }
-            connection.execute(
-                """INSERT INTO group_idempotency
-                (request_id, operation, request_hash, response_json, created_at)
-                VALUES (?, ?, ?, ?, ?)""",
-                (
-                    ledger_id,
-                    operation,
-                    request_hash,
-                    self._canonical_json(result),
-                    now,
-                ),
-            )
-            return result
-
-    def settle_run(
-        self,
-        run_id: str,
-        *,
-        runtime_session_id: str | None,
-        expected_stored_session_id: str | None,
-        stored_session_id: str | None,
-        outcome: str,
-        actual_model: str | None = None,
-        actual_provider: str | None = None,
-        actual_reasoning_effort: str | None = None,
-        actual_fast_mode: bool | None = None,
-        error: str = "",
-    ) -> dict[str, object]:
-        """Settle message, run, session rotation, and status in one transaction."""
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        runtime = self._runtime_session_id(runtime_session_id)
-        expected_stored = self._runtime_session_id(expected_stored_session_id)
-        stored = self._runtime_session_id(stored_session_id)
-        effective_model = self._agent_configuration_value(actual_model, "model")
-        effective_provider = self._agent_configuration_value(
-            actual_provider, "provider"
-        )
-        if (effective_model is None) != (effective_provider is None):
-            raise ValueError("actual model and provider must both be set or both be null")
-        effective_reasoning = self._agent_configuration_value(
-            actual_reasoning_effort, "reasoningEffort"
-        )
-        if actual_fast_mode is not None and not isinstance(actual_fast_mode, bool):
-            raise ValueError("actual fast mode must be a boolean or null")
-        run_error = self._message_text(error, "error", max_bytes=4096)
-        if outcome not in {"completed", "failed", "interrupted"}:
-            raise ValueError("outcome is invalid")
-        if runtime is None and outcome != "failed":
-            raise ValueError("A runtime-less settle only supports failed")
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            room = self._active_room(connection, run["room_id"])
-            agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            self._validate_run_message_state(run, response)
-            if run["status"] not in {"running", "awaiting_input"}:
-                raise GroupConflictError("Run is already settled")
-            if run["runtime_session_id"] != runtime:
-                raise GroupConflictError("Run runtime generation changed")
-            if agent["stored_session_id"] != expected_stored:
-                raise GroupConflictError("stored session generation changed")
-            if outcome == "completed" and response["status"] != "completed":
-                raise GroupConflictError("Response message must be completed first")
-            now = self._now()
-            if stored != agent["stored_session_id"]:
-                connection.execute(
-                    """UPDATE group_agents
-                    SET stored_session_id = ?, updated_at = ? WHERE id = ?""",
-                    (stored, now, agent["id"]),
-                )
-                agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "agent.updated",
-                    self._agent_wire(agent),
-                    created_at=now,
-                )
-            connection.execute(
-                """UPDATE group_agent_runs
-                SET actual_model = ?, actual_provider = ?,
-                    actual_reasoning_effort = ?, actual_fast_mode = ?
-                WHERE id = ?""",
-                (
-                    effective_model,
-                    effective_provider,
-                    effective_reasoning,
-                    None if actual_fast_mode is None else int(actual_fast_mode),
-                    run["id"],
-                ),
-            )
-            run = self._run_row(connection, run["id"])
-            self._cancel_pending_interactions(connection, run, now)
-            changed = self._update_run(connection, run, outcome, now, None, run_error)
-            self._fail_claimed_interaction_ledgers(
-                connection,
-                run_id=run["id"],
-                reason=run_error or f"Run {outcome}",
-                runtime_session_ids=[] if runtime is None else [runtime],
-                run=changed,
-            )
-            self._append_event(
-                connection,
-                run["room_id"],
-                "run.updated",
-                changed,
-                created_at=now,
-            )
-            if (
-                outcome in {"failed", "interrupted"}
-                and response["status"] != "completed"
-            ):
-                connection.execute(
-                    """UPDATE group_messages
-                    SET status = ?, error = ?, updated_at = ? WHERE id = ?""",
-                    (outcome, run_error, now, response["id"]),
-                )
-                response = self._message_row(connection, response["id"])
-                if response["visible"]:
-                    self._append_event(
-                        connection,
-                        run["room_id"],
-                        "message.upsert",
-                        self._message_wire(
-                            self._message_with_execution_row(
-                                connection, response["id"]
-                            )
-                        ),
-                        created_at=now,
-                    )
-            elif (
-                effective_model is not None
-                or effective_reasoning is not None
-                or actual_fast_mode is not None
-            ) and response["visible"]:
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "message.upsert",
-                    self._message_wire(
-                        self._message_with_execution_row(connection, response["id"])
-                    ),
-                    created_at=now,
-                )
-            if outcome == "completed" or (
-                room["orchestration_mode"] == "host" and not agent["is_host"]
-            ):
-                self._record_cascade_plan(
-                    connection,
-                    source=run,
-                    source_message=response,
-                    created_at=now,
-                )
-            self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
-            return {
-                "run": changed,
-                "message": self._message_wire(
-                    self._message_with_execution_row(connection, response["id"])
-                ),
-                "agent": self._agent_wire(agent),
-            }
-
-    @classmethod
-    def _cascade_request_id(cls, source_run_id: str) -> str:
-        return f"internal:cascade:{source_run_id}"
-
-    @classmethod
-    def _cascade_request_hash(
-        cls, source_run_id: str, *, parse_version: int = _CASCADE_PARSE_VERSION
-    ) -> str:
-        payload = {
-            "parseVersion": parse_version,
-            "sourceRunId": source_run_id,
-            "version": 1,
-        }
-        return hashlib.sha256(cls._canonical_json(payload).encode()).hexdigest()
-
-    def _record_cascade_plan(
-        self,
-        connection: sqlite3.Connection,
-        *,
-        source: sqlite3.Row,
-        source_message: sqlite3.Row,
-        created_at: float,
-    ) -> None:
-        request_id = self._cascade_request_id(source["id"])
-        existing = connection.execute(
-            "SELECT 1 FROM group_idempotency WHERE request_id = ?",
-            (request_id,),
-        ).fetchone()
-        if existing is not None:
-            raise GroupStoreError("Cascade ledger already exists")
-        agents = connection.execute(
-            "SELECT * FROM group_agents WHERE room_id = ? "
-            "ORDER BY created_at ASC, id ASC",
-            (source["room_id"],),
-        ).fetchall()
-        room = self._active_room(connection, source["room_id"])
-        source_agent = next(
-            (agent for agent in agents if agent["id"] == source["agent_id"]), None
-        )
-        if source_agent is None:
-            raise GroupStoreError("Cascade source Agent is missing")
-        if room["orchestration_mode"] == "host":
-            if source_agent["is_host"] and source_message["visible"]:
-                target_ids, warnings = self._plan_cascade_mentions(
-                    source_message["content"],
-                    agents,
-                    source_agent_id=source["agent_id"],
-                    include_automatic=False,
-                )
-                explicit_ids = list(target_ids)
-            elif not source_agent["is_host"]:
-                host = next(
-                    (agent for agent in agents if agent["is_host"] and agent["enabled"]),
-                    None,
-                )
-                if host is None:
-                    raise GroupStoreError("Administrator flow has no enabled administrator Agent")
-                target_ids, warnings = [str(host["id"])], []
-                explicit_ids = []
-            else:
-                target_ids, warnings = [], []
-                explicit_ids = []
-        elif source_message["visible"]:
-            target_ids, warnings = self._plan_cascade_mentions(
-                source_message["content"],
-                agents,
-                source_agent_id=source["agent_id"],
-            )
-            explicit_ids, _ = self._plan_cascade_mentions(
-                source_message["content"],
-                agents,
-                source_agent_id=source["agent_id"],
-                include_automatic=False,
-            )
-        else:
-            target_ids, warnings = [], []
-            explicit_ids = []
-        explicit_set = set(explicit_ids)
-        plan = {
-            "parseVersion": _CASCADE_PARSE_VERSION,
-            "sourceMessageId": source_message["id"],
-            "sourceRunId": source["id"],
-            "state": "pending",
-            "targets": [
-                {
-                    "agentId": agent_id,
-                    "replyMode": (
-                        "mentioned" if agent_id in explicit_set else "automatic"
-                    ),
-                }
-                for agent_id in target_ids
-            ],
-            "warnings": warnings,
-            "version": 1,
-        }
-        encoded = self._canonical_json(plan)
-        if len(encoded.encode("utf-8")) > _MAX_CASCADE_PLAN_BYTES:
-            raise GroupStoreError("Cascade plan exceeds the internal limit")
-        connection.execute(
-            """INSERT INTO group_idempotency
-            (request_id, operation, request_hash, response_json, created_at)
-            VALUES (?, ?, ?, ?, ?)""",
-            (
-                request_id,
-                _CASCADE_PENDING_OPERATION,
-                self._cascade_request_hash(source["id"]),
-                encoded,
-                created_at,
-            ),
-        )
-
-    def _record_host_flow_terminal_plan_if_needed(
-        self,
-        connection: sqlite3.Connection,
-        run: sqlite3.Row,
-        created_at: float,
-    ) -> None:
-        room = connection.execute(
-            "SELECT orchestration_mode, archived FROM group_rooms WHERE id = ?",
-            (run["room_id"],),
-        ).fetchone()
-        agent = connection.execute(
-            "SELECT is_host, enabled FROM group_agents WHERE id = ? AND room_id = ?",
-            (run["agent_id"], run["room_id"]),
-        ).fetchone()
-        if (
-            room is None
-            or room["archived"]
-            or room["orchestration_mode"] != "host"
-            or agent is None
-            or not agent["enabled"]
-            or agent["is_host"]
-        ):
-            return
-        self._record_cascade_plan(
-            connection,
-            source=run,
-            source_message=self._message_row(connection, run["response_message_id"]),
-            created_at=created_at,
-        )
-
-    @classmethod
-    def _plan_cascade_mentions(
-        cls,
-        content: str,
-        agents: list[sqlite3.Row],
-        *,
-        source_agent_id: str,
-        include_automatic: bool = True,
-    ) -> tuple[list[str], list[dict[str, str]]]:
-        searchable = cls._mention_search_text(content)
-        entries: list[tuple[str, int, sqlite3.Row]] = []
-        for agent in agents:
-            aliases = (
-                (agent["id"], 0),
-                (agent["profile"], 1),
-                (agent["display_name"], 2),
-            )
-            seen: set[str] = set()
-            for alias, priority in aliases:
-                key = alias.casefold()
-                if key in seen or is_reserved_mention_alias(key):
-                    continue
-                seen.add(key)
-                entries.append((key, priority, agent))
-        entries.sort(key=lambda item: (-len(item[0]), item[1], item[0], item[2]["id"]))
-        targets: list[str] = []
-        warning_names: list[str] = []
-        index = 0
-        while index < len(searchable):
-            if searchable[index] != "@" or (
-                index > 0 and cls._mention_word_char(searchable[index - 1])
-            ):
-                index += 1
-                continue
-            room_wide_match = next(
-                (
-                    match
-                    for alias in ALL_MENTION_ALIASES
-                    if (match := cls._casefold_prefix(searchable, index + 1, alias))
-                    is not None
-                    and cls._mention_end(searchable, match)
-                ),
-                None,
-            )
-            if room_wide_match is not None:
-                for agent in agents:
-                    if (
-                        agent["enabled"]
-                        and agent["id"] != source_agent_id
-                        and agent["id"] not in targets
-                    ):
-                        targets.append(agent["id"])
-                index = room_wide_match
-                continue
-            matched = False
-            for key, _priority, agent in entries:
-                end = cls._casefold_prefix(searchable, index + 1, key)
-                if end is None or not cls._mention_end(searchable, end):
-                    continue
-                matched = True
-                if not agent["enabled"]:
-                    warning_names.append(f"Agent disabled: {agent['display_name']}")
-                elif agent["id"] != source_agent_id and agent["id"] not in targets:
-                    targets.append(agent["id"])
-                index = end
-                break
-            if matched:
-                continue
-            token = re.match(
-                r"[^\s@,,。!?!?;;::()()\[\]{}]{1,100}",
-                searchable[index + 1 :],
-            )
-            if token is not None:
-                warning_names.append(f"Unknown Mention: @{token.group(0)}")
-                index += 1 + len(token.group(0))
-            else:
-                index += 1
-        if include_automatic and not targets:
-            for agent in agents:
-                if (
-                    agent["enabled"]
-                    and agent["reply_without_mention"]
-                    and agent["id"] != source_agent_id
-                    and agent["id"] not in targets
-                ):
-                    targets.append(agent["id"])
-        warnings = [
-            {"code": "mention", "message": value}
-            for value in list(dict.fromkeys(warning_names))[:MAX_AGENTS_PER_ROOM]
-        ]
-        return targets[:MAX_AGENTS_PER_ROOM], warnings
-
-    @staticmethod
-    def _casefold_prefix(content: str, start: int, expected: str) -> int | None:
-        folded = ""
-        index = start
-        while index < len(content) and len(folded) < len(expected):
-            folded += content[index].casefold()
-            index += 1
-        return index if folded == expected else None
-
-    @staticmethod
-    def _mention_search_text(content: str) -> str:
-        lines = content.splitlines(keepends=True)
-        visible: list[str] = []
-        fence: tuple[str, int] | None = None
-        for line in lines:
-            leading_spaces = len(line) - len(line.lstrip(" "))
-            candidate = line[leading_spaces:] if leading_spaces <= 3 else ""
-            marker_character = (
-                candidate[0]
-                if candidate.startswith("`") or candidate.startswith("~")
-                else None
-            )
-            marker_length = 0
-            if marker_character is not None:
-                while (
-                    marker_length < len(candidate)
-                    and candidate[marker_length] == marker_character
-                ):
-                    marker_length += 1
-            if fence is None and marker_length >= 3:
-                fence = (marker_character, marker_length)
-                continue
-            if fence is not None:
-                fence_character, fence_length = fence
-                remainder = candidate[marker_length:]
-                if (
-                    marker_character == fence_character
-                    and marker_length >= fence_length
-                    and not remainder.strip()
-                ):
-                    fence = None
-                continue
-            visible.append(line)
-        searchable = "".join(visible)
-        inline_visible: list[str] = []
-        for line in searchable.splitlines(keepends=True):
-            index = 0
-            while index < len(line):
-                if line[index] != "`":
-                    inline_visible.append(line[index])
-                    index += 1
-                    continue
-                end = index + 1
-                while end < len(line) and line[end] == "`":
-                    end += 1
-                delimiter = line[index:end]
-                close = line.find(delimiter, end)
-                if close < 0:
-                    if line.endswith("\n"):
-                        inline_visible.append("\n")
-                    break
-                index = close + len(delimiter)
-        searchable = "".join(inline_visible)
-        searchable = re.sub(
-            r"(?:[A-Za-z][A-Za-z0-9+.-]*://|www\.)"
-            r"[^\s,。!?;:()()\[\]{}]+",
-            "",
-            searchable,
-            flags=re.IGNORECASE,
-        )
-        return re.sub(r"\\@", "", searchable)
-
-    @staticmethod
-    def _mention_word_char(value: str) -> bool:
-        return value.isalnum() or value in {"_", ".", "-", "+", "@"}
-
-    @classmethod
-    def _mention_end(cls, value: str, end: int) -> bool:
-        return end >= len(value) or not cls._mention_word_char(value[end])
-
-    def list_pending_cascades(
-        self, *, limit: int = _MAX_CASCADE_PAGE_SIZE, after: int | None = None
-    ) -> dict[str, object]:
-        if (
-            isinstance(limit, bool)
-            or not isinstance(limit, int)
-            or not (1 <= limit <= _MAX_CASCADE_PAGE_SIZE)
-        ):
-            raise ValueError("limit must be between 1 and 32")
-        if after is None:
-            after_value = 0
-        elif isinstance(after, bool) or not isinstance(after, int) or after < 0:
-            raise ValueError("after must be a non-negative integer")
-        else:
-            after_value = after
-        with self.read_transaction() as connection:
-            rows = connection.execute(
-                """SELECT rowid, request_id, operation, request_hash, response_json
-                FROM group_idempotency
-                WHERE operation = ? AND rowid > ?
-                ORDER BY rowid ASC LIMIT ?""",
-                (_CASCADE_PENDING_OPERATION, after_value, limit + 1),
-            ).fetchall()
-        validated = [
-            (int(row["rowid"]), self._cascade_plan_from_ledger(row)) for row in rows
-        ]
-        has_more = len(validated) > limit
-        validated = validated[:limit]
-        items = [{"sourceRunId": plan["sourceRunId"]} for _rowid, plan in validated]
-        return {
-            "items": items,
-            "nextCursor": (validated[-1][0] if has_more and validated else None),
-        }
-
-    def _cascade_plan_from_ledger(
-        self, ledger: Mapping[str, object]
-    ) -> dict[str, object]:
-        try:
-            request_id = ledger["request_id"]
-            operation = ledger["operation"]
-            request_hash = ledger["request_hash"]
-            encoded = ledger["response_json"]
-        except (KeyError, IndexError, TypeError) as error:
-            raise GroupStoreError("Stored cascade ledger is corrupt") from error
-        prefix = "internal:cascade:"
-        if (
-            not isinstance(request_id, str)
-            or not request_id.startswith(prefix)
-            or operation != _CASCADE_PENDING_OPERATION
-            or not isinstance(encoded, str)
-            or len(encoded.encode("utf-8")) > _MAX_CASCADE_PLAN_BYTES
-        ):
-            raise GroupStoreError("Stored cascade ledger is corrupt")
-        raw_source_id = request_id[len(prefix) :]
-        try:
-            source_id = self._canonical_uuid(raw_source_id, "sourceRunId")
-        except ValueError as error:
-            raise GroupStoreError("Stored cascade ledger is corrupt") from error
-        if raw_source_id != source_id:
-            raise GroupStoreError("Stored cascade ledger is corrupt")
-        try:
-            plan = self._load_json(encoded)
-        except (TypeError, ValueError, json.JSONDecodeError) as error:
-            raise GroupStoreError("Stored cascade plan is corrupt") from error
-        if not isinstance(plan, dict) or self._canonical_json(plan) != encoded:
-            raise GroupStoreError("Stored cascade plan is corrupt")
-        parse_version = plan.get("parseVersion")
-        if (
-            parse_version not in {1, 2, 3}
-            or request_hash
-            != self._cascade_request_hash(source_id, parse_version=parse_version)
-        ):
-            raise GroupStoreError("Stored cascade ledger is corrupt")
-        common_invalid = (
-            plan.get("state") != "pending"
-            or plan.get("version") != 1
-            or plan.get("sourceRunId") != source_id
-            or not isinstance(plan.get("warnings"), list)
-            or not all(isinstance(item, dict) for item in plan["warnings"])
-            or len(plan["warnings"]) > MAX_AGENTS_PER_ROOM
-        )
-        if common_invalid:
-            raise GroupStoreError("Stored cascade plan is corrupt")
-        if parse_version == 1:
-            expected_keys = {
-                "parseVersion",
-                "sourceMessageId",
-                "sourceRunId",
-                "state",
-                "targetAgentIds",
-                "version",
-                "warnings",
-            }
-            target_ids = plan.get("targetAgentIds")
-            if (
-                set(plan) != expected_keys
-                or not isinstance(target_ids, list)
-                or not all(isinstance(item, str) for item in target_ids)
-            ):
-                raise GroupStoreError("Stored cascade plan is corrupt")
-            targets = [
-                {"agentId": item, "replyMode": "mentioned"} for item in target_ids
-            ]
-        else:
-            expected_keys = {
-                "parseVersion",
-                "sourceMessageId",
-                "sourceRunId",
-                "state",
-                "targets",
-                "version",
-                "warnings",
-            }
-            targets = plan.get("targets")
-            if (
-                set(plan) != expected_keys
-                or not isinstance(targets, list)
-                or not all(isinstance(item, dict) for item in targets)
-            ):
-                raise GroupStoreError("Stored cascade plan is corrupt")
-        if (
-            len(targets) > MAX_AGENTS_PER_ROOM
-            or any(set(item) != {"agentId", "replyMode"} for item in targets)
-            or any(not isinstance(item.get("agentId"), str) for item in targets)
-            or any(item.get("replyMode") not in {"mentioned", "automatic"} for item in targets)
-            or len({item.get("agentId") for item in targets}) != len(targets)
-        ):
-            raise GroupStoreError("Stored cascade plan is corrupt")
-        try:
-            if (
-                self._canonical_uuid(plan["sourceMessageId"], "sourceMessageId")
-                != plan["sourceMessageId"]
-            ):
-                raise ValueError
-            for target in targets:
-                if (
-                    self._canonical_uuid(target["agentId"], "targetAgentId")
-                    != target["agentId"]
-                ):
-                    raise ValueError
-            for warning in plan["warnings"]:
-                if set(warning) != {"code", "message"} or warning.get("code") != "mention":
-                    raise ValueError
-                self._message_text(
-                    warning.get("message"),
-                    "warning.message",
-                    max_bytes=MAX_MESSAGE_BYTES,
-                    nonblank=True,
-                )
-        except (KeyError, TypeError, ValueError) as error:
-            raise GroupStoreError("Stored cascade plan is corrupt") from error
-        return {
-            "parseVersion": parse_version,
-            "sourceMessageId": plan["sourceMessageId"],
-            "sourceRunId": source_id,
-            "state": "pending",
-            "targets": targets,
-            "version": 1,
-            "warnings": plan["warnings"],
-        }
-
-    def enqueue_cascade_runs(
-        self,
-        source_run_id: str,
-        *,
-        agent_ids: list[str],
-        warnings: list[Mapping[str, object]],
-    ) -> dict[str, object]:
-        """Create bounded, deduplicated Agent cascades and visible warnings."""
-        canonical_source_id = self._canonical_uuid(source_run_id, "sourceRunId")
-        canonical_agent_ids, requested_warnings = self._validated_cascade_inputs(
-            agent_ids, warnings
-        )
-        with self.write_transaction() as connection:
-            source = self._run_row(connection, canonical_source_id)
-            self._active_room(connection, source["room_id"])
-            self._enabled_agent(connection, source["room_id"], source["agent_id"])
-            if source["status"] != "completed":
-                raise GroupConflictError("Cascade source run must be completed")
-            source_message = self._message_row(
-                connection, source["response_message_id"]
-            )
-            if source_message["status"] != "completed":
-                raise GroupConflictError("Cascade source message must be completed")
-            return self._enqueue_cascade_runs_transaction(
-                connection,
-                source=source,
-                canonical_agent_ids=canonical_agent_ids,
-                requested_warnings=requested_warnings,
-                now=self._now(),
-            )
-
-    def _validated_cascade_inputs(
-        self,
-        agent_ids: object,
-        warnings: object,
-    ) -> tuple[list[str], list[str]]:
-        if not isinstance(agent_ids, list):
-            raise ValueError("agent_ids must be a list")
-        if len(agent_ids) > MAX_AGENTS_PER_ROOM:
-            raise ValueError(
-                f"agent_ids must contain at most {MAX_AGENTS_PER_ROOM} entries"
-            )
-        canonical_agent_ids: list[str] = []
-        seen_agent_ids: set[str] = set()
-        for value in agent_ids:
-            agent_id = self._canonical_uuid(value, "agentId")
-            if agent_id not in seen_agent_ids:
-                seen_agent_ids.add(agent_id)
-                canonical_agent_ids.append(agent_id)
-        if not isinstance(warnings, list):
-            raise ValueError("warnings must be a list of objects")
-        if len(warnings) > MAX_AGENTS_PER_ROOM:
-            raise ValueError(
-                f"warnings must contain at most {MAX_AGENTS_PER_ROOM} entries"
-            )
-        if not all(isinstance(item, Mapping) for item in warnings):
-            raise ValueError("warnings must be a list of objects")
-        warnings_json = self._strict_json(
-            [dict(warning) for warning in warnings], "warnings"
-        )
-        if len(warnings_json.encode("utf-8")) > MAX_MESSAGE_BYTES:
-            raise ValueError("warnings exceed maximum size")
-        requested_warnings: list[str] = []
-        for warning in warnings:
-            message = warning.get("message")
-            requested_warnings.append(
-                self._message_text(
-                    message,
-                    "warning.message",
-                    max_bytes=MAX_MESSAGE_BYTES,
-                    nonblank=True,
-                )
-            )
-        return canonical_agent_ids, requested_warnings
-
-    def complete_cascade(self, source_run_id: str) -> dict[str, object]:
-        """Execute one frozen Mention plan exactly once and terminalize it."""
-        canonical_source_id = self._canonical_uuid(source_run_id, "sourceRunId")
-        request_id = self._cascade_request_id(canonical_source_id)
-        expected_hashes = {
-            self._cascade_request_hash(canonical_source_id, parse_version=1),
-            self._cascade_request_hash(canonical_source_id, parse_version=2),
-            self._cascade_request_hash(canonical_source_id, parse_version=3),
-        }
-        with self.write_transaction() as connection:
-            ledger = connection.execute(
-                """SELECT request_id, operation, request_hash, response_json
-                FROM group_idempotency WHERE request_id = ?""",
-                (request_id,),
-            ).fetchone()
-            if ledger is None:
-                raise GroupNotFoundError("Cascade source not found")
-            if (
-                ledger["operation"] not in _CASCADE_OPERATIONS
-                or ledger["request_hash"] not in expected_hashes
-            ):
-                raise GroupStoreError("Stored cascade ledger is corrupt")
-            if ledger["operation"] != _CASCADE_PENDING_OPERATION:
-                return self._cascade_result(
-                    ledger["response_json"], ledger["operation"]
-                )
-            plan = self._cascade_plan_from_ledger(ledger)
-            source = connection.execute(
-                "SELECT * FROM group_agent_runs WHERE id = ?",
-                (canonical_source_id,),
-            ).fetchone()
-            if source is None:
-                raise GroupStoreError("Stored cascade source is missing")
-            room = connection.execute(
-                "SELECT archived, orchestration_mode FROM group_rooms WHERE id = ?",
-                (source["room_id"],),
-            ).fetchone()
-            source_agent = connection.execute(
-                "SELECT enabled, is_host FROM group_agents WHERE id = ? AND room_id = ?",
-                (source["agent_id"], source["room_id"]),
-            ).fetchone()
-            if room is None:
-                raise GroupStoreError("Stored cascade ownership is corrupt")
-            source_message = self._message_row(
-                connection, source["response_message_id"]
-            )
-            host_flow_member_terminal = (
-                room["orchestration_mode"] == "host"
-                and source_agent is not None
-                and not source_agent["is_host"]
-                and source["status"] in {"completed", "failed", "interrupted"}
-            )
-            if source["status"] != "completed" and not host_flow_member_terminal:
-                raise GroupStoreError("Stored cascade source is not terminal")
-            if source_message["id"] != plan["sourceMessageId"]:
-                raise GroupStoreError("Stored cascade message is corrupt")
-            self._validate_run_message_status(
-                str(source["status"]), str(source_message["status"])
-            )
-            if room["archived"] or source_agent is None or not source_agent["enabled"]:
-                result = self._cascade_summary([], [], state="discarded")
-                connection.execute(
-                    """UPDATE group_idempotency
-                    SET operation = ?, response_json = ? WHERE request_id = ?""",
-                    (
-                        _CASCADE_DISCARDED_OPERATION,
-                        self._canonical_json(result),
-                        request_id,
-                    ),
-                )
-                return result
-            try:
-                canonical_ids, warning_texts = self._validated_cascade_inputs(
-                    [target["agentId"] for target in plan["targets"]],
-                    plan["warnings"],
-                )
-                reply_modes = {
-                    target["agentId"]: target["replyMode"]
-                    for target in plan["targets"]
-                }
-            except ValueError as error:
-                raise GroupStoreError("Stored cascade plan is corrupt") from error
-            created = self._enqueue_cascade_runs_transaction(
-                connection,
-                source=source,
-                canonical_agent_ids=canonical_ids,
-                requested_warnings=warning_texts,
-                reply_modes=reply_modes,
-                now=self._now(),
-            )
-            result = self._cascade_summary(
-                created["runs"], created["systemMessages"], state="completed"
-            )
-            connection.execute(
-                """UPDATE group_idempotency
-                SET operation = ?, response_json = ? WHERE request_id = ?""",
-                (
-                    _CASCADE_COMPLETED_OPERATION,
-                    self._canonical_json(result),
-                    request_id,
-                ),
-            )
-            return result
-
-    @classmethod
-    def _cascade_result(cls, encoded: object, operation: str) -> dict[str, object]:
-        try:
-            result = cls._load_json(encoded)
-        except (TypeError, ValueError, json.JSONDecodeError) as error:
-            raise GroupStoreError("Stored cascade result is corrupt") from error
-        expected_state = (
-            "completed" if operation == _CASCADE_COMPLETED_OPERATION else "discarded"
-        )
-        expected_keys = {
-            "runCount",
-            "runIds",
-            "state",
-            "systemMessageCount",
-            "systemMessageIds",
-        }
-        if expected_state == "discarded":
-            expected_keys.add("discarded")
-        if (
-            not isinstance(result, dict)
-            or cls._canonical_json(result) != encoded
-            or set(result) != expected_keys
-            or result.get("state") != expected_state
-            or not isinstance(result.get("runIds"), list)
-            or not all(isinstance(item, str) for item in result["runIds"])
-            or len(result["runIds"]) > MAX_AGENTS_PER_ROOM
-            or len(result["runIds"]) != len(set(result["runIds"]))
-            or type(result.get("runCount")) is not int
-            or result.get("runCount") != len(result["runIds"])
-            or not isinstance(result.get("systemMessageIds"), list)
-            or not all(isinstance(item, str) for item in result["systemMessageIds"])
-            or len(result["systemMessageIds"]) > MAX_AGENTS_PER_ROOM
-            or len(result["systemMessageIds"]) != len(set(result["systemMessageIds"]))
-            or type(result.get("systemMessageCount")) is not int
-            or result.get("systemMessageCount") != len(result["systemMessageIds"])
-            or (expected_state == "discarded") != (result.get("discarded") is True)
-        ):
-            raise GroupStoreError("Stored cascade result is corrupt")
-        try:
-            if any(
-                cls._canonical_uuid(item, "runId") != item for item in result["runIds"]
-            ) or any(
-                cls._canonical_uuid(item, "messageId") != item
-                for item in result["systemMessageIds"]
-            ):
-                raise ValueError
-        except ValueError as error:
-            raise GroupStoreError("Stored cascade result is corrupt") from error
-        return result
-
-    @staticmethod
-    def _cascade_summary(
-        runs: list[Mapping[str, object]],
-        messages: list[Mapping[str, object]],
-        *,
-        state: str,
-    ) -> dict[str, object]:
-        result: dict[str, object] = {
-            "runCount": len(runs),
-            "runIds": [run["id"] for run in runs],
-            "state": state,
-            "systemMessageCount": len(messages),
-            "systemMessageIds": [message["id"] for message in messages],
-        }
-        if state == "discarded":
-            result["discarded"] = True
-        return result
-
-    def _enqueue_cascade_runs_transaction(
-        self,
-        connection: sqlite3.Connection,
-        *,
-        source: sqlite3.Row,
-        canonical_agent_ids: list[str],
-        requested_warnings: list[str],
-        now: float,
-        reply_modes: Mapping[str, str] | None = None,
-    ) -> dict[str, list[dict[str, object]]]:
-        room = self._active_room(connection, source["room_id"])
-        room_agents = connection.execute(
-            """SELECT * FROM group_agents WHERE room_id = ?
-            ORDER BY created_at ASC, id ASC""",
-            (source["room_id"],),
-        ).fetchall()
-        agents_by_id = {agent["id"]: agent for agent in room_agents}
-        warning_texts = list(requested_warnings)
-        source_agent = agents_by_id.get(source["agent_id"])
-        if source_agent is None:
-            raise GroupStoreError("Cascade source Agent is missing")
-        host_review = (
-            room["orchestration_mode"] == "host" and not source_agent["is_host"]
-        )
-        next_depth = int(source["depth"]) + (0 if host_review else 1)
-        max_reply_rounds = int(room["max_reply_rounds"])
-        if max_reply_rounds != -1 and next_depth >= max_reply_rounds:
-            warning_texts.append("Cascade depth limit reached")
-            canonical_agent_ids = []
-        source_message = self._message_row(connection, source["response_message_id"])
-        trigger_message_id = str(source["response_message_id"])
-        if host_review:
-            current_host = next(
-                (agent for agent in room_agents if agent["is_host"] and agent["enabled"]),
-                None,
-            )
-            if current_host is None:
-                raise GroupStoreError("Administrator flow has no enabled administrator Agent")
-            canonical_agent_ids = [str(current_host["id"])]
-            reply_modes = {str(current_host["id"]): "automatic"}
-            unfinished_sibling = connection.execute(
-                """SELECT 1 FROM group_agent_runs
-                WHERE topic_id = ? AND root_message_id = ? AND depth = ?
-                  AND trigger_message_id = ? AND id != ?
-                  AND status NOT IN ('completed', 'failed', 'interrupted')
-                LIMIT 1""",
-                (
-                    source["topic_id"],
-                    source["root_message_id"],
-                    source["depth"],
-                    source["trigger_message_id"],
-                    source["id"],
-                ),
-            ).fetchone()
-            if unfinished_sibling is not None:
-                return {"runs": [], "systemMessages": []}
-            existing_review = connection.execute(
-                """SELECT 1 FROM group_agent_runs
-                WHERE topic_id = ? AND root_message_id = ? AND depth = ?
-                  AND agent_id = ? LIMIT 1""",
-                (
-                    source["topic_id"],
-                    source["root_message_id"],
-                    next_depth,
-                    current_host["id"],
-                ),
-            ).fetchone()
-            if existing_review is not None:
-                return {"runs": [], "systemMessages": []}
-            barrier = connection.execute(
-                """SELECT id FROM group_messages
-                WHERE room_id = ? AND topic_id = ? AND root_message_id = ?
-                  AND reply_to_message_id = ? AND sender_kind = 'system'
-                  AND visible = 0 AND content = ? AND status = 'completed'
-                ORDER BY seq ASC LIMIT 1""",
-                (
-                    source["room_id"],
-                    source["topic_id"],
-                    source["root_message_id"],
-                    source["trigger_message_id"],
-                    _HOST_FLOW_BARRIER_CONTENT,
-                ),
-            ).fetchone()
-            if barrier is None:
-                barrier_id = str(uuid.uuid4())
-                connection.execute(
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                     root_message_id, reply_to_message_id, client_message_id,
-                     content, reasoning, tool_state_json, status, error, visible,
-                     created_at, updated_at)
-                    VALUES (?, ?, ?, 'system', 'system', '系统', ?, ?, NULL,
-                            ?, '', '[]', 'completed', '', 0, ?, ?)""",
-                    (
-                        barrier_id,
-                        source["room_id"],
-                        source["topic_id"],
-                        source["root_message_id"],
-                        source["trigger_message_id"],
-                        _HOST_FLOW_BARRIER_CONTENT,
-                        now,
-                        now,
-                    ),
-                )
-                trigger_message_id = barrier_id
-            else:
-                trigger_message_id = str(barrier["id"])
-        explicit_ids, _ = self._plan_cascade_mentions(
-            source_message["content"],
-            room_agents,
-            source_agent_id=source["agent_id"],
-            include_automatic=False,
-        )
-        explicit_set = set(explicit_ids)
-        created_runs: list[dict[str, object]] = []
-        for agent_id in canonical_agent_ids:
-            agent = agents_by_id.get(agent_id)
-            if agent is None:
-                warning_texts.append(f"Unknown Agent: {agent_id}")
-                continue
-            if not agent["enabled"]:
-                warning_texts.append(f"Agent disabled: {agent['display_name']}")
-                continue
-            duplicate = connection.execute(
-                """SELECT 1 FROM group_agent_runs
-                WHERE room_id = ? AND topic_id = ? AND root_message_id = ?
-                  AND agent_id = ? AND depth = ? LIMIT 1""",
-                (
-                    source["room_id"],
-                    source["topic_id"],
-                    source["root_message_id"],
-                    agent_id,
-                    next_depth,
-                ),
-            ).fetchone()
-            if duplicate is not None:
-                continue
-            reply_mode = (
-                reply_modes.get(agent_id, "mentioned")
-                if reply_modes is not None
-                else ("mentioned" if agent_id in explicit_set else "automatic")
-            )
-            if reply_mode not in {"mentioned", "automatic"}:
-                raise GroupStoreError("Stored cascade plan is corrupt")
-            required_reply = bool(host_review and agent["is_host"])
-            visible = reply_mode == "mentioned" or required_reply
-            response_id = str(uuid.uuid4())
-            run_id = str(uuid.uuid4())
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                 root_message_id, reply_to_message_id, client_message_id,
-                 content, reasoning, tool_state_json, status, error, visible,
-                 created_at, updated_at)
-                VALUES (?, ?, ?, 'agent', ?, ?, ?, ?, NULL,
-                        '', '', '[]', 'queued', '', ?, ?, ?)""",
-                (
-                    response_id,
-                    source["room_id"],
-                    source["topic_id"],
-                    agent_id,
-                    agent["display_name"],
-                    source["root_message_id"],
-                    trigger_message_id,
-                    int(visible),
-                    now,
-                    now,
-                ),
-            )
-            connection.execute(
-                """INSERT INTO group_agent_runs
-                (id, room_id, topic_id, agent_id, trigger_message_id,
-                 response_message_id, root_message_id, depth, reply_mode,
-                 required_reply, status, runtime_session_id, requested_model,
-                 requested_provider, requested_reasoning_effort,
-                 requested_fast_mode, actual_model, actual_provider,
-                 actual_reasoning_effort, actual_fast_mode, error, created_at,
-                 updated_at)
-                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL,
-                        ?, ?, ?, ?, NULL, NULL, NULL, NULL, '', ?, ?)""",
-                (
-                    run_id,
-                    source["room_id"],
-                    source["topic_id"],
-                    agent_id,
-                    trigger_message_id,
-                    response_id,
-                    source["root_message_id"],
-                    next_depth,
-                    reply_mode,
-                    int(required_reply),
-                    agent["model_override"],
-                    agent["provider_override"],
-                    agent["reasoning_effort_override"],
-                    agent["fast_mode_override"],
-                    now,
-                    now,
-                ),
-            )
-            message = self._message_wire(self._message_row(connection, response_id))
-            run = self._run_wire(self._run_row(connection, run_id))
-            if visible:
-                self._append_event(
-                    connection,
-                    source["room_id"],
-                    "message.upsert",
-                    message,
-                    created_at=now,
-                )
-            self._append_event(
-                connection,
-                source["room_id"],
-                "run.updated",
-                run,
-                created_at=now,
-            )
-            created_runs.append(run)
-        if (
-            room["orchestration_mode"] == "host"
-            and source_agent["is_host"]
-            and created_runs
-        ):
-            barrier_id = str(uuid.uuid4())
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                 root_message_id, reply_to_message_id, client_message_id,
-                 content, reasoning, tool_state_json, status, error, visible,
-                 created_at, updated_at)
-                VALUES (?, ?, ?, 'system', 'system', '系统', ?, ?, NULL,
-                        ?, '', '[]', 'completed', '', 0, ?, ?)""",
-                (
-                    barrier_id,
-                    source["room_id"],
-                    source["topic_id"],
-                    source["root_message_id"],
-                    source["response_message_id"],
-                    _HOST_FLOW_BARRIER_CONTENT,
-                    now,
-                    now,
-                ),
-            )
-        system_messages: list[dict[str, object]] = []
-        for warning_text in list(dict.fromkeys(warning_texts))[:MAX_AGENTS_PER_ROOM]:
-            duplicate = connection.execute(
-                """SELECT * FROM group_messages
-                WHERE room_id = ? AND topic_id = ? AND sender_kind = 'system'
-                  AND root_message_id = ? AND reply_to_message_id = ?
-                  AND content = ? AND status = 'completed'
-                ORDER BY seq ASC LIMIT 1""",
-                (
-                    source["room_id"],
-                    source["topic_id"],
-                    source["root_message_id"],
-                    source["response_message_id"],
-                    warning_text,
-                ),
-            ).fetchone()
-            if duplicate is not None:
-                continue
-            message_id = str(uuid.uuid4())
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                 root_message_id, reply_to_message_id, client_message_id,
-                 content, reasoning, tool_state_json, status, error,
-                 created_at, updated_at)
-                VALUES (?, ?, ?, 'system', 'system', '系统', ?, ?, NULL,
-                        ?, '', '[]', 'completed', '', ?, ?)""",
-                (
-                    message_id,
-                    source["room_id"],
-                    source["topic_id"],
-                    source["root_message_id"],
-                    source["response_message_id"],
-                    warning_text,
-                    now,
-                    now,
-                ),
-            )
-            message = self._message_wire(self._message_row(connection, message_id))
-            self._append_event(
-                connection,
-                source["room_id"],
-                "message.upsert",
-                message,
-                created_at=now,
-            )
-            system_messages.append(message)
-        return {"runs": created_runs, "systemMessages": system_messages}
-
-    def upsert_agent_message(
-        self,
-        run_id: str,
-        *,
-        content: str,
-        reasoning: str,
-        tool_state: object,
-        status: str,
-        error: str = "",
-        publish: bool = True,
-    ) -> dict[str, object]:
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        content = self._message_text(content, "content", max_bytes=MAX_MESSAGE_BYTES)
-        reasoning = self._message_text(
-            reasoning, "reasoning", max_bytes=MAX_MESSAGE_BYTES
-        )
-        error = self._message_text(error, "error", max_bytes=4096)
-        if not isinstance(status, str) or status not in _MESSAGE_STATUSES:
-            raise ValueError("status is invalid")
-        tool_json = self._tool_state_json(tool_state)
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            self._active_room(connection, run["room_id"])
-            self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            if (
-                response["room_id"] != run["room_id"]
-                or response["sender_id"] != run["agent_id"]
-            ):
-                raise GroupStoreError("Run response message is corrupt")
-            self._validate_run_message_state(run, response)
-            if status not in _AGENT_MESSAGE_STATUSES_BY_RUN[run["status"]]:
-                raise GroupConflictError("Message status is invalid for run state")
-            if status not in _AGENT_MESSAGE_TRANSITIONS.get(
-                response["status"], frozenset()
-            ):
-                raise GroupConflictError("Message status cannot move backwards")
-            now = self._now()
-            visible = bool(response["visible"]) or publish
-            connection.execute(
-                """UPDATE group_messages SET content = ?, reasoning = ?, tool_state_json = ?,
-                status = ?, error = ?, visible = ?, updated_at = ? WHERE id = ?""",
-                (
-                    content,
-                    reasoning,
-                    tool_json,
-                    status,
-                    error,
-                    int(visible),
-                    now,
-                    run["response_message_id"],
-                ),
-            )
-            message = self._message_wire(
-                self._message_row(connection, run["response_message_id"])
-            )
-            if visible:
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "message.upsert",
-                    message,
-                    created_at=now,
-                )
-            return message
-
-    def transition_run(
-        self,
-        run_id: str,
-        status: str,
-        *,
-        runtime_session_id: object = UNSET,
-        error: object = UNSET,
-    ) -> dict[str, object]:
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        if not isinstance(status, str) or status not in RUN_TRANSITIONS:
-            raise ValueError("status is invalid")
-        runtime_value = (
-            self._runtime_session_id(runtime_session_id)
-            if runtime_session_id is not UNSET
-            else UNSET
-        )
-        error_value = (
-            self._message_text(error, "error", max_bytes=4096)
-            if error is not UNSET
-            else UNSET
-        )
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            room = self._active_room(connection, run["room_id"])
-            agent = self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            if (
-                response["room_id"] != run["room_id"]
-                or response["sender_id"] != run["agent_id"]
-            ):
-                raise GroupStoreError("Run response message is corrupt")
-            self._validate_run_message_state(run, response)
-            if status == run["status"]:
-                if status == "running":
-                    if (
-                        runtime_value is not UNSET
-                        and runtime_value is not None
-                        and run["runtime_session_id"] is not None
-                        and runtime_value == run["runtime_session_id"]
-                    ):
-                        return self._run_wire(run)
-                    raise GroupConflictError("Run is already claimed")
-                return self._run_wire(run)
-            if status not in RUN_TRANSITIONS[run["status"]]:
-                raise GroupConflictError("Illegal run status transition")
-            if status == "completed" and response["status"] != "completed":
-                raise GroupConflictError("Response message must be completed first")
-            if status not in {"failed", "interrupted"}:
-                self._validate_run_message_status(status, response["status"])
-            now = self._now()
-            if status in {"completed", "failed", "interrupted"}:
-                self._cancel_pending_interactions(connection, run, now)
-            result = self._update_run(
-                connection, run, status, now, runtime_value, error_value
-            )
-            if status in {"completed", "failed", "interrupted"}:
-                self._fail_claimed_interaction_ledgers(
-                    connection,
-                    run_id=run["id"],
-                    reason=result["error"] or f"Run {status}",
-                    runtime_session_ids=(
-                        []
-                        if run["runtime_session_id"] is None
-                        else [run["runtime_session_id"]]
-                    ),
-                    run=result,
-                )
-            self._append_event(
-                connection, result["roomId"], "run.updated", result, created_at=now
-            )
-            if status in {"failed", "interrupted"}:
-                if response["status"] == "completed":
-                    self._validate_run_message_status(status, response["status"])
-                else:
-                    terminal_error = result["error"]
-                    connection.execute(
-                        """UPDATE group_messages
-                        SET status = ?, error = ?, updated_at = ? WHERE id = ?""",
-                        (status, terminal_error, now, run["response_message_id"]),
-                    )
-                    message = self._message_wire(
-                        self._message_row(connection, run["response_message_id"])
-                    )
-                    self._validate_run_message_status(
-                        result["status"], message["status"]
-                    )
-                    if message["visible"]:
-                        self._append_event(
-                            connection,
-                            result["roomId"],
-                            "message.upsert",
-                            message,
-                            created_at=now,
-                        )
-            if status == "completed" or (
-                room["orchestration_mode"] == "host" and not agent["is_host"]
-            ):
-                self._record_cascade_plan(
-                    connection,
-                    source=self._run_row(connection, run["id"]),
-                    source_message=self._message_row(
-                        connection, run["response_message_id"]
-                    ),
-                    created_at=now,
-                )
-            return result
-
-    def bind_run_runtime(
-        self, run_id: str, runtime_session_id: str
-    ) -> dict[str, object]:
-        """Bind the first real runtime identity without reopening the run claim."""
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        runtime_value = self._runtime_session_id(runtime_session_id)
-        if runtime_value is None:
-            raise ValueError("runtimeSessionId is invalid")
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            self._active_room(connection, run["room_id"])
-            self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            self._validate_run_message_state(run, response)
-            if run["status"] not in {"running", "awaiting_input"}:
-                raise GroupConflictError("Run does not accept a runtime binding")
-            if run["runtime_session_id"] == runtime_value:
-                return self._run_wire(run)
-            if run["runtime_session_id"] is not None:
-                raise GroupConflictError("Run runtime is already bound")
-            self._require_available_runtime(connection, runtime_value, canonical_run_id)
-            now = self._now()
-            result = self._update_run(
-                connection, run, run["status"], now, runtime_value, UNSET
-            )
-            self._append_event(
-                connection, run["room_id"], "run.updated", result, created_at=now
-            )
-            return result
-
-    def create_interaction(
-        self,
-        interaction_id: str,
-        run_id: str,
-        *,
-        kind: str,
-        payload: object,
-    ) -> dict[str, object]:
-        return self._create_gateway_interaction(
-            run_id,
-            kind=kind,
-            gateway_interaction_id=interaction_id,
-            payload=payload,
-            allow_awaiting=False,
-        )
-
-    def create_gateway_interaction(
-        self,
-        run_id: str,
-        *,
-        kind: str,
-        gateway_interaction_id: str | None,
-        payload: object,
-    ) -> dict[str, object]:
-        return self._create_gateway_interaction(
-            run_id,
-            kind=kind,
-            gateway_interaction_id=gateway_interaction_id,
-            payload=payload,
-            allow_awaiting=True,
-        )
-
-    def _create_gateway_interaction(
-        self,
-        run_id: str,
-        *,
-        kind: str,
-        gateway_interaction_id: str | None,
-        payload: object,
-        allow_awaiting: bool,
-    ) -> dict[str, object]:
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        if not isinstance(kind, str) or kind not in _INTERACTION_KINDS:
-            raise ValueError("kind is invalid")
-        payload_json = self._json_object(payload, "payload")
-        payload_value = self._load_json(payload_json)
-        clarification_gateway_id: str | None = None
-        if kind == "approval" and gateway_interaction_id is None:
-            interaction_id = f"approval-{uuid.uuid4()}"
-        elif gateway_interaction_id is None:
-            raise ValueError("Gateway clarification interactionId is required")
-        else:
-            gateway_id = self._interaction_id(gateway_interaction_id)
-            if kind == "clarification" and allow_awaiting:
-                if "gatewayRequestId" in payload_value:
-                    raise ValueError("payload.gatewayRequestId is reserved")
-                payload_value["gatewayRequestId"] = gateway_id
-                payload_json = self._json_object(payload_value, "payload")
-                clarification_gateway_id = gateway_id
-                interaction_id = None
-            else:
-                interaction_id = gateway_id
-        try:
-            with self.write_transaction() as connection:
-                run = self._run_row(connection, canonical_run_id)
-                self._active_room(connection, run["room_id"])
-                self._enabled_agent(connection, run["room_id"], run["agent_id"])
-                response = self._message_row(connection, run["response_message_id"])
-                self._validate_run_message_state(run, response)
-                accepted_statuses = (
-                    {"running", "awaiting_input"} if allow_awaiting else {"running"}
-                )
-                if run["status"] not in accepted_statuses:
-                    raise GroupConflictError("Interaction requires a running run")
-                self._validate_run_message_status("awaiting_input", response["status"])
-                if clarification_gateway_id is not None:
-                    pending = connection.execute(
-                        """SELECT * FROM group_interactions
-                        WHERE run_id = ? AND kind = 'clarification'
-                          AND status = 'pending' ORDER BY rowid ASC""",
-                        (canonical_run_id,),
-                    ).fetchall()
-                    matching = []
-                    for candidate in pending:
-                        candidate_wire = self._interaction_wire(candidate)
-                        if (
-                            candidate_wire["payload"].get("gatewayRequestId")
-                            == clarification_gateway_id
-                        ):
-                            matching.append(candidate)
-                    if len(matching) > 1:
-                        raise GroupStoreError(
-                            "Stored clarification identities are not unique"
-                        )
-                    if matching:
-                        existing = matching[0]
-                        if existing["payload_json"] != payload_json:
-                            raise GroupConflictError("Interaction already exists")
-                        return self._interaction_wire(existing)
-                    interaction_id = f"clarification-{uuid.uuid4()}"
-                if interaction_id is None:
-                    raise GroupStoreError("Interaction identity is missing")
-                existing = connection.execute(
-                    "SELECT * FROM group_interactions WHERE id = ?",
-                    (interaction_id,),
-                ).fetchone()
-                if existing is not None:
-                    if (
-                        existing["room_id"] != run["room_id"]
-                        or existing["agent_id"] != run["agent_id"]
-                        or existing["run_id"] != canonical_run_id
-                        or existing["kind"] != kind
-                        or existing["payload_json"] != payload_json
-                    ):
-                        raise GroupConflictError("Interaction already exists")
-                    return self._interaction_wire(existing)
-                now = self._now()
-                connection.execute(
-                    """INSERT INTO group_interactions
-                    (id, room_id, topic_id, agent_id, run_id, kind, payload_json, status, created_at, resolved_at)
-                    VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL)""",
-                    (
-                        interaction_id,
-                        run["room_id"],
-                        run["topic_id"],
-                        run["agent_id"],
-                        canonical_run_id,
-                        kind,
-                        payload_json,
-                        now,
-                    ),
-                )
-                interaction = self._interaction_wire(
-                    self._interaction_row(connection, interaction_id)
-                )
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "interaction.requested",
-                    interaction,
-                    created_at=now,
-                )
-                if run["status"] == "running":
-                    changed = self._update_run(
-                        connection, run, "awaiting_input", now, UNSET, UNSET
-                    )
-                    self._append_event(
-                        connection,
-                        run["room_id"],
-                        "run.updated",
-                        changed,
-                        created_at=now,
-                    )
-                return interaction
-        except sqlite3.IntegrityError as error:
-            if "group_interactions.id" in str(error):
-                raise GroupConflictError("Interaction already exists") from error
-            raise self._integrity_conflict(error) from error
-
-    def resolve_interaction(
-        self, interaction_id: str, *, status: str = "resolved"
-    ) -> dict[str, object]:
-        interaction_id = self._interaction_id(interaction_id)
-        if not isinstance(status, str) or status not in _INTERACTION_TERMINAL_STATUSES:
-            raise ValueError("status must be resolved or cancelled")
-        with self.write_transaction() as connection:
-            interaction = self._interaction_row(connection, interaction_id)
-            if interaction["status"] != "pending":
-                raise GroupConflictError("Interaction is already resolved")
-            run = self._run_row(connection, interaction["run_id"])
-            self._active_room(connection, run["room_id"])
-            self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            self._validate_run_message_state(run, response)
-            now = self._now()
-            connection.execute(
-                "UPDATE group_interactions SET status = ?, resolved_at = ? WHERE id = ?",
-                (status, now, interaction_id),
-            )
-            result = self._interaction_wire(
-                self._interaction_row(connection, interaction_id)
-            )
-            self._append_event(
-                connection,
-                result["roomId"],
-                "interaction.resolved",
-                result,
-                created_at=now,
-            )
-            if status == "resolved":
-                if run["status"] != "awaiting_input":
-                    raise GroupConflictError("Interaction run is not awaiting input")
-                remaining = connection.execute(
-                    """SELECT 1 FROM group_interactions
-                    WHERE run_id = ? AND status = 'pending' LIMIT 1""",
-                    (run["id"],),
-                ).fetchone()
-                if remaining is None:
-                    self._validate_run_message_status("running", response["status"])
-                    changed = self._update_run(
-                        connection, run, "running", now, UNSET, UNSET
-                    )
-                    self._append_event(
-                        connection,
-                        changed["roomId"],
-                        "run.updated",
-                        changed,
-                        created_at=now,
-                    )
-                    run_result = changed
-                else:
-                    run_result = self._run_wire(run)
-            else:
-                run_result = self._run_wire(run)
-            self._fail_claimed_interaction_ledgers(
-                connection,
-                run_id=run["id"],
-                interaction_id=interaction_id,
-                reason=f"Interaction {status}",
-                runtime_session_ids=(
-                    []
-                    if run["runtime_session_id"] is None
-                    else [run["runtime_session_id"]]
-                ),
-                run=run_result,
-            )
-            return result
-
-    def begin_interaction_response(
-        self,
-        room_id: str,
-        interaction_id: str,
-        *,
-        request_id: str,
-        kind: str,
-        response: Mapping[str, object],
-    ) -> dict[str, object]:
-        """Durably claim one FIFO Gateway response without a public status."""
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        interaction_id = self._interaction_id(interaction_id)
-        canonical_request_id = self._canonical_uuid(request_id, "requestId")
-        if kind not in _INTERACTION_KINDS:
-            raise ValueError("kind is invalid")
-        response_json = self._json_object(response, "response")
-        response_value = self._load_json(response_json)
-        legacy_operation = f"interaction.{kind}.response"
-        operation = self._interaction_operation(kind, interaction_id)
-        payload = {
-            "roomId": canonical_room_id,
-            "interactionId": interaction_id,
-            "kind": kind,
-            "response": response_value,
-        }
-        request_hash = hashlib.sha256(
-            self._canonical_json(payload).encode()
-        ).hexdigest()
-        with self.write_transaction() as connection:
-            existing = connection.execute(
-                """SELECT operation, request_hash, response_json
-                FROM group_idempotency WHERE request_id = ?""",
-                (canonical_request_id,),
-            ).fetchone()
-            if existing is not None:
-                if (
-                    existing["operation"] not in {operation, legacy_operation}
-                    or existing["request_hash"] != request_hash
-                ):
-                    raise IdempotencyConflict(
-                        "requestId was already used for a different request"
-                    )
-                state = self._idempotency_state(existing["response_json"])
-                if state["state"] == "claimed":
-                    raise GroupConflictError(
-                        "Interaction response is already in progress"
-                    )
-                if state["state"] == "completed":
-                    return {"state": "replay", "response": state["response"]}
-                if state["state"] == "failed":
-                    return state
-                raise GroupStoreError("Stored interaction response is corrupt")
-            competing = connection.execute(
-                """SELECT operation, response_json FROM group_idempotency
-                WHERE operation IN (?, ?)""",
-                (operation, legacy_operation),
-            ).fetchall()
-            for candidate in competing:
-                state = self._idempotency_state(candidate["response_json"])
-                if (
-                    state["state"] == "claimed"
-                    and state["interactionId"] == interaction_id
-                ):
-                    raise GroupConflictError("Interaction response is already claimed")
-            interaction = self._interaction_row(connection, interaction_id)
-            if interaction["room_id"] != canonical_room_id:
-                raise GroupNotFoundError("Interaction not found")
-            if interaction["kind"] != kind:
-                raise GroupConflictError("Interaction kind does not match")
-            if interaction["status"] != "pending":
-                raise GroupConflictError("Interaction is already resolved")
-            run = self._run_row(connection, interaction["run_id"])
-            self._active_room(connection, canonical_room_id)
-            self._enabled_agent(connection, canonical_room_id, run["agent_id"])
-            if run["status"] != "awaiting_input":
-                raise GroupConflictError("Interaction run is not awaiting input")
-            if run["runtime_session_id"] is None:
-                raise GroupConflictError("Interaction run has no runtime session")
-            first = connection.execute(
-                """SELECT id FROM group_interactions
-                WHERE run_id = ? AND kind = ? AND status = 'pending'
-                ORDER BY rowid ASC LIMIT 1""",
-                (run["id"], kind),
-            ).fetchone()
-            if first is None or first["id"] != interaction_id:
-                raise GroupConflictError(
-                    "Interaction responses must preserve FIFO order"
-                )
-            sentinel = {
-                "state": "claimed",
-                "interactionId": interaction_id,
-                "kind": kind,
-            }
-            connection.execute(
-                """INSERT INTO group_idempotency
-                (request_id, operation, request_hash, response_json, created_at)
-                VALUES (?, ?, ?, ?, ?)""",
-                (
-                    canonical_request_id,
-                    operation,
-                    request_hash,
-                    self._canonical_json(sentinel),
-                    self._now(),
-                ),
-            )
-            return {
-                "state": "claimed",
-                "interaction": self._interaction_wire(interaction),
-                "run": self._run_wire(run),
-            }
-
-    def finish_interaction_response(
-        self,
-        request_id: str,
-        *,
-        response: Mapping[str, object],
-        interaction_status: str = "resolved",
-    ) -> dict[str, object]:
-        """Commit a known Gateway response and release the run when possible."""
-        if interaction_status not in _INTERACTION_TERMINAL_STATUSES:
-            raise ValueError("interaction_status must be resolved or cancelled")
-        canonical_request_id = self._canonical_uuid(request_id, "requestId")
-        response_json = self._json_object(response, "response")
-        public_response = self._load_json(response_json)
-        with self.write_transaction() as connection:
-            claim = connection.execute(
-                """SELECT operation, response_json FROM group_idempotency
-                WHERE request_id = ?""",
-                (canonical_request_id,),
-            ).fetchone()
-            operation = (
-                None
-                if claim is None
-                else self._interaction_response_operation(claim["operation"])
-            )
-            if claim is None or operation is None:
-                raise GroupNotFoundError("Interaction response claim not found")
-            state = self._idempotency_state(claim["response_json"])
-            if state["state"] == "claimed" and (
-                operation[0] != state["kind"]
-                or (operation[1] is not None and operation[1] != state["interactionId"])
-            ):
-                raise GroupStoreError("Stored interaction response is corrupt")
-            if state["state"] == "completed":
-                stored_status = state.get("interactionStatus", "resolved")
-                if stored_status != interaction_status:
-                    raise GroupConflictError(
-                        "Interaction response terminal status changed"
-                    )
-                return state["response"]
-            if state["state"] != "claimed":
-                raise GroupConflictError("Interaction response claim is terminal")
-            interaction = self._interaction_row(connection, state["interactionId"])
-            if interaction["status"] != "pending":
-                raise GroupConflictError("Interaction is already resolved")
-            run = self._run_row(connection, interaction["run_id"])
-            self._active_room(connection, run["room_id"])
-            self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            if run["status"] != "awaiting_input":
-                raise GroupConflictError("Interaction run is not awaiting input")
-            now = self._now()
-            connection.execute(
-                """UPDATE group_interactions
-                SET status = ?, resolved_at = ? WHERE id = ?""",
-                (interaction_status, now, interaction["id"]),
-            )
-            resolved = self._interaction_wire(
-                self._interaction_row(connection, interaction["id"])
-            )
-            self._append_event(
-                connection,
-                run["room_id"],
-                "interaction.resolved",
-                resolved,
-                created_at=now,
-            )
-            pending = connection.execute(
-                """SELECT 1 FROM group_interactions
-                WHERE run_id = ? AND status = 'pending' LIMIT 1""",
-                (run["id"],),
-            ).fetchone()
-            if pending is None:
-                response_row = self._message_row(connection, run["response_message_id"])
-                self._validate_run_message_status("running", response_row["status"])
-                changed = self._update_run(
-                    connection, run, "running", now, UNSET, UNSET
-                )
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "run.updated",
-                    changed,
-                    created_at=now,
-                )
-            final = {
-                "state": "completed",
-                "interactionStatus": interaction_status,
-                "response": public_response,
-            }
-            connection.execute(
-                """UPDATE group_idempotency SET response_json = ?
-                WHERE request_id = ?""",
-                (self._canonical_json(final), canonical_request_id),
-            )
-            return public_response
-
-    def fail_interaction_response(
-        self, request_id: str, *, reason: str, uncertain: bool
-    ) -> dict[str, object]:
-        """Fail closed on an unknown Gateway outcome or release a retryable claim."""
-        canonical_request_id = self._canonical_uuid(request_id, "requestId")
-        failure_reason = self._message_text(
-            reason, "reason", max_bytes=4096, nonblank=True
-        )
-        if not isinstance(uncertain, bool):
-            raise ValueError("uncertain must be a boolean")
-        with self.write_transaction() as connection:
-            claim = connection.execute(
-                """SELECT operation, response_json FROM group_idempotency
-                WHERE request_id = ?""",
-                (canonical_request_id,),
-            ).fetchone()
-            operation = (
-                None
-                if claim is None
-                else self._interaction_response_operation(claim["operation"])
-            )
-            if claim is None or operation is None:
-                raise GroupNotFoundError("Interaction response claim not found")
-            state = self._idempotency_state(claim["response_json"])
-            if state["state"] == "claimed" and (
-                operation[0] != state["kind"]
-                or (operation[1] is not None and operation[1] != state["interactionId"])
-            ):
-                raise GroupStoreError("Stored interaction response is corrupt")
-            if state["state"] == "failed":
-                return state
-            if state["state"] != "claimed":
-                raise GroupConflictError("Interaction response claim is terminal")
-            interaction = self._interaction_row(connection, state["interactionId"])
-            run = self._run_row(connection, interaction["run_id"])
-            self._active_room(connection, run["room_id"])
-            self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            if run["status"] != "awaiting_input":
-                raise GroupConflictError("Interaction run is not awaiting input")
-            if not uncertain:
-                connection.execute(
-                    "DELETE FROM group_idempotency WHERE request_id = ?",
-                    (canonical_request_id,),
-                )
-                return {"state": "retryable"}
-            runtime_ids = (
-                [] if run["runtime_session_id"] is None else [run["runtime_session_id"]]
-            )
-            now = self._now()
-            self._cancel_pending_interactions(connection, run, now)
-            response_row = self._message_row(connection, run["response_message_id"])
-            changed = self._update_run(
-                connection, run, "failed", now, None, failure_reason
-            )
-            self._append_event(
-                connection,
-                run["room_id"],
-                "run.updated",
-                changed,
-                created_at=now,
-            )
-            if response_row["status"] != "completed":
-                connection.execute(
-                    """UPDATE group_messages
-                    SET status = 'failed', error = ?, updated_at = ? WHERE id = ?""",
-                    (failure_reason, now, response_row["id"]),
-                )
-                message = self._message_wire(
-                    self._message_row(connection, response_row["id"])
-                )
-                if message["visible"]:
-                    self._append_event(
-                        connection,
-                        run["room_id"],
-                        "message.upsert",
-                        message,
-                        created_at=now,
-                    )
-            self._append_agent_status(connection, run["room_id"], run["agent_id"], now)
-            final = {
-                "state": "failed",
-                "reason": failure_reason,
-                "runtimeSessionIds": runtime_ids,
-                "run": self._legacy_interaction_failure_run(changed),
-            }
-            self._fail_claimed_interaction_ledgers(
-                connection,
-                run_id=run["id"],
-                reason=failure_reason,
-                runtime_session_ids=runtime_ids,
-                run=changed,
-            )
-            connection.execute(
-                """UPDATE group_idempotency SET response_json = ?
-                WHERE request_id = ?""",
-                (self._canonical_json(final), canonical_request_id),
-            )
-            return final
-
-    def expire_interaction(self, interaction_id: str) -> dict[str, object]:
-        """Idempotently cancel a stale interaction and resume when it was last."""
-        interaction_id = self._interaction_id(interaction_id)
-        with self.write_transaction() as connection:
-            interaction = self._interaction_row(connection, interaction_id)
-            if interaction["status"] != "pending":
-                return self._interaction_wire(interaction)
-            run = self._run_row(connection, interaction["run_id"])
-            self._active_room(connection, run["room_id"])
-            self._enabled_agent(connection, run["room_id"], run["agent_id"])
-            now = self._now()
-            connection.execute(
-                """UPDATE group_interactions
-                SET status = 'cancelled', resolved_at = ? WHERE id = ?""",
-                (now, interaction_id),
-            )
-            result = self._interaction_wire(
-                self._interaction_row(connection, interaction_id)
-            )
-            self._append_event(
-                connection,
-                run["room_id"],
-                "interaction.resolved",
-                result,
-                created_at=now,
-            )
-            remaining = connection.execute(
-                """SELECT 1 FROM group_interactions
-                WHERE run_id = ? AND status = 'pending' LIMIT 1""",
-                (run["id"],),
-            ).fetchone()
-            if run["status"] == "awaiting_input" and remaining is None:
-                response = self._message_row(connection, run["response_message_id"])
-                self._validate_run_message_status("running", response["status"])
-                changed = self._update_run(
-                    connection, run, "running", now, UNSET, UNSET
-                )
-                self._append_event(
-                    connection,
-                    run["room_id"],
-                    "run.updated",
-                    changed,
-                    created_at=now,
-                )
-                run_result = changed
-            else:
-                run_result = self._run_wire(run)
-            self._fail_claimed_interaction_ledgers(
-                connection,
-                run_id=run["id"],
-                interaction_id=interaction_id,
-                reason="Interaction expired",
-                runtime_session_ids=(
-                    []
-                    if run["runtime_session_id"] is None
-                    else [run["runtime_session_id"]]
-                ),
-                run=run_result,
-            )
-            return result
-
-    def events_after(
-        self, cursor: int, limit: int = MAX_EVENT_BATCH_SIZE
-    ) -> list[dict[str, object]]:
-        cursor = self._nonnegative_int(cursor, "cursor")
-        self._page_limit(limit, MAX_EVENT_BATCH_SIZE, "limit")
-        with self.read_transaction() as connection:
-            current_epoch = self._validated_epoch(
-                self._metadata_value_from_connection(connection, "journal_epoch")
-            )
-            rows = connection.execute(
-                "SELECT * FROM group_events WHERE cursor > ? ORDER BY cursor ASC LIMIT ?",
-                (cursor, limit),
-            ).fetchall()
-            return [self._event_wire(row, current_epoch) for row in rows]
-
-    def cursor_status(self, epoch: str, cursor: int) -> str:
-        canonical_epoch = self._canonical_uuid(epoch, "epoch")
-        cursor = self._nonnegative_int(cursor, "cursor")
-        with self.read_transaction() as connection:
-            if canonical_epoch != self._validated_epoch(
-                self._metadata_value_from_connection(connection, "journal_epoch")
-            ):
-                return "epoch_mismatch"
-            bounds = connection.execute(
-                "SELECT MIN(cursor) AS oldest, MAX(cursor) AS latest FROM group_events"
-            ).fetchone()
-            latest = int(bounds["latest"] or 0)
-            if cursor > latest:
-                return "cursor_expired"
-            oldest = bounds["oldest"]
-            if oldest is not None and cursor < int(oldest) - 1:
-                return "cursor_expired"
-            return "ok"
-
-    def prune_events(self, now: float | None = None) -> int:
-        prune_now = self._now() if now is None else self._finite_timestamp(now, "now")
-        with self.write_transaction() as connection:
-            threshold = connection.execute(
-                "SELECT cursor FROM group_events ORDER BY cursor DESC LIMIT 1 OFFSET ?",
-                (MIN_RETAINED_EVENTS - 1,),
-            ).fetchone()
-            if threshold is None:
-                return 0
-            result = connection.execute(
-                "DELETE FROM group_events WHERE created_at < ? AND cursor < ?",
-                (prune_now - EVENT_RETENTION_SECONDS, threshold["cursor"]),
-            )
-            return result.rowcount
-
-    def _interrupt_runs_for_scope(
-        self,
-        connection: sqlite3.Connection,
-        *,
-        room_id: str,
-        reason: str,
-        now: float,
-        agent_id: str | None = None,
-        topic_id: str | None = None,
-        include_queued: bool = True,
-    ) -> dict[str, list[str]]:
-        statuses = (
-            "('queued', 'running', 'awaiting_input')"
-            if include_queued
-            else "('running', 'awaiting_input')"
-        )
-        query = f"""SELECT run.* FROM group_agent_runs AS run
-            JOIN group_messages AS response
-              ON response.id = run.response_message_id
-            WHERE run.room_id = ? AND run.status IN {statuses}"""
-        params: list[object] = [room_id]
-        if agent_id is not None:
-            query += " AND run.agent_id = ?"
-            params.append(agent_id)
-        if topic_id is not None:
-            query += " AND run.topic_id = ?"
-            params.append(topic_id)
-        query += " ORDER BY response.seq ASC, run.id ASC"
-        runs = connection.execute(query, params).fetchall()
-        changed_ids: list[str] = []
-        runtime_ids: list[str] = []
-        for run in runs:
-            run_runtime_ids = (
-                [] if run["runtime_session_id"] is None else [run["runtime_session_id"]]
-            )
-            if (
-                run["runtime_session_id"] is not None
-                and run["runtime_session_id"] not in runtime_ids
-            ):
-                runtime_ids.append(run["runtime_session_id"])
-            response = self._message_row(connection, run["response_message_id"])
-            if (
-                response["room_id"] != run["room_id"]
-                or response["sender_id"] != run["agent_id"]
-            ):
-                raise GroupStoreError("Run response message is corrupt")
-            self._validate_run_message_state(run, response)
-            changed = self._update_run(
-                connection, run, "interrupted", now, None, reason
-            )
-            self._append_event(
-                connection, room_id, "run.updated", changed, created_at=now
-            )
-            if response["status"] == "completed":
-                self._validate_run_message_status(changed["status"], response["status"])
-            else:
-                connection.execute(
-                    """UPDATE group_messages
-                    SET status = 'interrupted', error = ?, updated_at = ? WHERE id = ?""",
-                    (reason, now, run["response_message_id"]),
-                )
-                message = self._message_wire(
-                    self._message_row(connection, run["response_message_id"])
-                )
-                self._validate_run_message_status(changed["status"], message["status"])
-                if message["visible"]:
-                    self._append_event(
-                        connection,
-                        room_id,
-                        "message.upsert",
-                        message,
-                        created_at=now,
-                    )
-            self._cancel_pending_interactions(
-                connection, run, now, order_by_created_at=True
-            )
-            self._fail_claimed_interaction_ledgers(
-                connection,
-                run_id=run["id"],
-                reason=reason,
-                runtime_session_ids=run_runtime_ids,
-                run=changed,
-            )
-            self._record_host_flow_terminal_plan_if_needed(
-                connection, self._run_row(connection, run["id"]), now
-            )
-            changed_ids.append(run["id"])
-        return {"runIds": changed_ids, "runtimeSessionIds": runtime_ids}
-
-    def recover_after_restart(self) -> list[str]:
-        with self.write_transaction() as connection:
-            runs = connection.execute(
-                "SELECT * FROM group_agent_runs WHERE status IN ('running', 'awaiting_input') ORDER BY created_at ASC, id ASC"
-            ).fetchall()
-            if not runs:
-                return []
-            now = self._now()
-            changed_ids: list[str] = []
-            for run in runs:
-                runtime_ids = (
-                    []
-                    if run["runtime_session_id"] is None
-                    else [run["runtime_session_id"]]
-                )
-                response = self._message_row(connection, run["response_message_id"])
-                if (
-                    response["room_id"] != run["room_id"]
-                    or response["sender_id"] != run["agent_id"]
-                ):
-                    raise GroupStoreError("Run response message is corrupt")
-                self._validate_run_message_state(run, response)
-                changed = self._update_run(
-                    connection, run, "interrupted", now, None, "Dashboard restarted"
-                )
-                self._append_event(
-                    connection, run["room_id"], "run.updated", changed, created_at=now
-                )
-                if response["status"] == "completed":
-                    self._validate_run_message_status(
-                        changed["status"], response["status"]
-                    )
-                else:
-                    connection.execute(
-                        """UPDATE group_messages
-                        SET status = 'interrupted', error = 'Dashboard restarted',
-                            updated_at = ? WHERE id = ?""",
-                        (now, run["response_message_id"]),
-                    )
-                    message = self._message_wire(
-                        self._message_row(connection, run["response_message_id"])
-                    )
-                    self._validate_run_message_status(
-                        changed["status"], message["status"]
-                    )
-                    if message["visible"]:
-                        self._append_event(
-                            connection,
-                            run["room_id"],
-                            "message.upsert",
-                            message,
-                            created_at=now,
-                        )
-                self._cancel_pending_interactions(
-                    connection, run, now, order_by_created_at=True
-                )
-                self._fail_claimed_interaction_ledgers(
-                    connection,
-                    run_id=run["id"],
-                    reason="Dashboard restarted",
-                    runtime_session_ids=runtime_ids,
-                    run=changed,
-                )
-                self._record_host_flow_terminal_plan_if_needed(
-                    connection, self._run_row(connection, run["id"]), now
-                )
-                changed_ids.append(run["id"])
-            return changed_ids
-
-    def _cancel_pending_interactions(
-        self,
-        connection: sqlite3.Connection,
-        run: sqlite3.Row,
-        now: float,
-        *,
-        order_by_created_at: bool = False,
-    ) -> list[dict[str, object]]:
-        """Cancel a run's pending cards and publish their durable resolutions."""
-        ordering = "created_at ASC, id ASC" if order_by_created_at else "rowid ASC"
-        interactions = connection.execute(
-            f"""SELECT id FROM group_interactions
-            WHERE run_id = ? AND status = 'pending' ORDER BY {ordering}""",
-            (run["id"],),
-        ).fetchall()
-        cancelled: list[dict[str, object]] = []
-        for interaction in interactions:
-            connection.execute(
-                """UPDATE group_interactions
-                SET status = 'cancelled', resolved_at = ? WHERE id = ?""",
-                (now, interaction["id"]),
-            )
-            resolved = self._interaction_wire(
-                self._interaction_row(connection, interaction["id"])
-            )
-            self._append_event(
-                connection,
-                run["room_id"],
-                "interaction.resolved",
-                resolved,
-                created_at=now,
-            )
-            cancelled.append(resolved)
-        return cancelled
-
-    def _fail_claimed_interaction_ledgers(
-        self,
-        connection: sqlite3.Connection,
-        *,
-        run_id: str,
-        reason: str,
-        runtime_session_ids: list[str],
-        run: Mapping[str, object],
-        interaction_id: str | None = None,
-    ) -> None:
-        interactions = connection.execute(
-            """SELECT id, kind FROM group_interactions
-            WHERE run_id = ? ORDER BY rowid ASC""",
-            (run_id,),
-        ).fetchall()
-        if interaction_id is not None:
-            interactions = [
-                item for item in interactions if item["id"] == interaction_id
-            ]
-        if not interactions:
-            return
-        target_ids = {item["id"] for item in interactions}
-        scoped_operations = [
-            self._interaction_operation(item["kind"], item["id"])
-            for item in interactions
-        ]
-        placeholders = ", ".join("?" for _ in scoped_operations)
-        ledgers = connection.execute(
-            f"""SELECT request_id, operation, response_json
-            FROM group_idempotency WHERE operation IN ({placeholders})""",
-            scoped_operations,
-        ).fetchall()
-        legacy = connection.execute(
-            """SELECT request_id, operation, response_json
-            FROM group_idempotency WHERE operation IN (
-                'interaction.approval.response',
-                'interaction.clarification.response'
-            )"""
-        ).fetchall()
-        seen: set[str] = set()
-        terminal = {
-            "state": "failed",
-            "reason": reason,
-            "runtimeSessionIds": list(runtime_session_ids),
-            "run": self._legacy_interaction_failure_run(run),
-        }
-        encoded = self._canonical_json(terminal)
-        for ledger in (*ledgers, *legacy):
-            if ledger["request_id"] in seen:
-                continue
-            seen.add(ledger["request_id"])
-            operation = self._interaction_response_operation(ledger["operation"])
-            state = self._idempotency_state(ledger["response_json"])
-            if operation is None or state["state"] != "claimed":
-                continue
-            claimed_id = state["interactionId"]
-            if claimed_id not in target_ids:
-                continue
-            if operation[0] != state["kind"] or (
-                operation[1] is not None and operation[1] != claimed_id
-            ):
-                raise GroupStoreError("Stored interaction response is corrupt")
-            connection.execute(
-                """UPDATE group_idempotency SET response_json = ?
-                WHERE request_id = ?""",
-                (encoded, ledger["request_id"]),
-            )
-
-    def queued_run_count(self) -> int:
-        with self.connection() as connection:
-            return int(
-                connection.execute(
-                    "SELECT COUNT(*) FROM group_agent_runs WHERE status = 'queued'"
-                ).fetchone()[0]
-            )
-
-    def list_pending_interactions(self, room_id: str) -> list[dict[str, object]]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        with self.read_transaction() as connection:
-            self._room_detail(connection, canonical_room_id, include_archived=True)
-            rows = connection.execute(
-                "SELECT * FROM group_interactions WHERE room_id = ? AND status = 'pending' ORDER BY created_at, id",
-                (canonical_room_id,),
-            ).fetchall()
-            return [self._interaction_wire(row) for row in rows]
-
-    def list_queued_runs(self, room_id: str) -> list[dict[str, object]]:
-        canonical_room_id = self._canonical_uuid(room_id, "roomId")
-        with self.read_transaction() as connection:
-            self._room_detail(connection, canonical_room_id, include_archived=True)
-            rows = connection.execute(
-                "SELECT * FROM group_agent_runs WHERE room_id = ? AND status = 'queued' ORDER BY created_at, id",
-                (canonical_room_id,),
-            ).fetchall()
-            return [self._run_wire(row) for row in rows]
-
-    def latest_cursor(self) -> int:
-        with self.connection() as connection:
-            row = connection.execute(
-                "SELECT COALESCE(MAX(cursor), 0) AS cursor FROM group_events"
-            ).fetchone()
-            return int(row["cursor"])
-
-    @staticmethod
-    def _safe_context_seq(
-        connection: sqlite3.Connection,
-        room_id: str,
-        topic_id: str,
-        after_seq: int,
-        trigger_seq: int,
-    ) -> int:
-        hole = connection.execute(
-            """SELECT MIN(seq) AS seq FROM group_messages
-            WHERE room_id = ? AND topic_id = ? AND seq > ? AND seq <= ?
-              AND status NOT IN ('completed', 'failed', 'interrupted')""",
-            (room_id, topic_id, after_seq, trigger_seq),
-        ).fetchone()["seq"]
-        if hole is None:
-            return max(after_seq, trigger_seq)
-        return max(after_seq, int(hole) - 1)
-
-    def _append_agent_status(
-        self,
-        connection: sqlite3.Connection,
-        room_id: str,
-        agent_id: str,
-        now: float,
-    ) -> None:
-        row = connection.execute(
-            """SELECT id, status FROM group_agent_runs
-            WHERE room_id = ? AND agent_id = ?
-              AND status IN ('queued', 'running', 'awaiting_input')
-            ORDER BY CASE status
-                WHEN 'awaiting_input' THEN 3
-                WHEN 'running' THEN 2
-                ELSE 1 END DESC,
-                created_at ASC, id ASC
-            LIMIT 1""",
-            (room_id, agent_id),
-        ).fetchone()
-        payload: dict[str, object] = {
-            "roomId": room_id,
-            "agentId": agent_id,
-            "status": "idle" if row is None else row["status"],
-            "runId": None if row is None else row["id"],
-        }
-        self._append_event(connection, room_id, "agent.status", payload, created_at=now)
-
-    def _append_event(
-        self,
-        connection: sqlite3.Connection,
-        room_id: str,
-        event_type: str,
-        payload: Mapping[str, object],
-        *,
-        created_at: float | None = None,
-    ) -> int:
-        epoch = self._metadata_value_from_connection(connection, "journal_epoch")
-        event_time = self._now() if created_at is None else created_at
-        cursor = connection.execute(
-            """INSERT INTO group_events(epoch, room_id, event_type, payload_json, created_at)
-            VALUES (?, ?, ?, ?, ?) RETURNING cursor""",
-            (
-                epoch,
-                room_id,
-                event_type,
-                self._canonical_json(payload),
-                event_time,
-            ),
-        ).fetchone()["cursor"]
-        if event_type == "message.upsert":
-            topic_id = payload.get("topicId")
-            if not isinstance(topic_id, str):
-                raise GroupStoreError("Message event topic identity is missing")
-            connection.execute(
-                """UPDATE group_topics
-                SET updated_at = CASE WHEN updated_at < ? THEN ? ELSE updated_at END
-                WHERE id = ? AND room_id = ?""",
-                (event_time, event_time, topic_id, room_id),
-            )
-            topic = self._topic_summary_by_id(connection, room_id, topic_id)
-            connection.execute(
-                """INSERT INTO group_events
-                (epoch, room_id, event_type, payload_json, created_at)
-                VALUES (?, ?, 'topic.updated', ?, ?)""",
-                (epoch, room_id, self._canonical_json(topic), event_time),
-            )
-        message_activity = (
-            event_type == "message.upsert"
-            and payload.get("status") in {"completed", "failed", "interrupted"}
-        )
-        if event_type == "run.updated" or message_activity:
-            activity = self._room_activity_from_connection(connection, room_id)
-            connection.execute(
-                """INSERT INTO group_events
-                (epoch, room_id, event_type, payload_json, created_at)
-                VALUES (?, ?, 'room.activity', ?, ?)""",
-                (epoch, room_id, self._canonical_json(activity), event_time),
-            )
-        return int(cursor)
-
-    def _append_room_updated_summary(
-        self,
-        connection: sqlite3.Connection,
-        room_id: str,
-        *,
-        created_at: float,
-    ) -> None:
-        room = connection.execute(
-            """SELECT id, name, cwd, instructions, avatar_data_url, max_reply_rounds, orchestration_mode,
-            created_at, updated_at, archived,
-            (SELECT COUNT(*) FROM group_agents WHERE room_id = group_rooms.id)
-                AS agent_count,
-            (SELECT COUNT(*) FROM group_topics WHERE room_id = group_rooms.id)
-                AS topic_count
-            FROM group_rooms WHERE id = ? AND archived = 0""",
-            (room_id,),
-        ).fetchone()
-        if room is None:
-            raise GroupNotFoundError("Room not found")
-        self._append_event(
-            connection,
-            room_id,
-            "room.updated",
-            self._room_summary(
-                room, self._room_avatar_members(connection, room_id)
-            ),
-            created_at=created_at,
-        )
-
-    def _room_detail(
-        self, connection: sqlite3.Connection, room_id: str, *, include_archived: bool
-    ) -> dict[str, object]:
-        room = connection.execute(
-            "SELECT * FROM group_rooms WHERE id = ?", (room_id,)
-        ).fetchone()
-        if room is None or (room["archived"] and not include_archived):
-            raise GroupNotFoundError("Room not found")
-        agents = connection.execute(
-            "SELECT * FROM group_agents WHERE room_id = ? ORDER BY created_at ASC, id ASC",
-            (room_id,),
-        ).fetchall()
-        result = self._room_wire(room)
-        result["agents"] = [self._agent_wire(agent) for agent in agents]
-        result["avatarMembers"] = [
-            self._avatar_member_wire(agent) for agent in agents[:4]
-        ]
-        return result
-
-    def prepare_run_session_configuration(
-        self, run_id: str, configuration: Mapping[str, object]
-    ) -> bool:
-        """Detach a stale stored session before this claimed run is bound.
-
-        Configuration changes never interrupt the currently bound run. A later
-        claimed run reaches this method only after agent serialization, so it
-        can safely rotate the dormant stored session and rebuild full context.
-        """
-        canonical_run_id = self._canonical_uuid(run_id, "runId")
-        normalized = {
-            "model": configuration.get("model"),
-            "provider": configuration.get("provider"),
-            "reasoning_effort": configuration.get("reasoning_effort"),
-            "fast": configuration.get("fast"),
-        }
-        serialized = self._canonical_json(normalized)
-        with self.write_transaction() as connection:
-            run = self._run_row(connection, canonical_run_id)
-            if run["status"] != "running" or run["runtime_session_id"] is not None:
-                raise GroupConflictError("Run does not accept configuration rotation")
-            agent = self._owned_agent(connection, run["room_id"], run["agent_id"])
-            if agent["session_config_json"] == serialized:
-                return False
-            now = self._now()
-            connection.execute(
-                """UPDATE group_agents
-                SET stored_session_id = NULL,
-                    last_context_message_seq = 0,
-                    session_config_json = ?,
-                    updated_at = ?
-                WHERE id = ? AND room_id = ?""",
-                (serialized, now, agent["id"], run["room_id"]),
-            )
-            connection.execute(
-                """UPDATE group_agent_topic_state
-                SET last_context_message_seq = 0, updated_at = ?
-                WHERE agent_id = ?""",
-                (now, agent["id"]),
-            )
-            refreshed = self._owned_agent(connection, run["room_id"], run["agent_id"])
-            self._append_event(
-                connection,
-                run["room_id"],
-                "agent.updated",
-                self._agent_wire(refreshed),
-                created_at=now,
-            )
-            return True
-
-    @staticmethod
-    def _compatibility_topic_id(room_id: str) -> str:
-        return str(
-            uuid.uuid5(
-                uuid.NAMESPACE_URL,
-                f"hermes://yaoyao-group/{room_id}/compatibility-topic",
-            )
-        )
-
-    @staticmethod
-    def _topic_title(content: str) -> str:
-        normalized = " ".join(content.split()).strip()
-        return (normalized or "话题")[:_TOPIC_TITLE_LENGTH]
-
-    @staticmethod
-    def _topic_row(
-        connection: sqlite3.Connection, room_id: str, topic_id: str
-    ) -> sqlite3.Row:
-        topic = connection.execute(
-            "SELECT * FROM group_topics WHERE id = ? AND room_id = ?",
-            (topic_id, room_id),
-        ).fetchone()
-        if topic is None:
-            raise GroupNotFoundError("Topic not found in room")
-        return topic
-
-    def _active_topic(
-        self, connection: sqlite3.Connection, room_id: str, topic_id: str
-    ) -> sqlite3.Row:
-        topic = self._topic_row(connection, room_id, topic_id)
-        if topic["archived"]:
-            raise GroupNotFoundError("Topic not found in room")
-        return topic
-
-    @classmethod
-    def _topic_summary_by_id(
-        cls, connection: sqlite3.Connection, room_id: str, topic_id: str
-    ) -> dict[str, object]:
-        row = connection.execute(
-            """SELECT topic.*,
-            (SELECT COUNT(*) FROM group_messages AS counted
-             WHERE counted.topic_id = topic.id AND counted.visible = 1)
-                AS message_count,
-            COALESCE((SELECT CASE WHEN TRIM(latest.content) != ''
-                                  THEN latest.content ELSE latest.error END
-             FROM group_messages AS latest
-             WHERE latest.topic_id = topic.id AND latest.visible = 1
-               AND (TRIM(latest.content) != '' OR TRIM(latest.error) != '')
-             ORDER BY latest.seq DESC LIMIT 1), '') AS preview,
-            (SELECT COUNT(*) FROM group_messages AS unread
-             WHERE unread.topic_id = topic.id AND unread.visible = 1
-               AND unread.sender_kind = 'agent'
-               AND (TRIM(unread.content) != '' OR TRIM(unread.error) != '')
-               AND unread.seq > topic.last_read_message_seq) AS unread_count,
-            COALESCE((SELECT MAX(visible_message.seq)
-             FROM group_messages AS visible_message
-             WHERE visible_message.topic_id = topic.id
-               AND visible_message.visible = 1), 0) AS latest_message_seq
-            FROM group_topics AS topic
-            WHERE topic.id = ? AND topic.room_id = ?""",
-            (topic_id, room_id),
-        ).fetchone()
-        if row is None:
-            raise GroupNotFoundError("Topic not found in room")
-        return cls._topic_summary(row)
-
-    def _ensure_topic(
-        self,
-        connection: sqlite3.Connection,
-        room_id: str,
-        topic_id: str,
-        title_source: str,
-        now: float,
-    ) -> sqlite3.Row:
-        existing = connection.execute(
-            "SELECT * FROM group_topics WHERE id = ?", (topic_id,)
-        ).fetchone()
-        if existing is not None:
-            if existing["room_id"] != room_id:
-                raise GroupConflictError("Topic does not belong to room")
-            if existing["archived"]:
-                raise GroupConflictError("Topic is archived")
-            return existing
-        connection.execute(
-            """INSERT INTO group_topics
-            (id, room_id, title, created_at, updated_at)
-            VALUES (?, ?, ?, ?, ?)""",
-            (topic_id, room_id, self._topic_title(title_source), now, now),
-        )
-        connection.execute(
-            """INSERT INTO group_agent_topic_state
-            (agent_id, topic_id, last_context_message_seq, created_at, updated_at)
-            SELECT id, ?, 0, ?, ? FROM group_agents WHERE room_id = ?""",
-            (topic_id, now, now, room_id),
-        )
-        return self._topic_row(connection, room_id, topic_id)
-
-    @staticmethod
-    def _agent_topic_state(
-        connection: sqlite3.Connection, agent_id: str, topic_id: str
-    ) -> sqlite3.Row:
-        state = connection.execute(
-            """SELECT * FROM group_agent_topic_state
-            WHERE agent_id = ? AND topic_id = ?""",
-            (agent_id, topic_id),
-        ).fetchone()
-        if state is None:
-            raise GroupStoreError("Agent topic context state is missing")
-        return state
-
-    def _active_room(self, connection: sqlite3.Connection, room_id: str) -> sqlite3.Row:
-        room = connection.execute(
-            "SELECT * FROM group_rooms WHERE id = ? AND archived = 0", (room_id,)
-        ).fetchone()
-        if room is None:
-            raise GroupNotFoundError("Room not found")
-        return room
-
-    def _owned_agent(
-        self, connection: sqlite3.Connection, room_id: str, agent_id: str
-    ) -> sqlite3.Row:
-        agent = connection.execute(
-            "SELECT * FROM group_agents WHERE id = ? AND room_id = ?",
-            (agent_id, room_id),
-        ).fetchone()
-        if agent is None:
-            raise GroupNotFoundError("Agent not found in room")
-        return agent
-
-    @staticmethod
-    def _room_host(
-        connection: sqlite3.Connection, room_id: str
-    ) -> sqlite3.Row:
-        host = connection.execute(
-            "SELECT * FROM group_agents WHERE room_id = ? AND is_host = 1",
-            (room_id,),
-        ).fetchone()
-        if host is None:
-            raise GroupStoreError("Room administrator is missing")
-        return host
-
-    @staticmethod
-    def _first_enabled_host_candidate(
-        connection: sqlite3.Connection,
-        room_id: str,
-        *,
-        exclude_agent_id: str,
-    ) -> sqlite3.Row | None:
-        return connection.execute(
-            """SELECT * FROM group_agents
-            WHERE room_id = ? AND enabled = 1 AND id != ?
-            ORDER BY created_at ASC, id ASC LIMIT 1""",
-            (room_id, exclude_agent_id),
-        ).fetchone()
-
-    def _switch_host(
-        self,
-        connection: sqlite3.Connection,
-        room_id: str,
-        agent_id: str,
-        *,
-        now: float,
-    ) -> tuple[dict[str, object], dict[str, object]] | None:
-        current = self._room_host(connection, room_id)
-        if current["id"] == agent_id:
-            return None
-        replacement = self._owned_agent(connection, room_id, agent_id)
-        if not replacement["enabled"]:
-            raise GroupConflictError("Administrator Agent must be enabled")
-        connection.execute(
-            """UPDATE group_agents SET is_host = 0, updated_at = ?
-            WHERE id = ? AND room_id = ?""",
-            (now, current["id"], room_id),
-        )
-        connection.execute(
-            """UPDATE group_agents SET is_host = 1, updated_at = ?
-            WHERE id = ? AND room_id = ?""",
-            (now, replacement["id"], room_id),
-        )
-        return (
-            self._agent_detail(connection, room_id, str(current["id"])),
-            self._agent_detail(connection, room_id, str(replacement["id"])),
-        )
-
-    def _enabled_agent(
-        self, connection: sqlite3.Connection, room_id: str, agent_id: str
-    ) -> sqlite3.Row:
-        agent = self._owned_agent(connection, room_id, agent_id)
-        if not agent["enabled"]:
-            raise GroupConflictError("Agent is disabled")
-        return agent
-
-    @staticmethod
-    def _require_available_runtime(
-        connection: sqlite3.Connection, runtime_session_id: str, run_id: str
-    ) -> None:
-        occupied = connection.execute(
-            """SELECT id FROM group_agent_runs
-            WHERE runtime_session_id = ?
-              AND status IN ('running', 'awaiting_input')
-              AND id != ? LIMIT 1""",
-            (runtime_session_id, run_id),
-        ).fetchone()
-        if occupied is not None:
-            raise GroupConflictError("Runtime session is already in use")
-
-    def _agent_detail(
-        self, connection: sqlite3.Connection, room_id: str, agent_id: str
-    ) -> dict[str, object]:
-        return self._agent_wire(self._owned_agent(connection, room_id, agent_id))
-
-    @staticmethod
-    def _message_row(connection: sqlite3.Connection, message_id: str) -> sqlite3.Row:
-        row = connection.execute(
-            "SELECT * FROM group_messages WHERE id = ?", (message_id,)
-        ).fetchone()
-        if row is None:
-            raise GroupNotFoundError("Message not found")
-        return row
-
-    @staticmethod
-    def _message_with_execution_row(
-        connection: sqlite3.Connection, message_id: str
-    ) -> sqlite3.Row:
-        row = connection.execute(
-            """SELECT message.*,
-                run.requested_model AS execution_requested_model,
-                run.requested_provider AS execution_requested_provider,
-                run.requested_reasoning_effort AS execution_requested_reasoning_effort,
-                run.requested_fast_mode AS execution_requested_fast_mode,
-                run.actual_model AS execution_actual_model,
-                run.actual_provider AS execution_actual_provider,
-                run.actual_reasoning_effort AS execution_actual_reasoning_effort,
-                run.actual_fast_mode AS execution_actual_fast_mode
-            FROM group_messages AS message
-            LEFT JOIN group_agent_runs AS run
-              ON run.response_message_id = message.id
-            WHERE message.id = ?""",
-            (message_id,),
-        ).fetchone()
-        if row is None:
-            raise GroupNotFoundError("Message not found")
-        return row
-
-    @staticmethod
-    def _run_row(connection: sqlite3.Connection, run_id: str) -> sqlite3.Row:
-        row = connection.execute(
-            "SELECT * FROM group_agent_runs WHERE id = ?", (run_id,)
-        ).fetchone()
-        if row is None:
-            raise GroupNotFoundError("Run not found")
-        return row
-
-    @staticmethod
-    def _interaction_row(
-        connection: sqlite3.Connection, interaction_id: str
-    ) -> sqlite3.Row:
-        row = connection.execute(
-            "SELECT * FROM group_interactions WHERE id = ?", (interaction_id,)
-        ).fetchone()
-        if row is None:
-            raise GroupNotFoundError("Interaction not found")
-        return row
-
-    @classmethod
-    def _validate_run_message_state(
-        cls, run: sqlite3.Row, message: sqlite3.Row
-    ) -> None:
-        if (
-            run["room_id"] != message["room_id"]
-            or run["topic_id"] != message["topic_id"]
-        ):
-            raise GroupStoreError("Run response message is corrupt")
-        cls._validate_run_message_status(run["status"], message["status"])
-
-    @staticmethod
-    def _validate_run_message_status(run_status: str, message_status: str) -> None:
-        if message_status not in _MESSAGE_STATUSES_BY_RUN.get(run_status, frozenset()):
-            raise GroupConflictError("Run and response message states conflict")
-
-    def _update_run(
-        self,
-        connection: sqlite3.Connection,
-        run: sqlite3.Row,
-        status: str,
-        now: float,
-        runtime_session_id: object,
-        error: object,
-    ) -> dict[str, object]:
-        runtime = (
-            run["runtime_session_id"]
-            if runtime_session_id is UNSET
-            else runtime_session_id
-        )
-        run_error = run["error"] if error is UNSET else error
-        try:
-            connection.execute(
-                "UPDATE group_agent_runs SET status = ?, runtime_session_id = ?, error = ?, updated_at = ? WHERE id = ?",
-                (status, runtime, run_error, now, run["id"]),
-            )
-        except sqlite3.IntegrityError as conflict:
-            if "group_agent_runs.runtime_session_id" in str(conflict):
-                raise GroupConflictError(
-                    "Runtime session is already in use"
-                ) from conflict
-            raise
-        return self._run_wire(self._run_row(connection, run["id"]))
-
-    @staticmethod
-    def _message_wire(row: sqlite3.Row) -> dict[str, object]:
-        try:
-            tool_state = GroupStore._load_json(row["tool_state_json"])
-        except (
-            TypeError,
-            ValueError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-        ) as error:
-            raise GroupStoreError("Stored message tool state is corrupt") from error
-        if not isinstance(tool_state, list) or not all(
-            isinstance(item, dict) for item in tool_state
-        ):
-            raise GroupStoreError("Stored message tool state is corrupt")
-        result = {
-            "seq": row["seq"],
-            "id": row["id"],
-            "roomId": row["room_id"],
-            "topicId": row["topic_id"],
-            "senderKind": row["sender_kind"],
-            "senderId": row["sender_id"],
-            "senderName": row["sender_name"],
-            "rootMessageId": row["root_message_id"],
-            "replyToMessageId": row["reply_to_message_id"],
-            "clientMessageId": row["client_message_id"],
-            "content": row["content"],
-            "reasoning": row["reasoning"],
-            "toolState": tool_state,
-            "status": row["status"],
-            "error": row["error"],
-            "visible": bool(row["visible"]),
-            "createdAt": row["created_at"],
-            "updatedAt": row["updated_at"],
-        }
-        keys = set(row.keys())
-        if "execution_actual_model" in keys:
-            values = {
-                "requestedModel": row["execution_requested_model"],
-                "requestedProvider": row["execution_requested_provider"],
-                "requestedReasoningEffort": row[
-                    "execution_requested_reasoning_effort"
-                ],
-                "requestedFastMode": (
-                    None
-                    if row["execution_requested_fast_mode"] is None
-                    else bool(row["execution_requested_fast_mode"])
-                ),
-                "actualModel": row["execution_actual_model"],
-                "actualProvider": row["execution_actual_provider"],
-                "actualReasoningEffort": row["execution_actual_reasoning_effort"],
-                "actualFastMode": (
-                    None
-                    if row["execution_actual_fast_mode"] is None
-                    else bool(row["execution_actual_fast_mode"])
-                ),
-            }
-            if any(value is not None for value in values.values()):
-                result["execution"] = values
-        return result
-
-    @classmethod
-    def _projection_message(cls, row: sqlite3.Row) -> dict[str, object]:
-        try:
-            tool_state = cls._load_json(row["tool_state_json"])
-        except (
-            TypeError,
-            ValueError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-        ) as error:
-            raise GroupStoreError("Stored message tool state is corrupt") from error
-        if not isinstance(tool_state, list) or not all(
-            isinstance(item, dict) for item in tool_state
-        ):
-            raise GroupStoreError("Stored message tool state is corrupt")
-        tool_names: list[str] = []
-        tool_names_truncated = False
-        for item in tool_state:
-            name = None
-            for key in ("name", "toolName"):
-                candidate = item.get(key)
-                if not isinstance(candidate, str) or not candidate:
-                    continue
-                if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,119}", candidate) is None:
-                    tool_names_truncated = True
-                    continue
-                name = candidate
-                break
-            if name is None or name in tool_names:
-                continue
-            if len(tool_names) >= 16:
-                tool_names_truncated = True
-                break
-            tool_names.append(name)
-        return {
-            "seq": int(row["seq"]),
-            "senderKind": row["sender_kind"],
-            "senderId": row["sender_id"],
-            "senderName": row["sender_name"],
-            "content": row["content"],
-            "reasoning": row["reasoning"],
-            "toolNames": tool_names,
-            "status": row["status"],
-            "summary": row["error"],
-            "truncated": tool_names_truncated,
-        }
-
-    @classmethod
-    def _bound_projection_messages(
-        cls,
-        messages: list[dict[str, object]],
-        *,
-        omitted_count: int,
-        omitted_through_seq: int | None,
-    ) -> tuple[list[dict[str, object]], int, int | None, dict[str, object] | None]:
-        while len(messages) > 1:
-            omitted_summary = cls._projection_omitted_summary(
-                omitted_count, omitted_through_seq
-            )
-            if (
-                cls._projection_size(messages, omitted_summary)
-                <= CONTEXT_CHARACTER_BUDGET
-            ):
-                break
-            removed = messages.pop(0)
-            omitted_count += 1
-            omitted_through_seq = int(removed["seq"])
-        omitted_summary = cls._projection_omitted_summary(
-            omitted_count, omitted_through_seq
-        )
-        if (
-            messages
-            and cls._projection_size(messages, omitted_summary)
-            > CONTEXT_CHARACTER_BUDGET
-        ):
-            cls._truncate_projection_message(messages[0], omitted_summary)
-        if cls._projection_size(messages, omitted_summary) > CONTEXT_CHARACTER_BUDGET:
-            raise GroupStoreError("Projection metadata exceeds the character budget")
-        return messages, omitted_count, omitted_through_seq, omitted_summary
-
-    @staticmethod
-    def _projection_omitted_summary(
-        count: int, through_seq: int | None
-    ) -> dict[str, object] | None:
-        if count == 0:
-            return None
-        if through_seq is None:
-            raise GroupStoreError("Projection omission metadata is corrupt")
-        return {
-            "messageCount": count,
-            "throughSeq": through_seq,
-            "text": f"Omitted {count} earlier messages through seq {through_seq}.",
-        }
-
-    @classmethod
-    def _projection_size(
-        cls,
-        messages: list[dict[str, object]],
-        omitted_summary: dict[str, object] | None,
-    ) -> int:
-        return len(
-            cls._canonical_json(
-                {"messages": messages, "omittedSummary": omitted_summary}
-            ).encode("utf-8")
-        )
-
-    @classmethod
-    def _truncate_projection_message(
-        cls,
-        message: dict[str, object],
-        omitted_summary: dict[str, object] | None,
-    ) -> None:
-        marker = "…[truncated]"
-        originals = {
-            field: message[field]
-            for field in ("content", "reasoning", "summary")
-            if isinstance(message[field], str) and message[field]
-        }
-        message["truncated"] = True
-        for field in originals:
-            message[field] = marker
-        wrapper = [message]
-        if cls._projection_size(wrapper, omitted_summary) > CONTEXT_CHARACTER_BUDGET:
-            raise GroupStoreError("Projection identity exceeds the character budget")
-        for field in ("content", "reasoning", "summary"):
-            original = originals.get(field)
-            if original is None:
-                continue
-            low = 0
-            high = len(original)
-            while low < high:
-                candidate = (low + high + 1) // 2
-                message[field] = (
-                    original
-                    if candidate == len(original)
-                    else f"{original[:candidate]}{marker}"
-                )
-                if (
-                    cls._projection_size(wrapper, omitted_summary)
-                    <= CONTEXT_CHARACTER_BUDGET
-                ):
-                    low = candidate
-                else:
-                    high = candidate - 1
-            message[field] = (
-                original if low == len(original) else f"{original[:low]}{marker}"
-            )
-
-    @staticmethod
-    def _run_wire(row: sqlite3.Row) -> dict[str, object]:
-        return {
-            "id": row["id"],
-            "roomId": row["room_id"],
-            "topicId": row["topic_id"],
-            "agentId": row["agent_id"],
-            "triggerMessageId": row["trigger_message_id"],
-            "responseMessageId": row["response_message_id"],
-            "rootMessageId": row["root_message_id"],
-            "depth": row["depth"],
-            "replyMode": row["reply_mode"],
-            "status": row["status"],
-            "runtimeSessionId": row["runtime_session_id"],
-            "requestedModel": row["requested_model"],
-            "requestedProvider": row["requested_provider"],
-            "requestedReasoningEffort": row["requested_reasoning_effort"],
-            "requestedFastMode": (
-                None
-                if row["requested_fast_mode"] is None
-                else bool(row["requested_fast_mode"])
-            ),
-            "actualModel": row["actual_model"],
-            "actualProvider": row["actual_provider"],
-            "actualReasoningEffort": row["actual_reasoning_effort"],
-            "actualFastMode": (
-                None
-                if row["actual_fast_mode"] is None
-                else bool(row["actual_fast_mode"])
-            ),
-            "error": row["error"],
-            "createdAt": row["created_at"],
-            "updatedAt": row["updated_at"],
-        }
-
-    @staticmethod
-    def _legacy_interaction_failure_run(
-        run: Mapping[str, object],
-    ) -> dict[str, object]:
-        """Keep the pre-v4 strict HTTP replay shape for failed interactions."""
-        result = dict(run)
-        result.pop("topicId", None)
-        for field in (
-            "requestedModel",
-            "requestedProvider",
-            "requestedReasoningEffort",
-            "requestedFastMode",
-            "actualModel",
-            "actualProvider",
-            "actualReasoningEffort",
-            "actualFastMode",
-        ):
-            result.pop(field, None)
-        return result
-
-    @staticmethod
-    def _interaction_wire(row: sqlite3.Row) -> dict[str, object]:
-        try:
-            payload = GroupStore._load_json(row["payload_json"])
-        except (
-            TypeError,
-            ValueError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-        ) as error:
-            raise GroupStoreError("Stored interaction payload is corrupt") from error
-        if not isinstance(payload, dict):
-            raise GroupStoreError("Stored interaction payload is corrupt")
-        return {
-            "id": row["id"],
-            "roomId": row["room_id"],
-            "topicId": row["topic_id"],
-            "agentId": row["agent_id"],
-            "runId": row["run_id"],
-            "kind": row["kind"],
-            "payload": payload,
-            "status": row["status"],
-            "createdAt": row["created_at"],
-            "resolvedAt": row["resolved_at"],
-        }
-
-    def _event_wire(self, row: sqlite3.Row, current_epoch: str) -> dict[str, object]:
-        try:
-            epoch = self._validated_epoch(row["epoch"])
-            payload = self._load_json(row["payload_json"])
-        except (
-            TypeError,
-            ValueError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-        ) as error:
-            raise GroupStoreError("Stored event is corrupt") from error
-        if epoch != current_epoch or not isinstance(payload, dict):
-            raise GroupStoreError("Stored event is corrupt")
-        return {
-            "cursor": row["cursor"],
-            "epoch": epoch,
-            "roomId": row["room_id"],
-            "eventType": row["event_type"],
-            "payload": payload,
-            "createdAt": row["created_at"],
-        }
-
-    @staticmethod
-    def _message_text(
-        value: object, field: str, *, max_bytes: int, nonblank: bool = False
-    ) -> str:
-        if not isinstance(value, str):
-            raise ValueError(f"{field} must be a string")
-        try:
-            encoded = value.encode("utf-8")
-        except UnicodeEncodeError as error:
-            raise ValueError(f"{field} must be valid UTF-8") from error
-        if len(encoded) > max_bytes:
-            raise ValueError(f"{field} exceeds maximum size")
-        if nonblank and not value.strip():
-            raise ValueError(f"{field} must not be blank")
-        return value
-
-    @staticmethod
-    def _orchestration_mode(value: object) -> str:
-        if not isinstance(value, str) or value not in ORCHESTRATION_MODES:
-            raise ValueError("orchestrationMode must be free or host")
-        return value
-
-    @classmethod
-    def _mention_agent_ids(cls, value: object) -> list[str]:
-        if not isinstance(value, list):
-            raise ValueError("mentionAgentIds must be a list")
-        result = [
-            cls._canonical_uuid(agent_id, "mentionAgentIds") for agent_id in value
-        ]
-        if len(result) != len(set(result)):
-            raise GroupConflictError("mentionAgentIds must be unique")
-        return result
-
-    @staticmethod
-    def _interaction_id(value: object) -> str:
-        return normalize_interaction_id(value)
-
-    @staticmethod
-    def _runtime_session_id(value: object) -> str | None:
-        if value is None:
-            return None
-        if (
-            not isinstance(value, str)
-            or not value
-            or len(value) > 200
-            or any(unicodedata.category(character) == "Cc" for character in value)
-        ):
-            raise ValueError("runtimeSessionId is invalid")
-        return value
-
-    @classmethod
-    def _tool_state_json(cls, value: object) -> str:
-        if not isinstance(value, list):
-            raise ValueError("tool_state must be a list")
-        if not all(isinstance(item, Mapping) for item in value):
-            raise ValueError("tool_state entries must be objects")
-        encoded = cls._strict_json(value, "tool_state")
-        if len(encoded.encode("utf-8")) > MAX_TOOL_STATE_BYTES:
-            raise ValueError("tool_state exceeds maximum size")
-        return encoded
-
-    @classmethod
-    def _json_object(cls, value: object, field: str) -> str:
-        if not isinstance(value, Mapping):
-            raise ValueError(f"{field} must be an object")
-        encoded = cls._strict_json(dict(value), field)
-        if (
-            field == "payload"
-            and len(encoded.encode("utf-8")) > MAX_INTERACTION_PAYLOAD_BYTES
-        ):
-            raise ValueError("payload exceeds maximum size")
-        return encoded
-
-    @staticmethod
-    def _strict_json(value: object, field: str) -> str:
-        try:
-            encoded = json.dumps(
-                value,
-                ensure_ascii=False,
-                sort_keys=True,
-                separators=(",", ":"),
-                allow_nan=False,
-            )
-            encoded.encode("utf-8")
-            return encoded
-        except (TypeError, ValueError, UnicodeEncodeError) as error:
-            raise ValueError(f"{field} must be JSON-serializable") from error
-
-    @staticmethod
-    def _load_json(value: object) -> object:
-        if not isinstance(value, str):
-            raise ValueError("JSON must be a string")
-        return json.loads(
-            value,
-            parse_constant=lambda constant: (_ for _ in ()).throw(ValueError(constant)),
-        )
-
-    @staticmethod
-    def _page_limit(value: object, maximum: int, field: str) -> int:
-        if (
-            not isinstance(value, int)
-            or isinstance(value, bool)
-            or not 1 <= value <= maximum
-        ):
-            raise ValueError(f"{field} must be an integer from 1 to {maximum}")
-        return value
-
-    @staticmethod
-    def _positive_int(value: object, field: str) -> int:
-        if not isinstance(value, int) or isinstance(value, bool) or value < 1:
-            raise ValueError(f"{field} must be a positive integer")
-        return value
-
-    @staticmethod
-    def _nonnegative_int(value: object, field: str) -> int:
-        if not isinstance(value, int) or isinstance(value, bool) or value < 0:
-            raise ValueError(f"{field} must be a nonnegative integer")
-        return value
-
-    @staticmethod
-    def _finite_timestamp(value: object, field: str) -> float:
-        try:
-            finite = (
-                math.isfinite(value)
-                if isinstance(value, (int, float)) and not isinstance(value, bool)
-                else False
-            )
-        except OverflowError:
-            finite = False
-        if not finite:
-            raise ValueError(f"{field} must be finite")
-        return float(value)
-
-    def _new_agents(self, value: object) -> list[dict[str, object]]:
-        if not isinstance(value, list) or not 1 <= len(value) <= MAX_AGENTS_PER_ROOM:
-            raise ValueError(f"agents must contain 1 to {MAX_AGENTS_PER_ROOM} members")
-        agents = [self._new_agent(agent) for agent in value]
-        profiles = [agent["profile"] for agent in agents]
-        display_keys = [agent["display_name_key"] for agent in agents]
-        if len(profiles) != len(set(profiles)):
-            raise GroupConflictError("Agent profile must be unique within a room")
-        if len(display_keys) != len(set(display_keys)):
-            raise GroupConflictError("Agent display name must be unique within a room")
-        host_count = sum(bool(agent["is_host"]) for agent in agents)
-        if host_count > 1:
-            raise GroupConflictError("Room may contain only one administrator Agent")
-        if host_count == 0:
-            agents[0]["is_host"] = True
-        return agents
-
-    def _new_agent(self, command: object) -> dict[str, object]:
-        command = self._command(
-            command,
-            {
-                "profile", "displayName", "description", "replyWithoutMention",
-                "isHost", "nodeId", "nodeLabel",
-                "model", "provider", "reasoningEffort", "fastMode",
-            },
-        )
-        execution_profile = self._profile(command.get("profile"))
-        node_id = self._node_id(command.get("nodeId", "local"))
-        profile = (
-            execution_profile
-            if node_id == "local"
-            else f"node:{node_id}:{execution_profile}"
-        )
-        node_label = command.get("nodeLabel", "")
-        if not isinstance(node_label, str) or len(node_label) > 100:
-            raise ValueError("nodeLabel must be a string up to 100 characters")
-        node_label = " ".join(node_label.split())
-        raw_name = command.get("displayName")
-        explicit_name = (
-            raw_name.strip()
-            if isinstance(raw_name, str) and raw_name.strip()
-            else ""
-        )
-        display_name, display_name_key = normalize_display_name(
-            explicit_name
-            or (
-                self._resolved_agent_name(execution_profile)
-                if node_id == "local"
-                else ""
-            )
-            or execution_profile
-        )
-        reply_without_mention = command.get("replyWithoutMention", False)
-        if not isinstance(reply_without_mention, bool):
-            raise ValueError("replyWithoutMention must be a boolean")
-        is_host = command.get("isHost", False)
-        if not isinstance(is_host, bool):
-            raise ValueError("isHost must be a boolean")
-        fast_mode = command.get("fastMode")
-        if fast_mode is not None and not isinstance(fast_mode, bool):
-            raise ValueError("fastMode must be a boolean or null")
-        if (command.get("model") is None) != (command.get("provider") is None):
-            raise ValueError("model and provider must both be set or both be null")
-        return {
-            "profile": profile,
-            "node_id": node_id,
-            "node_label": node_label,
-            "execution_profile": (
-                None if node_id == "local" else execution_profile
-            ),
-            "display_name": display_name,
-            "display_name_key": display_name_key,
-            "description": self._description(command.get("description", "")),
-            "reply_without_mention": reply_without_mention,
-            "is_host": is_host,
-            "model_override": self._agent_configuration_value(
-                command.get("model"), "model"
-            ),
-            "provider_override": self._agent_configuration_value(
-                command.get("provider"), "provider"
-            ),
-            "reasoning_effort_override": self._agent_configuration_value(
-                command.get("reasoningEffort"), "reasoningEffort"
-            ),
-            "fast_mode_override": fast_mode,
-        }
-
-    @staticmethod
-    def _agent_configuration_value(value: object, field: str) -> str | None:
-        if value is None:
-            return None
-        if not isinstance(value, str) or not value.strip():
-            raise ValueError(f"{field} must be a non-empty string or null")
-        normalized = value.strip()
-        if field == "reasoningEffort" and normalized not in {
-            "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"
-        }:
-            raise ValueError("reasoningEffort is invalid")
-        return normalized
-
-    def _resolved_agent_name(self, profile: str) -> str:
-        try:
-            value = self._agent_name_resolver(profile)
-        except Exception as error:
-            raise GroupStoreError("Agent name settings could not be read") from error
-        if not isinstance(value, str):
-            raise GroupStoreError("Agent name settings are invalid")
-        normalized = value.strip()
-        return "" if is_reserved_mention_alias(normalized) else normalized
-
-    def _insert_agent(
-        self,
-        connection: sqlite3.Connection,
-        room_id: str,
-        agent: Mapping[str, object],
-        now: float,
-    ) -> str:
-        self._check_agent_conflicts(
-            connection, room_id, agent["display_name_key"], profile=agent["profile"]
-        )
-        agent_id = str(uuid.uuid4())
-        connection.execute(
-            """INSERT INTO group_agents
-            (id, room_id, profile, node_id, node_label, execution_profile,
-             display_name, display_name_key, description,
-             reply_without_mention, is_host, model_override, provider_override,
-             reasoning_effort_override, fast_mode_override, created_at, updated_at)
-            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
-            (
-                agent_id,
-                room_id,
-                agent["profile"],
-                agent["node_id"],
-                agent["node_label"],
-                agent["execution_profile"],
-                agent["display_name"],
-                agent["display_name_key"],
-                agent["description"],
-                int(bool(agent["reply_without_mention"])),
-                int(bool(agent["is_host"])),
-                agent["model_override"],
-                agent["provider_override"],
-                agent["reasoning_effort_override"],
-                None if agent["fast_mode_override"] is None
-                else int(bool(agent["fast_mode_override"])),
-                now,
-                now,
-            ),
-        )
-        connection.execute(
-            """INSERT INTO group_agent_topic_state
-            (agent_id, topic_id, last_context_message_seq, created_at, updated_at)
-            SELECT ?, id, 0, ?, ? FROM group_topics WHERE room_id = ?""",
-            (agent_id, now, now, room_id),
-        )
-        return agent_id
-
-    @staticmethod
-    def _check_agent_conflicts(
-        connection: sqlite3.Connection,
-        room_id: str,
-        display_name_key: str,
-        *,
-        profile: str | None = None,
-        exclude_agent_id: str | None = None,
-    ) -> None:
-        exclusion = " AND id != ?" if exclude_agent_id is not None else ""
-        suffix: tuple[object, ...] = (
-            (exclude_agent_id,) if exclude_agent_id is not None else ()
-        )
-        if (
-            profile is not None
-            and connection.execute(
-                f"SELECT 1 FROM group_agents WHERE room_id = ? AND profile = ?{exclusion}",
-                (room_id, profile, *suffix),
-            ).fetchone()
-            is not None
-        ):
-            raise GroupConflictError("Agent profile must be unique within a room")
-        if (
-            connection.execute(
-                f"SELECT 1 FROM group_agents WHERE room_id = ? AND display_name_key = ?{exclusion}",
-                (room_id, display_name_key, *suffix),
-            ).fetchone()
-            is not None
-        ):
-            raise GroupConflictError("Agent display name must be unique within a room")
-
-    @staticmethod
-    def _room_wire(row: sqlite3.Row) -> dict[str, object]:
-        return {
-            "id": row["id"],
-            "name": row["name"],
-            "cwd": row["cwd"],
-            "instructions": row["instructions"],
-            "avatar": row["avatar_data_url"],
-            "maxReplyRounds": row["max_reply_rounds"],
-            "orchestrationMode": row["orchestration_mode"],
-            "createdAt": row["created_at"],
-            "updatedAt": row["updated_at"],
-            "archived": bool(row["archived"]),
-        }
-
-    @staticmethod
-    def _room_summary(
-        row: sqlite3.Row,
-        avatar_members: list[dict[str, object]] | None = None,
-    ) -> dict[str, object]:
-        return {
-            "id": row["id"],
-            "name": row["name"],
-            "cwd": row["cwd"],
-            "instructions": row["instructions"],
-            "avatar": row["avatar_data_url"],
-            "avatarMembers": avatar_members or [],
-            "maxReplyRounds": row["max_reply_rounds"],
-            "orchestrationMode": row["orchestration_mode"],
-            "createdAt": row["created_at"],
-            "updatedAt": row["updated_at"],
-            "archived": False,
-            "agentCount": row["agent_count"],
-            "topicCount": row["topic_count"],
-        }
-
-    @staticmethod
-    def _avatar_member_wire(row: sqlite3.Row) -> dict[str, object]:
-        return {
-            "profile": row["execution_profile"] or row["profile"],
-            "nodeId": row["node_id"],
-            "displayName": row["display_name"],
-        }
-
-    def _room_avatar_members(
-        self, connection: sqlite3.Connection, room_id: str
-    ) -> list[dict[str, object]]:
-        rows = connection.execute(
-            """SELECT profile, execution_profile, node_id, display_name FROM group_agents
-            WHERE room_id = ? ORDER BY created_at ASC, id ASC LIMIT 4""",
-            (room_id,),
-        ).fetchall()
-        return [self._avatar_member_wire(row) for row in rows]
-
-    @staticmethod
-    def _topic_summary(row: sqlite3.Row) -> dict[str, object]:
-        preview = str(row["preview"] or "")
-        return {
-            "id": row["id"],
-            "roomId": row["room_id"],
-            "title": row["title"],
-            "preview": preview[:_TOPIC_PREVIEW_LENGTH],
-            "messageCount": int(row["message_count"]),
-            "unreadCount": int(row["unread_count"]),
-            "latestMessageSeq": int(row["latest_message_seq"]),
-            "lastReadMessageSeq": int(row["last_read_message_seq"]),
-            "archived": bool(row["archived"]),
-            "pinned": bool(row["pinned"]),
-            "createdAt": row["created_at"],
-            "updatedAt": row["updated_at"],
-        }
-
-    @staticmethod
-    def _agent_wire(row: sqlite3.Row) -> dict[str, object]:
-        return {
-            "id": row["id"],
-            "roomId": row["room_id"],
-            "profile": row["execution_profile"] or row["profile"],
-            "nodeId": row["node_id"],
-            "nodeLabel": row["node_label"],
-            "displayName": row["display_name"],
-            "description": row["description"],
-            "storedSessionId": row["stored_session_id"],
-            "lastContextMessageSeq": row["last_context_message_seq"],
-            "enabled": bool(row["enabled"]),
-            "replyWithoutMention": bool(row["reply_without_mention"]),
-            "isHost": bool(row["is_host"]),
-            "model": row["model_override"],
-            "provider": row["provider_override"],
-            "reasoningEffort": row["reasoning_effort_override"],
-            "fastMode": None if row["fast_mode_override"] is None
-            else bool(row["fast_mode_override"]),
-            "createdAt": row["created_at"],
-            "updatedAt": row["updated_at"],
-        }
-
-    @staticmethod
-    def _canonical_uuid(value: object, field: str) -> str:
-        if not isinstance(value, str):
-            raise ValueError(f"{field} must be a canonical UUID")
-        try:
-            canonical = str(uuid.UUID(value))
-        except ValueError as error:
-            raise ValueError(f"{field} must be a canonical UUID") from error
-        if value != canonical:
-            raise ValueError(f"{field} must be a canonical UUID")
-        return canonical
-
-    @staticmethod
-    def _canonical_json(value: object) -> str:
-        try:
-            encoded = json.dumps(
-                value,
-                ensure_ascii=False,
-                sort_keys=True,
-                separators=(",", ":"),
-                allow_nan=False,
-            )
-            encoded.encode("utf-8")
-            return encoded
-        except (TypeError, ValueError, UnicodeEncodeError) as error:
-            raise ValueError("value must be strict JSON") from error
-
-    @classmethod
-    def _interaction_response_operation(
-        cls, value: object
-    ) -> tuple[str, str | None] | None:
-        if not isinstance(value, str):
-            return None
-        base, separator, interaction_id = value.partition(":")
-        operations = {
-            "interaction.approval.response": "approval",
-            "interaction.clarification.response": "clarification",
-        }
-        kind = operations.get(base)
-        if kind is None:
-            return None
-        if not separator:
-            return kind, None
-        try:
-            canonical_interaction_id = cls._interaction_id(interaction_id)
-        except ValueError:
-            return None
-        if canonical_interaction_id != interaction_id:
-            return None
-        return kind, canonical_interaction_id
-
-    @classmethod
-    def _interaction_operation(cls, kind: str, interaction_id: str) -> str:
-        if kind not in _INTERACTION_KINDS:
-            raise GroupStoreError("Stored interaction kind is corrupt")
-        canonical_interaction_id = cls._interaction_id(interaction_id)
-        if canonical_interaction_id != interaction_id:
-            raise GroupStoreError("Stored interaction identity is corrupt")
-        return f"interaction.{kind}.response:{canonical_interaction_id}"
-
-    @classmethod
-    def _idempotency_state(cls, value: object) -> dict[str, object]:
-        try:
-            state = cls._load_json(value)
-        except (TypeError, ValueError, json.JSONDecodeError) as error:
-            raise GroupStoreError("Stored interaction response is corrupt") from error
-        if not isinstance(state, dict) or cls._canonical_json(state) != value:
-            raise GroupStoreError("Stored interaction response is corrupt")
-        status = state.get("state")
-        if status == "claimed":
-            if (
-                not isinstance(state.get("interactionId"), str)
-                or state.get("kind") not in _INTERACTION_KINDS
-            ):
-                raise GroupStoreError("Stored interaction response is corrupt")
-        elif status == "completed":
-            if not isinstance(state.get("response"), dict):
-                raise GroupStoreError("Stored interaction response is corrupt")
-            interaction_status = state.get("interactionStatus", "resolved")
-            if interaction_status not in _INTERACTION_TERMINAL_STATUSES:
-                raise GroupStoreError("Stored interaction response is corrupt")
-        elif status == "failed":
-            runtime_ids = state.get("runtimeSessionIds")
-            if (
-                not isinstance(state.get("reason"), str)
-                or not isinstance(runtime_ids, list)
-                or not all(isinstance(item, str) for item in runtime_ids)
-                or len(runtime_ids) != len(set(runtime_ids))
-                or not isinstance(state.get("run"), dict)
-            ):
-                raise GroupStoreError("Stored interaction response is corrupt")
-        else:
-            raise GroupStoreError("Stored interaction response is corrupt")
-        return state
-
-    @staticmethod
-    def _runtime_envelope(response: dict[str, object]) -> dict[str, object]:
-        if "result" not in response and "runtimeSessionIds" not in response:
-            return {"result": response, "runtimeSessionIds": []}
-        result = response.get("result")
-        runtime_ids = response.get("runtimeSessionIds")
-        if not isinstance(result, dict) or not isinstance(runtime_ids, list):
-            raise GroupStoreError("Stored lifecycle response is corrupt")
-        if not all(isinstance(value, str) for value in runtime_ids):
-            raise GroupStoreError("Stored lifecycle response is corrupt")
-        if len(runtime_ids) != len(set(runtime_ids)):
-            raise GroupStoreError("Stored lifecycle response is corrupt")
-        return {"result": result, "runtimeSessionIds": runtime_ids}
-
-    @staticmethod
-    def _scoped_payload(
-        command: Mapping[str, object], room_id: str, agent_id: str | None = None
-    ) -> dict[str, object]:
-        payload: dict[str, object] = {"body": dict(command), "roomId": room_id}
-        if agent_id is not None:
-            payload["agentId"] = agent_id
-        return payload
-
-    @staticmethod
-    def _integrity_conflict(error: sqlite3.IntegrityError) -> GroupStoreError:
-        message = str(error)
-        if "group_agents.room_id, group_agents.profile" in message:
-            return GroupConflictError("Agent profile must be unique within a room")
-        if "group_agents.room_id, group_agents.display_name_key" in message:
-            return GroupConflictError("Agent display name must be unique within a room")
-        if "group_messages.client_message_id" in message:
-            return GroupConflictError("clientMessageId already exists")
-        if "group_agent_runs.runtime_session_id" in message:
-            return GroupConflictError("Runtime session is already in use")
-        return GroupStoreError("Group storage constraint failed")
-
-    @staticmethod
-    def _command(value: object, allowed: set[str]) -> dict[str, object]:
-        if not isinstance(value, Mapping) or not all(
-            isinstance(key, str) for key in value
-        ):
-            raise ValueError("command must be an object")
-        unexpected = set(value) - allowed
-        if unexpected:
-            raise ValueError(
-                f"Unexpected command fields: {', '.join(sorted(unexpected))}"
-            )
-        return dict(value)
-
-    def _command_request_id(self, command: Mapping[str, object]) -> str:
-        if "requestId" not in command:
-            raise ValueError("requestId is required")
-        return self._canonical_uuid(command["requestId"], "requestId")
-
-    @staticmethod
-    def _string(command: Mapping[str, object], key: str) -> str:
-        value = command.get(key)
-        if not isinstance(value, str):
-            raise ValueError(f"{key} must be a string")
-        return value
-
-    @staticmethod
-    def _profile(value: object) -> str:
-        if not isinstance(value, str):
-            raise ValueError("profile must be a string")
-        profile = value.strip()
-        if not 1 <= len(profile) <= 100:
-            raise ValueError("profile must contain 1 to 100 characters")
-        return profile
-
-    @staticmethod
-    def _node_id(value: object) -> str:
-        if not isinstance(value, str):
-            raise ValueError("nodeId must be a string")
-        normalized = value.strip().lower()
-        if normalized == "local":
-            return normalized
-        try:
-            canonical = str(uuid.UUID(normalized))
-        except ValueError as error:
-            raise ValueError("nodeId must be local or a canonical UUID") from error
-        if canonical != normalized:
-            raise ValueError("nodeId must be local or a canonical UUID")
-        return canonical
-
-    @staticmethod
-    def _description(value: object) -> str:
-        if not isinstance(value, str):
-            raise ValueError("description must be a string")
-        description = value.strip()
-        if len(description) > 500:
-            raise ValueError("description must contain at most 500 characters")
-        return description
-
-    @staticmethod
-    def _now() -> float:
-        return time.time()
-
-    @staticmethod
-    def _encode_cursor(updated_at: float, room_id: str) -> str:
-        raw = json.dumps([updated_at, room_id], separators=(",", ":")).encode()
-        return base64.urlsafe_b64encode(raw).decode().rstrip("=")
-
-    @classmethod
-    def _decode_cursor(cls, cursor: str) -> tuple[float, str]:
-        if (
-            not isinstance(cursor, str)
-            or not cursor
-            or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor)
-        ):
-            raise ValueError("cursor is malformed")
-        try:
-            raw = base64.b64decode(
-                cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
-            )
-            decoded = json.loads(raw.decode("utf-8"))
-            if (
-                not isinstance(decoded, list)
-                or len(decoded) != 2
-                or isinstance(decoded[0], bool)
-                or not isinstance(decoded[0], (int, float))
-                or not math.isfinite(decoded[0])
-            ):
-                raise ValueError
-            updated_at = float(decoded[0])
-            room_id = cls._canonical_uuid(decoded[1], "cursor room id")
-            if cursor != cls._encode_cursor(updated_at, room_id):
-                raise ValueError
-            return updated_at, room_id
-        except (
-            ValueError,
-            TypeError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-            binascii.Error,
-            OverflowError,
-        ) as error:
-            raise ValueError("cursor is malformed") from error
-
-    @staticmethod
-    def _encode_topic_cursor(
-        room_id: str, updated_at: float, topic_id: str
-    ) -> str:
-        raw = json.dumps(
-            ["topic", room_id, updated_at, topic_id], separators=(",", ":")
-        ).encode()
-        return base64.urlsafe_b64encode(raw).decode().rstrip("=")
-
-    @classmethod
-    def _decode_topic_cursor(
-        cls, cursor: str, expected_room_id: str
-    ) -> tuple[float, str]:
-        if (
-            not isinstance(cursor, str)
-            or not cursor
-            or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor)
-        ):
-            raise ValueError("cursor is malformed")
-        try:
-            raw = base64.b64decode(
-                cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
-            )
-            decoded = json.loads(raw.decode("utf-8"))
-            if (
-                not isinstance(decoded, list)
-                or len(decoded) != 4
-                or decoded[0] != "topic"
-                or isinstance(decoded[2], bool)
-                or not isinstance(decoded[2], (int, float))
-                or not math.isfinite(decoded[2])
-            ):
-                raise ValueError
-            room_id = cls._canonical_uuid(decoded[1], "cursor room id")
-            updated_at = float(decoded[2])
-            topic_id = cls._canonical_uuid(decoded[3], "cursor topic id")
-            if cursor != cls._encode_topic_cursor(room_id, updated_at, topic_id):
-                raise ValueError
-        except (
-            ValueError,
-            TypeError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-            binascii.Error,
-            OverflowError,
-        ) as error:
-            raise ValueError("cursor is malformed") from error
-        if room_id != expected_room_id:
-            raise ValueError("cursor does not belong to room")
-        return updated_at, topic_id
-
-    @staticmethod
-    def _encode_global_topic_cursor(
-        pinned: bool, updated_at: float, topic_id: str
-    ) -> str:
-        raw = json.dumps(
-            ["global-topic", int(pinned), updated_at, topic_id],
-            separators=(",", ":"),
-        ).encode()
-        return base64.urlsafe_b64encode(raw).decode().rstrip("=")
-
-    @classmethod
-    def _decode_global_topic_cursor(
-        cls, cursor: str
-    ) -> tuple[int, float, str]:
-        if (
-            not isinstance(cursor, str)
-            or not cursor
-            or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor)
-        ):
-            raise ValueError("cursor is malformed")
-        try:
-            raw = base64.b64decode(
-                cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
-            )
-            decoded = json.loads(raw.decode("utf-8"))
-            if (
-                not isinstance(decoded, list)
-                or len(decoded) != 4
-                or decoded[0] != "global-topic"
-                or isinstance(decoded[1], bool)
-                or decoded[1] not in (0, 1)
-                or isinstance(decoded[2], bool)
-                or not isinstance(decoded[2], (int, float))
-                or not math.isfinite(decoded[2])
-            ):
-                raise ValueError
-            pinned = int(decoded[1])
-            updated_at = float(decoded[2])
-            topic_id = cls._canonical_uuid(decoded[3], "cursor topic id")
-            if cursor != cls._encode_global_topic_cursor(
-                bool(pinned), updated_at, topic_id
-            ):
-                raise ValueError
-            return pinned, updated_at, topic_id
-        except (
-            ValueError,
-            TypeError,
-            UnicodeDecodeError,
-            json.JSONDecodeError,
-            binascii.Error,
-            OverflowError,
-        ) as error:
-            raise ValueError("cursor is malformed") from error

+ 0 - 413
hermes-plugins/yaoyao/dashboard/group_stream.py

@@ -1,413 +0,0 @@
-"""Authenticated, cursor-based event streaming for Yaoyao Group Chat."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import re
-import time
-from collections.abc import Callable, Mapping
-from typing import Any
-from uuid import UUID
-
-from fastapi import WebSocket
-from starlette.websockets import WebSocketDisconnect
-
-from .group_protocol import MAX_EVENT_BATCH_SIZE, MAX_EVENT_FRAME_BYTES
-
-
-HEARTBEAT_SECONDS = 20
-EVENT_POLL_SECONDS = 0.1
-IDLE_POLL_SECONDS = 0.5
-PLUGIN_STATE_POLL_SECONDS = 1.0
-MAX_CURSOR = 2**63 - 1
-FRAME_TOO_LARGE_CLOSE_CODE = 1009
-PLUGIN_DISABLED_CLOSE_CODE = 4404
-
-_ASCII_DECIMAL = re.compile(r"[0-9]+", flags=re.ASCII)
-_DISCONNECT_RUNTIME_MESSAGES = frozenset(
-    {
-        'cannot call "receive" once a disconnect message has been received.',
-        'cannot call "send" once a close message has been sent.',
-        'websocket is not connected. need to call "accept" first.',
-    }
-)
-
-
-def websocket_upgrade_allowed(websocket: WebSocket) -> tuple[bool, int]:
-    """Apply the core Dashboard WebSocket guards, in their required order."""
-    try:
-        from hermes_cli import web_server
-    except Exception:
-        return False, 4401
-
-    try:
-        if not web_server._ws_auth_ok(websocket):
-            return False, 4401
-    except Exception:
-        return False, 4401
-
-    try:
-        if not web_server._ws_request_is_allowed(websocket):
-            return False, 4403
-    except Exception:
-        return False, 4403
-    return True, 1000
-
-
-def parse_cursor(value: str | None) -> int:
-    """Parse an unsigned 63-bit ASCII decimal cursor without coercion."""
-    raw = "0" if value is None else value
-    if not isinstance(raw, str) or _ASCII_DECIMAL.fullmatch(raw) is None:
-        raise ValueError("cursor is malformed")
-    cursor = int(raw, 10)
-    if cursor > MAX_CURSOR:
-        raise ValueError("cursor is out of range")
-    return cursor
-
-
-def _canonical_epoch(value: object) -> str | None:
-    if not isinstance(value, str):
-        return None
-    try:
-        canonical = str(UUID(value))
-    except ValueError:
-        return None
-    return canonical if value == canonical else None
-
-
-def _epoch_matches(value: str | None, current_epoch: str) -> bool:
-    return _canonical_epoch(value) == current_epoch
-
-
-async def _store_call(
-    store_provider: Callable[[], object],
-    method: str,
-    *args: object,
-) -> Any:
-    """Resolve the shared store and perform one complete read off-loop."""
-
-    def invoke() -> Any:
-        store = store_provider()
-        return getattr(store, method)(*args)
-
-    return await asyncio.to_thread(invoke)
-
-
-def event_frame(event: Mapping[str, object]) -> dict[str, object]:
-    """Project a persisted Store event onto the exact public WS envelope."""
-    return {
-        "type": "group.event",
-        "epoch": event["epoch"],
-        "cursor": event["cursor"],
-        "roomId": event["roomId"],
-        "event": event["eventType"],
-        "payload": event["payload"],
-    }
-
-
-def _encode_frame_json(frame: object) -> str:
-    """Match Starlette's text-frame JSON encoding for byte-limit checks."""
-    return json.dumps(frame, separators=(",", ":"), ensure_ascii=False)
-
-
-async def _send_json_bounded(
-    websocket: WebSocket,
-    frame: dict[str, object],
-) -> bool:
-    """Send one v1 frame, or close without advancing a replay cursor."""
-    encoded = _encode_frame_json(frame)
-    if len(encoded.encode("utf-8")) > MAX_EVENT_FRAME_BYTES:
-        await websocket.close(code=FRAME_TOO_LARGE_CLOSE_CODE)
-        return False
-    await websocket.send_json(frame)
-    return True
-
-
-def _batch_has_different_epoch(events: object, *, epoch: str) -> bool:
-    """Return whether a shaped event belongs to another journal epoch."""
-    if not isinstance(events, list):
-        return False
-    for event in events:
-        if not isinstance(event, Mapping):
-            continue
-        event_epoch = _canonical_epoch(event.get("epoch"))
-        if event_epoch is not None and event_epoch != epoch:
-            return True
-    return False
-
-
-def _batch_is_contiguous(
-    events: object,
-    *,
-    cursor: int,
-    epoch: str,
-) -> bool:
-    if not isinstance(events, list):
-        return False
-    expected = cursor + 1
-    for event in events:
-        if not isinstance(event, Mapping):
-            return False
-        event_cursor = event.get("cursor")
-        if (
-            not isinstance(event_cursor, int)
-            or isinstance(event_cursor, bool)
-            or event_cursor != expected
-            or event.get("epoch") != epoch
-            or "roomId" not in event
-            or not isinstance(event.get("eventType"), str)
-            or not isinstance(event.get("payload"), Mapping)
-        ):
-            return False
-        expected += 1
-    return True
-
-
-async def _send_reset(
-    websocket: WebSocket,
-    store_provider: Callable[[], object],
-    *,
-    reason: str,
-    epoch: str,
-    accepted: bool,
-) -> None:
-    latest_cursor = await _store_call(store_provider, "latest_cursor")
-    if not accepted:
-        await websocket.accept()
-    if not await _send_json_bounded(
-        websocket,
-        {
-            "type": "group.reset_required",
-            "reason": reason,
-            "epoch": epoch,
-            "cursor": latest_cursor,
-        },
-    ):
-        return
-    await websocket.close(code=4409)
-
-
-async def _send_status_reset(
-    websocket: WebSocket,
-    store_provider: Callable[[], object],
-    *,
-    status: object,
-    current_epoch: str,
-    accepted: bool,
-) -> None:
-    reason = "epoch_mismatch" if status == "epoch_mismatch" else "cursor_expired"
-    epoch = current_epoch
-    if reason == "epoch_mismatch":
-        epoch = await _store_call(store_provider, "journal_epoch")
-    await _send_reset(
-        websocket,
-        store_provider,
-        reason=reason,
-        epoch=epoch,
-        accepted=accepted,
-    )
-
-
-async def _watch_disconnect(websocket: WebSocket) -> None:
-    """Wait for peer disconnect without consuming or mutating runtime state."""
-    while True:
-        message = await websocket.receive()
-        if message.get("type") == "websocket.disconnect":
-            return
-
-
-async def _pause_until_poll(
-    disconnect_task: asyncio.Task[None], seconds: float
-) -> bool:
-    done, _ = await asyncio.wait({disconnect_task}, timeout=seconds)
-    if disconnect_task not in done:
-        return True
-    await disconnect_task
-    return False
-
-
-def _is_disconnect_runtime_error(error: RuntimeError) -> bool:
-    return str(error).lower() in _DISCONNECT_RUNTIME_MESSAGES
-
-
-async def _stream_authorized(
-    websocket: WebSocket,
-    store_provider: Callable[[], object],
-    *,
-    availability_provider: Callable[[], bool] | None = None,
-) -> None:
-    if availability_provider is not None and not await asyncio.to_thread(
-        availability_provider
-    ):
-        await websocket.close(code=PLUGIN_DISABLED_CLOSE_CODE)
-        return
-
-    current_epoch = await _store_call(store_provider, "journal_epoch")
-    requested_epoch = websocket.query_params.get("epoch")
-    if not _epoch_matches(requested_epoch, current_epoch):
-        await _send_reset(
-            websocket,
-            store_provider,
-            reason="epoch_mismatch",
-            epoch=current_epoch,
-            accepted=False,
-        )
-        return
-
-    try:
-        cursor = parse_cursor(websocket.query_params.get("cursor"))
-    except ValueError:
-        await _send_reset(
-            websocket,
-            store_provider,
-            reason="cursor_expired",
-            epoch=current_epoch,
-            accepted=False,
-        )
-        return
-
-    status = await _store_call(store_provider, "cursor_status", current_epoch, cursor)
-    if status != "ok":
-        await _send_status_reset(
-            websocket,
-            store_provider,
-            status=status,
-            current_epoch=current_epoch,
-            accepted=False,
-        )
-        return
-
-    await websocket.accept()
-    if not await _send_json_bounded(
-        websocket,
-        {
-            "type": "group.ready",
-            "epoch": current_epoch,
-            "cursor": cursor,
-            "heartbeatSeconds": HEARTBEAT_SECONDS,
-        },
-    ):
-        return
-    last_activity = time.monotonic()
-    last_availability_check = last_activity
-    disconnect_task = asyncio.create_task(_watch_disconnect(websocket))
-    try:
-        while not disconnect_task.done():
-            now = time.monotonic()
-            if (
-                availability_provider is not None
-                and now - last_availability_check >= PLUGIN_STATE_POLL_SECONDS
-            ):
-                if not await asyncio.to_thread(availability_provider):
-                    await websocket.close(code=PLUGIN_DISABLED_CLOSE_CODE)
-                    return
-                last_availability_check = now
-
-            status = await _store_call(
-                store_provider, "cursor_status", current_epoch, cursor
-            )
-            if status != "ok":
-                await _send_status_reset(
-                    websocket,
-                    store_provider,
-                    status=status,
-                    current_epoch=current_epoch,
-                    accepted=True,
-                )
-                return
-
-            events = await _store_call(
-                store_provider,
-                "events_after",
-                cursor,
-                MAX_EVENT_BATCH_SIZE,
-            )
-            observed_epoch = await _store_call(store_provider, "journal_epoch")
-            if observed_epoch != current_epoch or _batch_has_different_epoch(
-                events, epoch=current_epoch
-            ):
-                await _send_reset(
-                    websocket,
-                    store_provider,
-                    reason="epoch_mismatch",
-                    epoch=observed_epoch,
-                    accepted=True,
-                )
-                return
-            if not _batch_is_contiguous(events, cursor=cursor, epoch=current_epoch):
-                await _send_reset(
-                    websocket,
-                    store_provider,
-                    reason="cursor_expired",
-                    epoch=current_epoch,
-                    accepted=True,
-                )
-                return
-
-            if disconnect_task.done():
-                await disconnect_task
-                return
-
-            for event in events:
-                next_cursor = int(event["cursor"])
-                if not await _send_json_bounded(websocket, event_frame(event)):
-                    return
-                cursor = next_cursor
-                last_activity = time.monotonic()
-
-            now = time.monotonic()
-            if not events and now - last_activity >= HEARTBEAT_SECONDS:
-                if not await _send_json_bounded(
-                    websocket,
-                    {"type": "group.heartbeat", "cursor": cursor},
-                ):
-                    return
-                last_activity = time.monotonic()
-
-            delay = EVENT_POLL_SECONDS if events else IDLE_POLL_SECONDS
-            if not await _pause_until_poll(disconnect_task, delay):
-                return
-    finally:
-        disconnect_task.cancel()
-        try:
-            await disconnect_task
-        except (asyncio.CancelledError, WebSocketDisconnect):
-            pass
-        except RuntimeError as error:
-            if not _is_disconnect_runtime_error(error):
-                raise
-
-
-async def stream_group_events(
-    websocket: WebSocket,
-    store_provider: Callable[[], object],
-) -> None:
-    """Authenticate and stream persisted events without touching Agent runtime."""
-    allowed, close_code = websocket_upgrade_allowed(websocket)
-    if not allowed:
-        await websocket.close(code=close_code)
-        return
-
-    await stream_authorized_group_events(websocket, store_provider)
-
-
-async def stream_authorized_group_events(
-    websocket: WebSocket,
-    store_provider: Callable[[], object],
-    *,
-    availability_provider: Callable[[], bool] | None = None,
-) -> None:
-    """Stream after the caller has consumed auth and request guards exactly once."""
-
-    try:
-        await _stream_authorized(
-            websocket,
-            store_provider,
-            availability_provider=availability_provider,
-        )
-    except WebSocketDisconnect:
-        return
-    except RuntimeError as error:
-        if not _is_disconnect_runtime_error(error):
-            raise

+ 0 - 11
hermes-plugins/yaoyao/dashboard/manifest.json

@@ -1,11 +0,0 @@
-{
-  "name": "yaoyao",
-  "label": "夭夭",
-  "description": "文件归档、Agent 名称、语音设置与多设备群聊",
-  "icon": "FolderOpen",
-  "version": "1.7.3",
-  "tab": { "path": "/yaoyao-files", "position": "after:files" },
-  "entry": "dist/index.js",
-  "css": "dist/style.v1.4.0.css",
-  "api": "plugin_api.py"
-}

+ 0 - 858
hermes-plugins/yaoyao/dashboard/plugin_api.py

@@ -1,858 +0,0 @@
-"""Yaoyao plugin backend routes for files, settings, voice, and group chat.
-
-Auto-mounted at /api/plugins/yaoyao/ by the dashboard plugin loader
-(web_server.py:17277). HTTP routes run behind the dashboard's session-token
-auth middleware just like core /api routes - no explicit auth dependency is
-needed (see the kanban plugin_api.py docstring for the authoritative note).
-
-Response field naming is camelCase to match iOS FileLibraryModels.swift
-CodingKeys (itemId / messageId / displayName / contentType / ...). The
-``message-files/query`` payload shape matches the existing ArchivedMessageFile
-contract so iOS keeps working with only a path-string change.
-
-This file is loaded by path as a standalone module (web_server.py:17256
-spec_from_file_location), so it puts its own directory on sys.path and imports
-its companions (store, poller) as top-level modules.
-"""
-
-from __future__ import annotations
-
-import hashlib
-import importlib.util
-import logging
-import os
-import sys
-import tempfile
-import json
-from pathlib import Path
-from typing import Any, Optional
-
-from fastapi import APIRouter, HTTPException, Query
-from fastapi.responses import FileResponse, StreamingResponse
-from pydantic import BaseModel, Field
-from urllib.parse import quote
-
-log = logging.getLogger("yaoyao.plugin_api")
-
-# Make sibling modules importable when this file is loaded by path.
-_THIS_DIR = str(Path(__file__).resolve().parent)
-if _THIS_DIR not in sys.path:
-    sys.path.insert(0, _THIS_DIR)
-
-import store  # noqa: E402
-import poller  # noqa: E402
-import voice_store  # noqa: E402
-import data_paths  # noqa: E402
-
-
-def _profile_home(profile: Optional[str]) -> Path:
-    """Resolve the Hermes profile home without consulting YaoYao state."""
-    profile_name = str(profile or "default").strip() or "default"
-    try:
-        from hermes_constants import get_default_hermes_root  # type: ignore
-
-        root = Path(get_default_hermes_root())
-    except Exception:
-        configured = os.environ.get("HERMES_HOME", "").strip()
-        root = Path(configured) if configured else Path.home() / ".hermes"
-    if profile_name == "default":
-        return root
-    try:
-        from hermes_cli.profiles import get_profile_dir  # type: ignore
-
-        return Path(get_profile_dir(profile_name))
-    except Exception:
-        return root / "profiles" / profile_name
-
-
-def _hermes_bot_name(profile: Optional[str], profile_home: Optional[Path] = None) -> str:
-    """Read the Bot Mode title, then the core Hermes display name.
-
-    Agent identity no longer falls back to YaoYao's legacy agent_settings.json.
-    """
-    try:
-        import yaml  # type: ignore
-
-        path = (profile_home or _profile_home(profile)) / "profile.yaml"
-        raw = yaml.safe_load(path.read_text(encoding="utf-8")) if path.is_file() else {}
-        if not isinstance(raw, dict):
-            return ""
-        ui_meta = raw.get("ui_meta")
-        bot_meta = ui_meta.get("hermes-bots") if isinstance(ui_meta, dict) else None
-        candidates = [
-            bot_meta.get("title") if isinstance(bot_meta, dict) else None,
-            raw.get("display_name"),
-        ]
-        for candidate in candidates:
-            if not isinstance(candidate, str):
-                continue
-            name = " ".join(candidate.split())
-            if (
-                name
-                and len(name) <= store.MAX_AGENT_NAME_LENGTH
-                and not any(ord(character) < 32 or ord(character) == 127 for character in name)
-                and not store.is_reserved_mention_alias(name)
-            ):
-                return name
-    except (OSError, TypeError, ValueError):
-        pass
-    except Exception as error:
-        log.warning("Hermes Bot name load failed for %s: %s", profile, error)
-    return ""
-
-
-def _load_group_plugin_api():
-    module_path = Path(_THIS_DIR) / "group_plugin_api.py"
-    module_name = (
-        "_hermes_yaoyao_group_api_"
-        + hashlib.sha256(str(module_path).encode("utf-8")).hexdigest()[:24]
-    )
-    loaded = sys.modules.get(module_name)
-    if loaded is not None:
-        loaded_path = getattr(loaded, "__file__", None)
-        if loaded_path is None or Path(loaded_path).resolve() != module_path.resolve():
-            raise ImportError("Yaoyao group API module identity is invalid")
-        return loaded
-
-    spec = importlib.util.spec_from_file_location(module_name, module_path)
-    if spec is None or spec.loader is None:
-        raise ImportError("Unable to load Yaoyao group API")
-    module = importlib.util.module_from_spec(spec)
-    sys.modules[module_name] = module
-    try:
-        spec.loader.exec_module(module)
-    except BaseException:
-        sys.modules.pop(module_name, None)
-        raise
-    return module
-
-
-group_plugin_api = _load_group_plugin_api()
-group_plugin_api.set_agent_name_resolver(
-    lambda profile: _hermes_bot_name(profile)
-)
-
-
-def _store_for(profile: Optional[str]):
-    """Resolve the Store for ``profile`` (default if None). Raises 404 if the
-    profile is unknown. Validates against the live profile set so a typo or a
-    not-yet-created profile returns 404 instead of silently creating an empty
-    data dir."""
-    if not profile or profile == "default":
-        return store.get_store(store.DEFAULT_DATA_ROOT)
-    # Validate: the profile must exist on disk. Use profiles_to_serve to avoid
-    # importing hermes_cli.profiles when not needed, but fall back to a path
-    # check.
-    try:
-        from hermes_cli.profiles import profile_exists  # type: ignore
-
-        if not profile_exists(profile):
-            raise HTTPException(status_code=404, detail=f"unknown profile: {profile}")
-    except HTTPException:
-        raise
-    except Exception:
-        # hermes_cli not importable (standalone runtime): best-effort path check.
-        data_root = store.data_root_for_profile(profile)
-        if not data_root.parent.parent.parent.is_dir():  # <home>/plugins/yaoyao
-            raise HTTPException(status_code=404, detail=f"unknown profile: {profile}")
-    return store.get_store(store.data_root_for_profile(profile))
-
-
-router = APIRouter()
-router.include_router(group_plugin_api.router)
-
-# Start the background archiver as soon as the module loads (the dashboard
-# loader imports this file once at server startup). Idempotent.
-try:
-    poller.start()
-except Exception:
-    log.exception("yaoyao: poller failed to start (routes still serve existing data)")
-
-
-@router.get("/maintenance/storage")
-def maintenance_storage():
-    """Report whether every profile's runtime data is safe across updates."""
-
-    profiles: list[dict[str, object]] = []
-    ready = True
-    try:
-        discovered = poller._discover_profiles()
-    except Exception as error:
-        log.warning("yaoyao: unable to discover profile storage: %s", error)
-        discovered = [("default", _profile_home("default"))]
-    seen: set[str] = set()
-    for profile, home in discovered:
-        name = str(profile or "default")
-        if name in seen:
-            continue
-        seen.add(name)
-        try:
-            status = data_paths.ensure_durable_data_root(Path(home))
-            entry = {
-                "profile": name,
-                "ready": status.ready,
-                "migrated": status.migrated,
-                "legacyPresent": status.legacy_present,
-                "conflict": status.conflict,
-            }
-        except OSError as error:
-            log.warning("yaoyao: storage migration failed for %s: %s", name, error)
-            entry = {
-                "profile": name,
-                "ready": False,
-                "migrated": False,
-                "legacyPresent": True,
-                "conflict": True,
-            }
-        ready = ready and bool(entry["ready"])
-        profiles.append(entry)
-    return {"ready": ready, "profiles": profiles}
-
-
-# ---------------------------------------------------------------------------
-# Request / response models
-# ---------------------------------------------------------------------------
-
-
-class MessageFileQueryRequest(BaseModel):
-    # Field names mirror iOS FileLibraryModels.swift MessageFileArchiveQueryRequest
-    # CodingKeys: contextType / contextId / messageIds (camelCase).
-    context_type: str = Field(default="session", alias="contextType")
-    context_id: Optional[str] = Field(default=None, alias="contextId")
-    message_ids: list[int] = Field(default_factory=list, alias="messageIds")
-
-    model_config = {"populate_by_name": True}
-
-
-class UploadBody(BaseModel):
-    # Reserved for the future upload endpoint; kept here for schema stability.
-    display_name: Optional[str] = None
-
-
-class SessionContextSnapshotBody(BaseModel):
-    used_tokens: int = Field(alias="usedTokens", gt=0)
-    limit_tokens: Optional[int] = Field(default=None, alias="limitTokens", gt=0)
-    percent: Optional[float] = Field(default=None, ge=0, le=100)
-    compressions: Optional[int] = Field(default=None, ge=0)
-    model: Optional[str] = Field(default=None, max_length=4096)
-    provider: Optional[str] = Field(default=None, max_length=4096)
-    observed_at: float = Field(alias="observedAt", gt=0)
-
-    model_config = {"populate_by_name": True}
-
-
-# ---------------------------------------------------------------------------
-# Endpoints
-# ---------------------------------------------------------------------------
-
-
-def _kind_of(item: dict) -> str:
-    return store.infer_kind(item["displayName"], item["contentType"])
-
-
-def _to_file_library_item(it: dict) -> dict:
-    """Render an attachment row as an iOS FileLibraryItem-compatible payload.
-
-    Field names match FileLibraryItem.CodingKeys (FileLibraryModels.swift):
-    id / fileId / path / name / extension / mimeType / size / modifiedAt /
-    exists / firstSeenAt / lastSeenAt / messageTimestamp / origins. The origin
-    block matches FileLibraryOrigin.CodingKeys.
-    """
-    name = it["displayName"]
-    ext = os.path.splitext(name)[1]  # includes the leading "."
-    ts = it["discoveredAt"]
-    sender = it.get("sender") or "agent"
-    author_kind = "user" if sender == "user" else "agent"
-    source_kind = "agent_generated" if sender == "agent" else "upload"
-    event_kind = "generated" if sender == "agent" else "uploaded"
-    session_id = it.get("sessionId") or ""
-    origin = {
-        "id": it["id"],
-        "sourceKind": source_kind,
-        "eventKind": event_kind,
-        "userId": None,
-        "username": "",
-        "profile": "",
-        "agent": "",
-        "agentProfile": None,
-        "agentDisplayName": None,
-        "authorKind": author_kind,
-        "authorId": None,
-        "authorName": None,
-        "contextType": "session",
-        "sessionId": session_id,
-        "sessionTitle": "",
-        "roomId": "",
-        "roomName": "",
-        "messageId": str(it["sourceMessageId"])
-        if it.get("sourceMessageId") is not None
-        else "",
-        "runId": "",
-        "workspace": "",
-        "originalPath": "",
-        "observedAt": ts,
-        "messageTimestamp": ts,
-        "messageSequence": None,
-        "messageOrdinal": None,
-    }
-    return {
-        "id": it["id"],
-        "fileId": None,
-        "path": f"yaoyao-file-library://archive/{it['id']}?name={quote(name, safe='')}",
-        "name": name,
-        "extension": ext,
-        "mimeType": it.get("contentType") or "application/octet-stream",
-        "size": it.get("byteCount", 0),
-        "modifiedAt": ts,
-        "exists": True,
-        "firstSeenAt": ts,
-        "lastSeenAt": ts,
-        "messageTimestamp": ts,
-        "origins": [origin],
-    }
-
-
-@router.get("/profiles")
-def list_profiles():
-    """Profiles with an existing state.db (i.e. ones the poller watches).
-
-    Returns ``[{name, label, botName, isDefault}]``. ``botName`` comes from
-    Hermes Bot Mode (then the core profile display name), never YaoYao's
-    legacy Agent-name setting. ``default`` is always first when present.
-    """
-    pairs = poller._discover_profiles()
-    out = []
-    for name, home in pairs:
-        bot_name = _hermes_bot_name(name, Path(home))
-        out.append(
-            {
-                "name": name,
-                "label": bot_name or ("默认" if name == "default" else name),
-                "botName": bot_name,
-                # Compatibility alias for older YaoYao clients. Its value is
-                # still Hermes-owned Bot metadata, not agent_settings.json.
-                "agentName": bot_name,
-                "isDefault": name == "default",
-            }
-        )
-    return {"profiles": out}
-
-
-@router.get("/files")
-def list_files(
-    sender: Optional[str] = Query(None, description="agent | user"),
-    kind: Optional[str] = Query(None, description="image | video | text | file"),
-    session_id: Optional[str] = Query(None),
-    search: Optional[str] = Query(None),
-    profile: Optional[str] = Query(
-        None, description="which agent's library to read (default if omitted)"
-    ),
-    limit: int = Query(50, ge=1, le=200),
-    cursor: Optional[int] = Query(
-        None, description="last item id seen, for pagination"
-    ),
-):
-    """Page over the archive, newest first. Powers both iOS list and the dashboard tab.
-
-    Each item is shaped as an iOS FileLibraryItem so the iOS list service can
-    decode the response directly. ``profile`` selects which agent's library to
-    read; omitted -> the default profile.
-    """
-    st = _store_for(profile)
-    items, next_cursor, total = st.query_attachments(
-        sender=sender,
-        kind=kind,
-        session_id=session_id,
-        search=search,
-        limit=limit,
-        cursor=cursor,
-    )
-    return {
-        "items": [_to_file_library_item(it) for it in items],
-        "nextCursor": str(next_cursor) if next_cursor is not None else None,
-        "total": total,
-        "profile": profile or "default",
-    }
-
-
-@router.get("/stats")
-def get_stats(
-    profile: Optional[str] = Query(
-        None, description="which agent's library to read (default if omitted)"
-    ),
-):
-    """Archive summary: counts and total bytes for one profile."""
-    return _store_for(profile).stats()
-
-
-@router.get("/session-context/{session_id}")
-def get_session_context(
-    session_id: str,
-    profile: Optional[str] = Query(default=None),
-):
-    """Return the last confirmed context-window reading for one chat."""
-    snapshot = _store_for(profile).get_session_context(session_id)
-    return {"snapshot": snapshot}
-
-
-@router.put("/session-context/{session_id}")
-def put_session_context(
-    session_id: str,
-    body: SessionContextSnapshotBody,
-    profile: Optional[str] = Query(default=None),
-):
-    """Persist a monotonic, profile-scoped context-window reading."""
-    snapshot = _store_for(profile).upsert_session_context(
-        session_id,
-        context_used=body.used_tokens,
-        context_limit=body.limit_tokens,
-        context_percent=body.percent,
-        compressions=body.compressions,
-        model=body.model,
-        provider=body.provider,
-        observed_at=body.observed_at,
-    )
-    return {"snapshot": snapshot}
-
-
-@router.get("/{item_id}")
-def get_item(
-    item_id: int,
-    profile: Optional[str] = Query(
-        None, description="which agent's library holds this item"
-    ),
-):
-    att = _store_for(profile).get_attachment(item_id)
-    if att is None:
-        raise HTTPException(status_code=404, detail="attachment not found")
-    return {**att, "kind": _kind_of(att)}
-
-
-@router.get("/{item_id}/download")
-def download_item(
-    item_id: int,
-    profile: Optional[str] = Query(
-        None, description="which agent's library holds this item"
-    ),
-):
-    """Stream the archived file body. Arbitrary extension; behind dashboard auth.
-
-    The static /dashboard-plugins/<name>/<file> route rejects non-browser
-    suffixes (.pdf/.zip/...) and is unauthenticated, so arbitrary file
-    downloads must live here as a FileResponse under /api/plugins/yaoyao/.
-    """
-    st = _store_for(profile)
-    att = st.get_attachment(item_id)
-    if att is None:
-        raise HTTPException(status_code=404, detail="attachment not found")
-    storage_name = st.get_object_storage_name(att["objectSha256"])
-    if storage_name is None:
-        raise HTTPException(status_code=404, detail="object body missing")
-    path = st.objects_dir / storage_name
-    if not path.is_file():
-        raise HTTPException(status_code=404, detail="object body not on disk")
-    return FileResponse(
-        path=str(path),
-        filename=att["displayName"],
-        media_type=att["contentType"] or "application/octet-stream",
-    )
-
-
-@router.post("/message-files/query")
-def query_message_files(
-    req: MessageFileQueryRequest,
-    profile: Optional[str] = Query(
-        None, description="which agent's library to read (default if omitted)"
-    ),
-):
-    """Batch-resolve archived files for a set of message ids.
-
-    Mirrors the legacy /api/hermes/file-library/message-files/query contract:
-    request {contextType, contextId, messageIds}, response
-    {messages: {<messageId>: [file, ...]}} where each file's fields match
-    iOS ArchivedMessageFile (camelCase) so a path-string change is the only
-    iOS delta needed.
-
-    ``profile`` selects which agent's library to read; omitted -> the default
-    profile. Read from the query string so iOS callers that route through the
-    shared HermesRESTClient (which sends profile via the X-Hermes-Profile
-    header) can pass it explicitly as a query item.
-    """
-    st = _store_for(profile)
-    grouped = st.query_message_files(req.message_ids)
-    out: dict[str, list[dict]] = {}
-    for mid, files in grouped.items():
-        out[str(mid)] = [
-            {
-                "itemId": f["id"],
-                "messageId": str(f["sourceMessageId"])
-                if f["sourceMessageId"] is not None
-                else "",
-                "ordinal": idx,
-                "originalPath": "",
-                "referencePath": f"/api/plugins/yaoyao/{f['id']}/download",
-                "name": f["displayName"],
-                "size": f["byteCount"],
-                "mimeType": f["contentType"],
-                "archiveStatus": "ready",
-                "archivedAt": f["discoveredAt"],
-                "availability": "archived",
-            }
-            for idx, f in enumerate(files)
-        ]
-    return {"messages": out}
-
-
-@router.post("/rescan")
-def rescan():
-    """Force one immediate poll cycle (handy after a big agent run)."""
-    try:
-        poller.poll_now()
-    except Exception:
-        log.debug("rescan: poll_now failed", exc_info=True)
-    return store.stats()
-
-
-# ===========================================================================
-# Legacy Agent display-name settings
-#
-# The profile id stays the stable routing key. ``agentName`` is an optional,
-# per-profile presentation value retained for older clients. Group Agent
-# identity and current clients use Hermes Bot metadata instead.
-#
-#   GET /agent/settings?profile=<profile>
-#   PUT /agent/settings?profile=<profile>  <- {"agentName": "..."}
-# ===========================================================================
-
-
-@router.get("/agent/settings")
-def get_agent_settings(
-    profile: Optional[str] = Query(
-        None, description="Hermes profile (default if omitted)"
-    ),
-):
-    """Read one profile's configured Agent display name."""
-    _store_for(profile)
-    return store.load_agent_settings(profile)
-
-
-@router.put("/agent/settings")
-def put_agent_settings(
-    body: dict,
-    profile: Optional[str] = Query(
-        None, description="Hermes profile (default if omitted)"
-    ),
-):
-    """Set or clear one profile's Agent display name."""
-    _store_for(profile)
-    try:
-        return store.save_agent_settings(profile, body)
-    except ValueError as error:
-        raise HTTPException(status_code=400, detail=str(error)) from error
-
-
-# ===========================================================================
-# iOS duplex voice settings
-#
-# Mirrors the yaoyao-webui ``ios-duplex-voice`` contract: one shared API key,
-# a voice list (id + name), and the currently selected voice. The iOS app
-# connects directly to the TTS provider (e.g. Volcano/doubao) for low-latency
-# duplex voice; this plugin stores the configuration it downloads.
-#
-# Endpoints (matching yaoyao-webui's /api/app/duplex-voice/* shape):
-#   GET  /voice/settings        -> {hasApiKey, voices, currentVoiceId, updatedAt}
-#   PUT  /voice/settings        <- {apiKey?, voices, currentVoiceId}
-#   GET  /voice/runtime         -> {apiKey, voices, currentVoiceId, updatedAt}
-#   PUT  /voice/current-voice   <- {currentVoiceId}
-# ===========================================================================
-
-
-@router.get("/voice/settings")
-def get_duplex_settings():
-    """Public settings for the dashboard UI (apiKey masked as hasApiKey)."""
-    return store.public_duplex_voice()
-
-
-@router.put("/voice/settings")
-def put_duplex_settings(body: dict):
-    """Update duplex voice settings. Partial: omit apiKey to keep existing.
-    Returns public settings (apiKey masked as hasApiKey), matching
-    yaoyao-webui's saveSettings controller."""
-    try:
-        store.save_duplex_voice(body)
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-    return store.public_duplex_voice()
-
-
-@router.get("/voice/runtime")
-def get_duplex_runtime():
-    """Runtime settings for the iOS app (includes the real apiKey)."""
-    return store.runtime_duplex_voice()
-
-
-@router.put("/voice/current-voice")
-def put_duplex_current_voice(body: dict):
-    """Quick-switch the current voice without re-sending the full list.
-    Returns {voices, currentVoiceId, updatedAt} (no apiKey fields), matching
-    yaoyao-webui's saveCurrentVoice controller."""
-    try:
-        store.save_duplex_voice({"currentVoiceId": body.get("currentVoiceId")})
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-    s = store.load_duplex_voice()
-    return {
-        "voices": s["voices"],
-        "currentVoiceId": s["currentVoiceId"],
-        "updatedAt": s["updatedAt"],
-    }
-
-
-# ===========================================================================
-# TTS provider settings (mirrors yaoyao-webui's /api/hermes/tts/settings/*)
-# ===========================================================================
-
-
-@router.get("/tts/settings")
-def tts_list_settings():
-    """List all configured TTS providers + the active one."""
-    return voice_store.tts_list_settings()
-
-
-@router.put("/tts/settings/active")
-def tts_set_active(body: dict):
-    try:
-        return {"activeProvider": voice_store.tts_set_active(body.get("provider", ""))}
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-@router.put("/tts/settings/{provider}")
-def tts_save_provider(provider: str, body: dict):
-    try:
-        row = voice_store.tts_save_provider(
-            provider, body.get("settings"), body.get("secrets")
-        )
-        # Optionally set active
-        if "activeProvider" in body:
-            voice_store.tts_set_active(body["activeProvider"])
-        return {"setting": row, "activeProvider": voice_store.tts_get_active()}
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-@router.delete("/tts/settings/{provider}")
-def tts_delete_provider(provider: str):
-    try:
-        deleted = voice_store.tts_delete_provider(provider)
-        return {
-            "success": True,
-            "deleted": deleted,
-            "activeProvider": voice_store.tts_get_active(),
-        }
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-@router.delete("/tts/settings/{provider}/base-url-preset")
-def tts_delete_base_url_preset(provider: str, url: str = Query(...)):
-    row = voice_store.tts_delete_base_url_preset(provider, url)
-    if row is None:
-        raise HTTPException(status_code=404, detail="provider not found")
-    return {"success": True, "setting": row}
-
-
-@router.delete("/tts/settings/{provider}/secret/{secret_name}")
-def tts_clear_secret(provider: str, secret_name: str):
-    try:
-        row = voice_store.tts_clear_secret(provider, secret_name)
-        if row is None:
-            raise HTTPException(status_code=404, detail="provider not found")
-        return {"success": True, "setting": row}
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-# ===========================================================================
-# STT provider settings (mirrors yaoyao-webui's /api/hermes/stt/settings/*)
-# ===========================================================================
-
-
-@router.get("/stt/settings")
-def stt_list_settings():
-    """List all configured STT providers + the active one."""
-    return voice_store.stt_list_settings()
-
-
-@router.put("/stt/settings/active")
-def stt_set_active(body: dict):
-    try:
-        return {"activeProvider": voice_store.stt_set_active(body.get("provider", ""))}
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-@router.put("/stt/settings/{provider}")
-def stt_save_provider(provider: str, body: dict):
-    try:
-        row = voice_store.stt_save_provider(
-            provider, body.get("settings"), body.get("secrets")
-        )
-        if "activeProvider" in body:
-            voice_store.stt_set_active(body["activeProvider"])
-        return {"setting": row, "activeProvider": voice_store.stt_get_active()}
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-@router.delete("/stt/settings/{provider}")
-def stt_delete_provider(provider: str):
-    deleted = voice_store.stt_delete_provider(provider)
-    return {
-        "success": True,
-        "deleted": deleted,
-        "activeProvider": voice_store.stt_get_active(),
-    }
-
-
-@router.delete("/stt/settings/{provider}/base-url-preset")
-def stt_delete_base_url_preset(provider: str, url: str = Query(...)):
-    row = voice_store.stt_delete_base_url_preset(provider, url)
-    if row is None:
-        raise HTTPException(status_code=404, detail="provider not found")
-    return {"success": True, "setting": row}
-
-
-@router.delete("/stt/settings/{provider}/secret/{secret_name}")
-def stt_clear_secret(provider: str, secret_name: str):
-    try:
-        row = voice_store.stt_clear_secret(provider, secret_name)
-        if row is None:
-            raise HTTPException(status_code=404, detail="provider not found")
-        return {"success": True, "setting": row}
-    except ValueError as e:
-        raise HTTPException(status_code=400, detail=str(e))
-
-
-# ===========================================================================
-# Provider info + probe
-# ===========================================================================
-
-
-@router.get("/voice/providers-info")
-def get_providers_info():
-    """Static provider metadata for the frontend picker."""
-    return voice_store.provider_info()
-
-
-class ProbeRequest(BaseModel):
-    kind: str  # 'tts' | 'stt'
-    provider: Optional[str] = None
-    compatibility: Optional[str] = None  # 'openai-compatible' | 'manual'
-    baseUrl: Optional[str] = None
-    apiKey: Optional[str] = None
-
-
-@router.post("/voice/probe")
-def probe_provider(req: ProbeRequest):
-    """Probe a TTS/STT provider's /models endpoint to validate connectivity.
-
-    Mirrors yaoyao-webui's /api/voice/providers/probe. For 'manual' mode,
-    just validates the baseUrl. For 'openai-compatible', fetches <baseUrl>/models.
-    """
-    import urllib.request
-    import urllib.error
-
-    compatibility = req.compatibility or "openai-compatible"
-    base_url = (req.baseUrl or "").strip()
-
-    if not base_url:
-        raise HTTPException(status_code=400, detail="baseUrl is required")
-
-    if not (base_url.startswith("http://") or base_url.startswith("https://")):
-        raise HTTPException(status_code=400, detail="baseUrl must be http(s)")
-
-    if compatibility == "manual":
-        return {
-            "ok": True,
-            "models": [],
-            "recommendedModel": "",
-            "errorSummary": "",
-            "manualModelAllowed": True,
-            "normalizedBaseUrl": base_url,
-        }
-
-    # openai-compatible: fetch /models
-    api_key = req.apiKey or ""
-    url = base_url.rstrip("/") + "/models"
-    headers = {"Content-Type": "application/json"}
-    if api_key:
-        headers["Authorization"] = f"Bearer {api_key}"
-
-    try:
-        request = urllib.request.Request(url, headers=headers, method="GET")
-        with urllib.request.urlopen(request, timeout=10) as resp:
-            body = resp.read().decode("utf-8", errors="replace")
-            data = json.loads(body)
-            raw_models = data.get("data", []) if isinstance(data, dict) else []
-            models = []
-            for m in raw_models[:100]:
-                mid = m.get("id", "") if isinstance(m, dict) else str(m)
-                if not mid:
-                    continue
-                mid_lower = mid.lower()
-                # TTS vs STT preference
-                if req.kind == "tts":
-                    pref = any(
-                        k in mid_lower
-                        for k in (
-                            "tts",
-                            "speech",
-                            "audio",
-                            "voice",
-                            "playai",
-                            "orpheus",
-                        )
-                    )
-                else:
-                    pref = any(
-                        k in mid_lower
-                        for k in ("whisper", "transcrib", "stt", "speech-to-text")
-                    )
-                models.append(
-                    {
-                        "id": mid,
-                        "label": mid,
-                        "capability": "preferred" if pref else "other",
-                    }
-                )
-            # Sort: preferred first
-            models.sort(key=lambda m: 0 if m["capability"] == "preferred" else 1)
-            recommended = models[0]["id"] if models else ""
-            return {
-                "ok": True,
-                "models": models,
-                "recommendedModel": recommended,
-                "errorSummary": "",
-                "manualModelAllowed": True,
-                "normalizedBaseUrl": base_url,
-            }
-    except urllib.error.HTTPError as e:
-        return {
-            "ok": False,
-            "models": [],
-            "recommendedModel": "",
-            "errorSummary": f"HTTP {e.code}",
-            "errorDetails": e.read().decode("utf-8", errors="replace")[:500],
-            "manualModelAllowed": True,
-            "normalizedBaseUrl": base_url,
-        }
-    except Exception as e:
-        return {
-            "ok": False,
-            "models": [],
-            "recommendedModel": "",
-            "errorSummary": str(e)[:200],
-            "manualModelAllowed": True,
-            "normalizedBaseUrl": base_url,
-        }

+ 0 - 510
hermes-plugins/yaoyao/dashboard/poller.py

@@ -1,510 +0,0 @@
-"""Background poller that archives files observed in hermes state.db messages.
-
-This is the "save everything that passes between agent and user" mechanism.
-It reads each profile's ``state.db`` read-only (WAL safe, ``query_only=1``)
-and copies any ``MEDIA:<path>`` referenced in assistant/user messages, plus
-any local file paths in tool results (``image_generate``, ``tts_tool``, ...)
-into the plugin's content-addressed store.
-
-Profile isolation
------------------
-Each profile (agent) - ``default``, ``yaoyao``, ``yaoer``, ``gril``,
-``succubus`` ... - has its OWN ``state.db`` and its OWN plugin data dir
-(``<profile_home>/plugin-data/yaoyao``). The poller keeps one watcher state
-per profile: a separate RO connection to that profile's state.db, its own
-mtime watermark, and its own waterline. Files are ingested into that
-profile's store with ``owner_profile=<profile name>``.
-
-Profiles are discovered via ``profiles_to_serve(multiplex=True)`` and
-re-scanned periodically so newly created profiles are picked up.
-
-Lightweight polling (no full-content scan every cycle)
-------------------------------------------------------
-Each cycle, per profile:
-  1. ``stat(state.db)`` - if mtime unchanged since last cycle, SKIP entirely
-     (no SQL). Near-zero cost. [unchanged from the original poller]
-  2. ``SELECT id FROM messages WHERE id > <waterline> LIMIT N`` - reads only
-     the rowid, never the content blob. Cheap even on a huge messages table.
-  3. Drop ids already in the plugin's ``processed_messages`` side table
-     (in-process set lookup) so a replayed/re-flushed row isn't re-read.
-  4. Only for the remaining NEW ids: ``SELECT id, session_id, role, content,
-     tool_name FROM messages WHERE id IN (...)``. This is the only place we
-     touch message content, and only for genuinely new rows.
-
-Why a side table instead of state.db triggers: we never modify state.db
-(cross-process safety; state.db is owned by the gateway). The
-``processed_messages`` table lives in the plugin's OWN index.sqlite3, which
-the dashboard process owns exclusively.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-import os
-import re
-import sqlite3
-import threading
-import time
-from pathlib import Path
-from typing import Optional
-
-import sys
-
-# When loaded by the dashboard plugin loader (web_server.py:17256) this file is
-# imported by path as a standalone module, so __package__ is None and relative
-# imports fail. Make this directory importable so `import store` works both
-# here and from plugin_api.py.
-_THIS_DIR = str(Path(__file__).resolve().parent)
-if _THIS_DIR not in sys.path:
-    sys.path.insert(0, _THIS_DIR)
-
-import store  # noqa: E402
-
-log = logging.getLogger("yaoyao.poller")
-
-POLL_INTERVAL = 2.0  # seconds between cycles (per profile: stat-first, so cheap)
-BATCH_LIMIT = 1000
-PROFILE_RESCAN_EVERY = 30  # cycles between profile re-discovery passes
-# Bump this whenever extraction learns a new persisted message shape.  Each
-# profile then replays its complete history once; Store deduplication keeps the
-# archive idempotent while newly-recognized references are added.
-SCANNER_CONTRACT_VERSION = 1
-
-# MEDIA paths are normally bare tokens.  Quoted paths additionally support
-# spaces.  A quote terminates the bare form so MEDIA references embedded in a
-# GROUP_CONTEXT_JSON string do not swallow the following JSON fields.
-MEDIA_RE = re.compile(
-    r"MEDIA:\s*(?:\"(?P<double>[^\"]+)\"|'(?P<single>[^']+)'|"
-    r"(?P<plain>[^\s\"'\\]+))"
-)
-
-# Tools whose result JSON carries a local file path we should archive.
-# Keys are the tool_name; values are the candidate JSON fields that may hold
-# a local path (URLs are skipped - only real local files get archived).
-MEDIA_TOOL_FIELDS = {
-    "image_generate": ("image", "host_image", "agent_visible_image", "outputpath", "filepath"),
-    "video_generate": ("video", "outputpath", "filepath", "path"),
-    "text_to_speech": ("audio", "outputpath", "filepath", "path"),
-    "tts_tool": ("audio", "outputpath", "filepath", "path"),
-    "write_file": (
-        "path",
-        "filepath",
-        "file_path",
-        "output_path",
-        "resolved_path",
-    ),
-}
-
-# Roles we inspect. 'session_meta'/'system' carry no user-visible files.
-TRACKED_ROLES = ("assistant", "tool", "user")
-
-
-# ---------------------------------------------------------------------------
-# state.db resolution
-# ---------------------------------------------------------------------------
-
-def _profile_state_db(profile_home: Path) -> Path:
-    """Path to a profile's state.db (profile_home / state.db)."""
-    return profile_home / "state.db"
-
-
-def _open_state_db(path: Path) -> Optional[sqlite3.Connection]:
-    """Open a read-only connection. Returns None if the db doesn't exist."""
-    if not path.is_file():
-        return None
-    try:
-        conn = sqlite3.connect(
-            f"file:{path}?mode=ro", uri=True, timeout=5.0, check_same_thread=False
-        )
-        conn.row_factory = sqlite3.Row
-        conn.execute("PRAGMA query_only=1")
-        conn.execute("PRAGMA busy_timeout=5000")
-        return conn
-    except sqlite3.Error as e:
-        log.warning("poller: cannot open %s: %s", path, e)
-        return None
-
-
-# ---------------------------------------------------------------------------
-# Path extraction (profile-independent)
-# ---------------------------------------------------------------------------
-
-def _is_local_path(s: str) -> bool:
-    """True if s looks like a real local file path (not a URL, not empty)."""
-    if not s or len(s) < 2:
-        return False
-    if "://" in s[:12]:  # http:// https:// file:// oss url etc.
-        return False
-    if s.startswith("data:"):
-        return False
-    # Must have a path-ish shape: absolute, or has an extension.
-    if s.startswith("/"):
-        return True
-    if "." in os.path.basename(s):
-        return True
-    return False
-
-
-def _paths_from_assistant(content: str) -> list[str]:
-    """MEDIA: tags in assistant/user text content."""
-    found: list[str] = []
-    for match in MEDIA_RE.finditer(content):
-        path = next((value for value in match.groups() if value is not None), "")
-        if _is_local_path(path):
-            found.append(path)
-    return found
-
-
-def _paths_from_tool(content: str, tool_name: str) -> list[str]:
-    """Local paths buried in a tool result JSON body."""
-    fields = MEDIA_TOOL_FIELDS.get(tool_name)
-    if not fields:
-        return []
-    try:
-        data = json.loads(content)
-    except (json.JSONDecodeError, TypeError):
-        return []
-    found: list[str] = []
-    if isinstance(data, dict):
-        for f in fields:
-            v = data.get(f)
-            if isinstance(v, str) and _is_local_path(v):
-                found.append(v)
-            elif isinstance(v, list):
-                for item in v:
-                    if isinstance(item, str) and _is_local_path(item):
-                        found.append(item)
-            elif isinstance(v, dict):
-                for sub in v.values():
-                    if isinstance(sub, str) and _is_local_path(sub):
-                        found.append(sub)
-    return found
-
-
-# ---------------------------------------------------------------------------
-# Profile discovery
-# ---------------------------------------------------------------------------
-
-def _discover_profiles() -> list[tuple[str, Path]]:
-    """Return ``(profile_name, profile_home)`` for every profile whose
-    ``state.db`` exists.
-
-    Always includes ``default`` (-> ``~/.hermes``) when its state.db exists.
-    Named profiles come from ``profiles_to_serve(multiplex=True)``; if that
-    import is unavailable (e.g. stripped-down runtime), falls back to a
-    directory scan of ``~/.hermes/profiles/``.
-    """
-    try:
-        from hermes_cli.profiles import profiles_to_serve  # type: ignore
-        pairs = profiles_to_serve(multiplex=True)
-    except Exception:
-        # Fallback: directory scan of ~/.hermes/profiles/ + default.
-        try:
-            env = os.environ.get("HERMES_HOME", "").strip()
-            root = Path(env) if env else Path.home() / ".hermes"
-        except Exception:
-            root = Path.home() / ".hermes"
-        pairs = [("default", root)]
-        prof_root = root / "profiles"
-        if prof_root.is_dir():
-            for entry in sorted(prof_root.iterdir()):
-                if entry.is_dir() and re.match(r"^[a-z0-9][a-z0-9_-]{0,63}$", entry.name):
-                    pairs.append((entry.name, entry))
-
-    # Keep only profiles whose state.db exists (a profile dir may exist but
-    # never have been started -> no state.db -> nothing to watch).
-    out: list[tuple[str, Path]] = []
-    for name, home in pairs:
-        try:
-            home = Path(home)
-        except Exception:
-            continue
-        if _profile_state_db(home).is_file():
-            out.append((name, home))
-    if not out:
-        log.debug("poller: no profiles with an existing state.db found")
-    return out
-
-
-# ---------------------------------------------------------------------------
-# Per-profile watcher state
-# ---------------------------------------------------------------------------
-
-class _ProfileWatcher:
-    """State for one profile: RO state.db conn + waterline + mtime."""
-
-    __slots__ = ("profile", "home", "db_path", "data_root", "store",
-                 "conn", "last_id", "last_mtime", "max_known_id")
-
-    def __init__(self, profile: str, home: Path):
-        self.profile = profile
-        self.home = Path(home)
-        self.db_path = _profile_state_db(self.home)
-        self.data_root = store.data_root_for_profile(profile)
-        self.store = store.get_store(self.data_root)
-        self.conn: Optional[sqlite3.Connection] = None
-        self.last_id = 0
-        self.last_mtime: int = -1
-        # Highest message id known to exist at connect time. While last_id <
-        # max_known_id we're still backfilling history and must NOT short-circuit
-        # on mtime (the db isn't changing during a historical catch-up, but
-        # there's still work to do).
-        self.max_known_id: int = 0
-
-    def ensure_connection(self) -> Optional[sqlite3.Connection]:
-        if self.conn is not None:
-            return self.conn
-        conn = _open_state_db(self.db_path)
-        if conn is None:
-            return None
-        self.conn = conn
-        self._establish_baseline()
-        log.info("poller[%s]: connected to %s, waterline=%d",
-                 self.profile, self.db_path, self.last_id)
-        return conn
-
-    def _establish_baseline(self) -> None:
-        """Set the starting waterline for this profile.
-
-        On a fresh profile we start at id=0 so the ENTIRE history is archived
-        - existing files referenced by old messages are exactly what users
-        expect to see in the library ("谁的文件" includes files exchanged in
-        past conversations). The ``processed_messages`` side table keeps this
-        idempotent: a one-time backfill, after which each cycle only touches
-        genuinely new ids.
-
-        If we already scanned some messages (resumed after a restart), the
-        waterline is taken from ``processed_messages`` so we never re-read
-        content for already-archived rows.
-        """
-        if self.store.prepare_scanner_version(SCANNER_CONTRACT_VERSION):
-            log.info(
-                "poller[%s]: scanner contract v%d requires a full-session replay",
-                self.profile,
-                SCANNER_CONTRACT_VERSION,
-            )
-        wl = self.store.processed_waterline()
-        if wl > 0:
-            self.last_id = wl
-            # Even on resume we need max_known_id to detect catch-up. Probe it
-            # lazily on first poll if it's still 0.
-            try:
-                row = self.conn.execute("SELECT MAX(id) FROM messages").fetchone()
-                self.max_known_id = int(row[0] or 0)
-            except Exception:
-                self.max_known_id = 0
-            log.info("poller[%s]: resumed at message id=%d (from processed_messages, max=%d)",
-                     self.profile, wl, self.max_known_id)
-            return
-        # Fresh: start from 0 to backfill history.
-        try:
-            row = self.conn.execute("SELECT MAX(id) FROM messages").fetchone()
-            total = int(row[0] or 0)
-        except Exception:
-            total = 0
-        self.last_id = 0
-        self.max_known_id = total
-        log.info("poller[%s]: backfill from id=0 (history has %d messages)",
-                 self.profile, total)
-
-    def close(self) -> None:
-        if self.conn is not None:
-            try:
-                self.conn.close()
-            except Exception:
-                pass
-            self.conn = None
-
-
-# ---------------------------------------------------------------------------
-# Poll loop (one cycle, one profile)
-# ---------------------------------------------------------------------------
-
-def _process_rows(watcher: _ProfileWatcher, rows: list[sqlite3.Row]) -> None:
-    """Extract + ingest every file path in ``rows``; mark them processed."""
-    profile = watcher.profile
-    st = watcher.store
-    for row in rows:
-        mid = int(row["id"])
-        role = row["role"]
-        content = row["content"] or ""
-        session_id = row["session_id"]
-        tool_name = row["tool_name"]
-
-        if role == "tool":
-            paths = _paths_from_tool(content, tool_name or "")
-            sender = "agent"
-            kind = "tool_result"
-        else:
-            paths = _paths_from_assistant(content)
-            sender = "user" if role == "user" else "agent"
-            kind = "media_tag"
-
-        for p in paths:
-            try:
-                st.ingest(
-                    p,
-                    sender=sender,
-                    source_kind=kind,
-                    source_message_id=mid,
-                    session_id=session_id,
-                    tool_name=tool_name,
-                    display_name=os.path.basename(p) or Path(p).name,
-                    owner_profile=profile,
-                )
-            except Exception as e:
-                log.debug("poller[%s]: ingest %s failed: %s", profile, p, e)
-        # Mark processed even if no paths were found, so we never re-read it.
-        st.mark_processed(mid)
-
-
-def _poll_profile(watcher: _ProfileWatcher) -> None:
-    """One poll cycle for one profile. Lightweight: stat -> id-only probe ->
-    fetch content only for genuinely new, unprocessed rows."""
-    conn = watcher.ensure_connection()
-    if conn is None:
-        return
-
-    # mtime short-circuit: if state.db hasn't changed since last cycle, skip
-    # the SQL entirely. This is the common steady-state case (no new messages).
-    # BUT only when we've finished the historical backfill (last_id >=
-    # max_known_id). While catching up on history the db isn't changing, yet
-    # there's still work to do, so we must keep probing.
-    try:
-        mtime = int(watcher.db_path.stat().st_mtime)
-    except OSError:
-        return
-    backfilling = watcher.last_id < watcher.max_known_id
-    if not backfilling and mtime == watcher.last_mtime:
-        return
-
-    # id-only probe: read just rowids for messages past the waterline. Never
-    # touches the content blob, so it's cheap even on a huge messages table.
-    try:
-        id_rows = conn.execute(
-            "SELECT id FROM messages "
-            "WHERE id > ? AND role IN ('assistant','tool','user') "
-            "ORDER BY id LIMIT ?",
-            (watcher.last_id, BATCH_LIMIT),
-        ).fetchall()
-    except sqlite3.Error as e:
-        log.warning("poller[%s]: id probe failed: %s; reopening", watcher.profile, e)
-        watcher.close()
-        return
-
-    if not id_rows:
-        watcher.last_mtime = mtime
-        return
-
-    new_ids = [int(r["id"]) for r in id_rows]
-    # Drop ids we've already scanned (replayed / re-flushed rows).
-    already = watcher.store.processed_set(new_ids)
-    fresh = [i for i in new_ids if i not in already]
-    if not fresh:
-        # All already processed; just advance waterline + mtime.
-        watcher.last_id = max(new_ids)
-        watcher.last_mtime = mtime
-        return
-
-    # Fetch content ONLY for genuinely new rows.
-    placeholders = ",".join("?" * len(fresh))
-    try:
-        rows = conn.execute(
-            f"SELECT id, session_id, role, content, tool_name FROM messages "
-            f"WHERE id IN ({placeholders})",
-            fresh,
-        ).fetchall()
-    except sqlite3.Error as e:
-        log.warning("poller[%s]: content fetch failed: %s", watcher.profile, e)
-        return
-
-    _process_rows(watcher, rows)
-    watcher.last_id = max(new_ids)
-    watcher.last_mtime = mtime
-    log.debug("poller[%s]: processed %d new messages, waterline %d",
-              watcher.profile, len(fresh), watcher.last_id)
-
-
-# ---------------------------------------------------------------------------
-# Lifecycle
-# ---------------------------------------------------------------------------
-
-_lock = threading.Lock()
-_watchers: dict[str, _ProfileWatcher] = {}
-_cycle_count = 0
-_stop_event: Optional[threading.Event] = None
-_thread: Optional[threading.Thread] = None
-
-
-def _refresh_profiles() -> None:
-    """Reconcile the watcher set with the on-disk profiles.
-
-    Adds watchers for newly-seen profiles; leaves removed profiles' watchers
-    in place (their state.db still exists on disk - we keep reading it until
-    the dir is gone, then they just never get new data).
-    """
-    discovered = _discover_profiles()
-    for name, home in discovered:
-        if name not in _watchers:
-            try:
-                w = _ProfileWatcher(name, home)
-                # init the store so the data dir exists immediately
-                w.store.init()
-                _watchers[name] = w
-                log.info("poller[%s]: watching %s", name, w.db_path)
-            except Exception as e:
-                log.warning("poller[%s]: failed to set up watcher: %s", name, e)
-
-
-def poll_now() -> None:
-    """Run one poll cycle across all profiles. Idempotent / thread-safe."""
-    global _cycle_count
-    with _lock:
-        _cycle_count += 1
-        if _cycle_count % PROFILE_RESCAN_EVERY == 0:
-            _refresh_profiles()
-        elif not _watchers:
-            _refresh_profiles()
-        for name, watcher in list(_watchers.items()):
-            try:
-                _poll_profile(watcher)
-            except Exception as e:
-                log.debug("poller[%s]: cycle error: %s", name, e)
-
-
-def _loop(stop_event: threading.Event) -> None:
-    log.info("poller: started (interval=%.1fs)", POLL_INTERVAL)
-    while not stop_event.is_set():
-        try:
-            poll_now()
-        except Exception as e:
-            log.exception("poller: unexpected error: %s", e)
-        stop_event.wait(POLL_INTERVAL)
-    # Clean up connections on stop.
-    for watcher in _watchers.values():
-        watcher.close()
-    _watchers.clear()
-    log.info("poller: stopped")
-
-
-def start() -> None:
-    """Start the poller daemon thread. Idempotent."""
-    global _stop_event, _thread
-    if _thread is not None and _thread.is_alive():
-        return
-    with _lock:
-        _refresh_profiles()
-    _stop_event = threading.Event()
-    _thread = threading.Thread(
-        target=_loop, args=(_stop_event,), name="yaoyao-poller", daemon=True
-    )
-    _thread.start()
-    log.info("poller: starting (profiles=%s)", sorted(_watchers.keys()))
-
-
-def stop() -> None:
-    """Signal the poller to stop (for tests / clean shutdown)."""
-    global _stop_event
-    if _stop_event is not None:
-        _stop_event.set()

+ 0 - 1166
hermes-plugins/yaoyao/dashboard/store.py

@@ -1,1166 +0,0 @@
-"""Content-addressed file store + SQLite index for the yaoyao file library.
-
-One row in ``attachments`` == one file observed in one message. Identical
-file bodies are deduplicated via the ``objects`` table (keyed by sha256), so
-storing the same image N times costs one copy on disk.
-
-Profile isolation
------------------
-Each profile (agent) gets its OWN durable data directory:
-``<profile_home>/plugin-data/yaoyao/{index.sqlite3, objects/}``. Legacy
-``<profile_home>/plugins/yaoyao/data`` trees are moved there once before the
-store opens. A ``Store`` instance owns one connection per
-``data_root``; the module keeps a small cache keyed by resolved path so
-callers passing the same ``data_root`` share a connection.
-
-This store never touches the hermes ``state.db`` - it is fully isolated.
-"""
-
-from __future__ import annotations
-
-import copy
-import hashlib
-import json
-import logging
-import math
-import mimetypes
-import os
-import sqlite3
-import threading
-import time
-from pathlib import Path
-from typing import Any, Optional
-
-try:
-    from .group_protocol import is_reserved_mention_alias
-    from .data_paths import DURABLE_DATA_SUBPATH, ensure_durable_data_root
-except ImportError:  # Loaded by the Dashboard plugin loader as a top-level module.
-    from group_protocol import is_reserved_mention_alias
-    from data_paths import DURABLE_DATA_SUBPATH, ensure_durable_data_root
-
-log = logging.getLogger("yaoyao.store")
-
-# ---------------------------------------------------------------------------
-# Paths
-# ---------------------------------------------------------------------------
-PLUGIN_ROOT = Path(__file__).resolve().parent.parent  # ~/.hermes/plugins/yaoyao
-# An installed plugin root is <profile_home>/plugins/yaoyao. Keeping this
-# derivation local also makes source-tree tests independent of the real home.
-DEFAULT_PROFILE_HOME = Path(
-    os.environ.get("HERMES_HOME") or PLUGIN_ROOT.parent.parent
-).expanduser().resolve()
-DEFAULT_DATA_PATH_STATUS = ensure_durable_data_root(DEFAULT_PROFILE_HOME)
-DEFAULT_DATA_ROOT = DEFAULT_DATA_PATH_STATUS.data_root
-
-# Back-compatible public constant used by callers resolving named profiles.
-PLUGIN_DATA_SUBPATH = DURABLE_DATA_SUBPATH
-
-_SCHEMA = """
-CREATE TABLE IF NOT EXISTS objects (
-    sha256        TEXT PRIMARY KEY,
-    storage_name  TEXT NOT NULL,
-    byte_count    INTEGER NOT NULL,
-    content_type  TEXT,
-    created_at    INTEGER NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS attachments (
-    id                 INTEGER PRIMARY KEY AUTOINCREMENT,
-    object_sha256      TEXT NOT NULL REFERENCES objects(sha256),
-    display_name       TEXT NOT NULL,
-    content_type       TEXT,
-    byte_count         INTEGER NOT NULL,
-    sender             TEXT NOT NULL,
-    source_kind        TEXT NOT NULL,
-    source_message_id  INTEGER,
-    session_id         TEXT,
-    tool_name          TEXT,
-    owner_profile      TEXT NOT NULL DEFAULT 'default',
-    discovered_at      INTEGER NOT NULL,
-    UNIQUE(source_message_id, display_name, object_sha256)
-);
-
-CREATE INDEX IF NOT EXISTS idx_att_sender     ON attachments(sender);
-CREATE INDEX IF NOT EXISTS idx_att_session    ON attachments(session_id);
-CREATE INDEX IF NOT EXISTS idx_att_discovered ON attachments(discovered_at);
-CREATE INDEX IF NOT EXISTS idx_att_kind       ON attachments(source_kind);
-
--- Outbox-style side table: which message ids have already been scanned.
--- Lets the poller do a cheap `SELECT id FROM messages WHERE id > ?` against
--- state.db and skip rows already here, instead of re-reading content for
--- every message on each cycle. Lives in THIS db (the plugin's own), never in
--- state.db.
-CREATE TABLE IF NOT EXISTS processed_messages (
-    message_id    INTEGER PRIMARY KEY,
-    processed_at  INTEGER NOT NULL
-);
-
--- Version the extraction contract separately from the database schema.  When
--- the poller learns how to recognize a new file-reference shape, it can clear
--- only the cheap processed-message waterline and replay history without
--- deleting archived objects or attachment metadata.
-CREATE TABLE IF NOT EXISTS scanner_metadata (
-    key    TEXT PRIMARY KEY,
-    value  TEXT NOT NULL
-);
-
--- Last authoritative context-window snapshot for an ordinary Hermes chat.
--- The database itself is already profile-scoped, so session_id is sufficient
--- as the primary key and no profile value can leak across stores.
-CREATE TABLE IF NOT EXISTS session_context_snapshots (
-    session_id       TEXT PRIMARY KEY,
-    context_used     INTEGER NOT NULL,
-    context_limit    INTEGER,
-    context_percent  REAL,
-    compressions     INTEGER,
-    model            TEXT,
-    provider         TEXT,
-    observed_at      REAL NOT NULL,
-    updated_at       REAL NOT NULL
-);
-
-CREATE INDEX IF NOT EXISTS idx_session_context_updated
-    ON session_context_snapshots(updated_at DESC);
-"""
-
-# Additive migrations run once per data_root at init time. Each is idempotent:
-# ALTER TABLE ... ADD COLUMN errors if the column exists, so we catch it.
-#
-# These run BEFORE the owner_profile INDEX is created (below), so an existing
-# DB that predates the column gets it added before we try to index it.
-_MIGRATIONS = [
-    "ALTER TABLE attachments ADD COLUMN owner_profile TEXT NOT NULL DEFAULT 'default'",
-]
-
-
-def _dedup_attachments(conn: sqlite3.Connection) -> None:
-    """Remove duplicate attachment rows, keeping the lowest-id row per
-    (owner_profile, display_name, object_sha256).
-
-    Runs once per DB after the owner_profile column exists. Idempotent: if no
-    duplicates remain it's a no-op. Needed because the original dedup key was
-    (source_message_id, ...) so a file referenced by N messages left N rows;
-    the new dedup key is (owner_profile, display_name, sha256) so the same
-    file is archived once regardless of how many messages reference it.
-    """
-    try:
-        conn.execute(
-            "DELETE FROM attachments WHERE id IN ("
-            "  SELECT a.id FROM attachments a "
-            "  JOIN ("
-            "    SELECT owner_profile, display_name, object_sha256, MIN(id) AS keep_id "
-            "    FROM attachments "
-            "    GROUP BY owner_profile, display_name, object_sha256"
-            "  ) k ON a.owner_profile=k.owner_profile "
-            "       AND a.display_name=k.display_name "
-            "       AND a.object_sha256=k.object_sha256 "
-            "  WHERE a.id <> k.keep_id"
-            ")"
-        )
-        conn.commit()
-    except sqlite3.Error as e:
-        log.warning("dedup_attachments failed: %s", e)
-
-
-# Indexes that depend on a migrated column. Created after migrations so the
-# column is guaranteed present on both fresh and pre-existing DBs. The unique
-# index enforces the new dedup key (owner_profile, display_name, sha256) so the
-# same file is never archived twice in one profile.
-_POST_MIGRATION_SCHEMA = """
-CREATE INDEX IF NOT EXISTS idx_att_profile ON attachments(owner_profile);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_att_dedup
-    ON attachments(owner_profile, display_name, object_sha256);
-"""
-
-
-def _ensure_dirs(data_root: Optional[Path] = None) -> None:
-    """Ensure the data dir + objects/ exist. Defaults to the default profile."""
-    root = data_root if data_root is not None else DEFAULT_DATA_ROOT
-    root.mkdir(parents=True, exist_ok=True)
-    (root / "objects").mkdir(parents=True, exist_ok=True)
-
-
-# Back-compat: the pre-profile module exposed a module-level DATA_ROOT. Some
-# companions (voice_store) still import it. Keep it pointing at the default
-# profile's data dir.
-DATA_ROOT = DEFAULT_DATA_ROOT
-
-
-def _connect(data_root: Path) -> sqlite3.Connection:
-    """Open a read-write connection to a profile's own index database.
-
-    This is NOT the hermes state.db - it is a separate SQLite file owned by
-    this plugin. WAL mode + a short busy_timeout so the poller thread and the
-    FastAPI request threads can interleave reads/writes without blocking.
-    """
-    _ensure_dirs(data_root)
-    db_path = data_root / "index.sqlite3"
-    conn = sqlite3.connect(str(db_path), timeout=5.0, check_same_thread=False)
-    conn.row_factory = sqlite3.Row
-    conn.execute("PRAGMA journal_mode=WAL")
-    conn.execute("PRAGMA busy_timeout=5000")
-    conn.execute("PRAGMA synchronous=NORMAL")
-    conn.executescript(_SCHEMA)
-    for stmt in _MIGRATIONS:
-        try:
-            conn.execute(stmt)
-        except sqlite3.OperationalError:
-            pass  # column already exists
-    # Dedup BEFORE creating the unique index (the index would fail to build on
-    # a DB that still has the old per-message duplicates).
-    _dedup_attachments(conn)
-    conn.executescript(_POST_MIGRATION_SCHEMA)
-    return conn
-
-
-# ---------------------------------------------------------------------------
-# Per-data_root Store
-# ---------------------------------------------------------------------------
-# A single process (the dashboard) may talk to several profiles' data dirs.
-# Keep one connection per resolved data_root, guarded by a per-root lock so
-# the poller thread and request threads interleave cleanly.
-
-class Store:
-    """Content-addressed store bound to one ``data_root`` (one profile).
-
-    Holds one SQLite connection (WAL) + a threading lock. Safe to call from
-    multiple threads within the owning process. Each profile gets its own
-    Store instance; the module caches them by resolved path.
-    """
-
-    __slots__ = ("data_root", "objects_dir", "_conn", "_lock")
-
-    def __init__(self, data_root: Path):
-        self.data_root = Path(data_root).resolve()
-        self.objects_dir = self.data_root / "objects"
-        self._conn: Optional[sqlite3.Connection] = None
-        self._lock = threading.Lock()
-
-    @property
-    def state_file(self) -> Path:
-        return self.data_root / "state.json"
-
-    def init(self) -> sqlite3.Connection:
-        """Lazily create the DB + tables. Returns the connection. Idempotent."""
-        if self._conn is None:
-            self._conn = _connect(self.data_root)
-        return self._conn
-
-    # -- content-type + kind inference -------------------------------------
-
-    def ingest(
-        self,
-        src_path: str,
-        *,
-        sender: str,
-        source_kind: str,
-        source_message_id: Optional[int],
-        session_id: Optional[str],
-        tool_name: Optional[str] = None,
-        display_name: Optional[str] = None,
-        owner_profile: str = "default",
-        discovered_at: Optional[int] = None,
-    ) -> Optional[int]:
-        """Archive one file. Returns the attachment id, or None on skip/failure.
-
-        Skips (returns None) when:
-          - the source file does not exist (agent wrote to /tmp then it was cleaned)
-          - it's not a regular file (dir / socket / fifo)
-          - it's already archived for this (message_id, display_name, sha256)
-
-        The body is content-addressed: identical bytes are stored once.
-        """
-        p = Path(src_path)
-        try:
-            if not p.is_file():
-                log.debug("ingest: skip non-file %s", src_path)
-                return None
-        except OSError as e:
-            log.debug("ingest: cannot stat %s: %s", src_path, e)
-            return None
-
-        name = display_name or p.name
-        try:
-            sha256, size = _sha256_of_file(p)
-        except OSError as e:
-            log.warning("ingest: cannot read %s: %s", src_path, e)
-            return None
-
-        content_type = guess_content_type(src_path, name)
-        ts = int(discovered_at if discovered_at is not None else time.time())
-
-        conn = self.init()
-        try:
-            with self._lock:
-                cur = conn.execute(
-                    "SELECT 1 FROM objects WHERE sha256=?", (sha256,)
-                )
-                if cur.fetchone() is None:
-                    storage_name = _copy_to_objects(p, sha256, name, self.objects_dir)
-                    conn.execute(
-                        "INSERT INTO objects(sha256, storage_name, byte_count, content_type, created_at) "
-                        "VALUES(?,?,?,?,?)",
-                        (sha256, storage_name, size, content_type, ts),
-                    )
-                conn.commit()
-        except Exception as e:
-            log.warning("ingest: object insert failed: %s", e)
-            return None
-
-        try:
-            with self._lock:
-                # Dedup by (owner_profile, display_name, sha256): the SAME file
-                # (same bytes + same name in the same profile) is archived ONCE,
-                # no matter how many messages reference it. This keeps the list
-                # free of duplicates when an agent resends/replays an image
-                # across multiple messages. The first occurrence wins; later
-                # references just return the existing attachment id.
-                cur = conn.execute(
-                    "SELECT id FROM attachments "
-                    "WHERE owner_profile=? AND display_name=? AND object_sha256=?",
-                    (owner_profile, name, sha256),
-                )
-                existing = cur.fetchone()
-                if existing:
-                    return existing["id"]
-
-                cur = conn.execute(
-                    "INSERT INTO attachments("
-                    "object_sha256, display_name, content_type, byte_count, sender, "
-                    "source_kind, source_message_id, session_id, tool_name, "
-                    "owner_profile, discovered_at"
-                    ") VALUES(?,?,?,?,?,?,?,?,?,?,?)",
-                    (sha256, name, content_type, size, sender,
-                     source_kind, source_message_id, session_id, tool_name,
-                     owner_profile, ts),
-                )
-                conn.commit()
-                return cur.lastrowid
-        except sqlite3.IntegrityError:
-            # UNIQUE race - fetch existing
-            cur = conn.execute(
-                "SELECT id FROM attachments "
-                "WHERE owner_profile=? AND display_name=? AND object_sha256=?",
-                (owner_profile, name, sha256),
-            )
-            row = cur.fetchone()
-            return row["id"] if row else None
-        except Exception as e:
-            log.warning("ingest: attachment insert failed: %s", e)
-            return None
-
-    # -- processed-messages side table -------------------------------------
-
-    def mark_processed(self, message_id: int) -> None:
-        conn = self.init()
-        with self._lock:
-            conn.execute(
-                "INSERT OR IGNORE INTO processed_messages(message_id, processed_at) "
-                "VALUES(?,?)",
-                (message_id, int(time.time())),
-            )
-            conn.commit()
-
-    def processed_set(self, message_ids: list[int]) -> set[int]:
-        """Return the subset of ``message_ids`` already in processed_messages."""
-        if not message_ids:
-            return set()
-        conn = self.init()
-        placeholders = ",".join("?" * len(message_ids))
-        rows = conn.execute(
-            f"SELECT message_id FROM processed_messages WHERE message_id IN ({placeholders})",
-            message_ids,
-        ).fetchall()
-        return {int(r["message_id"]) for r in rows}
-
-    def processed_waterline(self) -> int:
-        """Highest message_id we've already scanned (0 if none)."""
-        conn = self.init()
-        row = conn.execute(
-            "SELECT MAX(message_id) AS m FROM processed_messages"
-        ).fetchone()
-        return int(row["m"]) if row and row["m"] is not None else 0
-
-    def prepare_scanner_version(self, version: int) -> bool:
-        """Prepare ``processed_messages`` for the current extraction contract.
-
-        Returns ``True`` exactly once for each new version.  The archived file
-        rows and content-addressed objects stay intact; only the scan waterline
-        is reset so every historical session is replayed with the new rules.
-        """
-        if version < 1:
-            raise ValueError("scanner version must be positive")
-        conn = self.init()
-        requested = str(version)
-        with self._lock:
-            row = conn.execute(
-                "SELECT value FROM scanner_metadata WHERE key='contract_version'"
-            ).fetchone()
-            if row is not None and row["value"] == requested:
-                return False
-            conn.execute("DELETE FROM processed_messages")
-            conn.execute(
-                "INSERT INTO scanner_metadata(key, value) VALUES('contract_version', ?) "
-                "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
-                (requested,),
-            )
-            conn.commit()
-        return True
-
-    # -- ordinary-session context snapshots -------------------------------
-
-    def upsert_session_context(
-        self,
-        session_id: str,
-        *,
-        context_used: int,
-        context_limit: Optional[int],
-        context_percent: Optional[float],
-        compressions: Optional[int],
-        model: Optional[str],
-        provider: Optional[str],
-        observed_at: float,
-    ) -> dict[str, Any]:
-        """Persist the newest confirmed context-window reading for a session.
-
-        ``observed_at`` makes writes monotonic across reconnects and devices:
-        a delayed request can never replace a newer model turn.
-        """
-        canonical_id = self._session_context_id(session_id)
-        if isinstance(context_used, bool) or not isinstance(context_used, int):
-            raise ValueError("contextUsed must be an integer")
-        if context_used <= 0:
-            raise ValueError("contextUsed must be positive")
-        if context_limit is not None and (
-            isinstance(context_limit, bool)
-            or not isinstance(context_limit, int)
-            or context_limit <= 0
-        ):
-            raise ValueError("contextLimit must be positive or null")
-        if context_percent is not None and (
-            isinstance(context_percent, bool)
-            or not isinstance(context_percent, (int, float))
-            or not math.isfinite(float(context_percent))
-            or not 0 <= float(context_percent) <= 100
-        ):
-            raise ValueError("contextPercent must be between 0 and 100")
-        if compressions is not None and (
-            isinstance(compressions, bool)
-            or not isinstance(compressions, int)
-            or compressions < 0
-        ):
-            raise ValueError("compressions must be non-negative or null")
-        if (
-            isinstance(observed_at, bool)
-            or not isinstance(observed_at, (int, float))
-            or not math.isfinite(float(observed_at))
-            or observed_at <= 0
-        ):
-            raise ValueError("observedAt must be a positive timestamp")
-        normalized_model = self._optional_context_label(model, "model")
-        normalized_provider = self._optional_context_label(provider, "provider")
-        percentage = (
-            float(context_percent)
-            if context_percent is not None
-            else (
-                min(100.0, max(0.0, context_used / context_limit * 100.0))
-                if context_limit is not None
-                else None
-            )
-        )
-        now = time.time()
-        conn = self.init()
-        with self._lock:
-            conn.execute(
-                """INSERT INTO session_context_snapshots
-                (session_id, context_used, context_limit, context_percent,
-                 compressions, model, provider, observed_at, updated_at)
-                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
-                ON CONFLICT(session_id) DO UPDATE SET
-                    context_used = excluded.context_used,
-                    context_limit = excluded.context_limit,
-                    context_percent = excluded.context_percent,
-                    compressions = excluded.compressions,
-                    model = excluded.model,
-                    provider = excluded.provider,
-                    observed_at = excluded.observed_at,
-                    updated_at = excluded.updated_at
-                WHERE excluded.observed_at >= session_context_snapshots.observed_at""",
-                (
-                    canonical_id,
-                    context_used,
-                    context_limit,
-                    percentage,
-                    compressions,
-                    normalized_model,
-                    normalized_provider,
-                    float(observed_at),
-                    now,
-                ),
-            )
-            conn.commit()
-            row = conn.execute(
-                "SELECT * FROM session_context_snapshots WHERE session_id = ?",
-                (canonical_id,),
-            ).fetchone()
-        if row is None:
-            raise RuntimeError("session context snapshot was not persisted")
-        return self._session_context_payload(row)
-
-    def get_session_context(self, session_id: str) -> Optional[dict[str, Any]]:
-        canonical_id = self._session_context_id(session_id)
-        conn = self.init()
-        with self._lock:
-            row = conn.execute(
-                "SELECT * FROM session_context_snapshots WHERE session_id = ?",
-                (canonical_id,),
-            ).fetchone()
-        return None if row is None else self._session_context_payload(row)
-
-    @staticmethod
-    def _session_context_id(value: str) -> str:
-        if not isinstance(value, str):
-            raise ValueError("sessionId must be a string")
-        normalized = value.strip()
-        if not normalized or len(normalized.encode("utf-8")) > 4096:
-            raise ValueError("sessionId must be between 1 and 4096 bytes")
-        if any(ord(character) < 32 for character in normalized):
-            raise ValueError("sessionId contains control characters")
-        return normalized
-
-    @staticmethod
-    def _optional_context_label(value: Optional[str], field: str) -> Optional[str]:
-        if value is None:
-            return None
-        if not isinstance(value, str):
-            raise ValueError(f"{field} must be a string or null")
-        normalized = value.strip()
-        if not normalized:
-            return None
-        if len(normalized.encode("utf-8")) > 4096:
-            raise ValueError(f"{field} exceeds 4096 bytes")
-        return normalized
-
-    @staticmethod
-    def _session_context_payload(row: sqlite3.Row) -> dict[str, Any]:
-        return {
-            "sessionId": row["session_id"],
-            "usedTokens": int(row["context_used"]),
-            "limitTokens": (
-                None if row["context_limit"] is None else int(row["context_limit"])
-            ),
-            "percent": (
-                None
-                if row["context_percent"] is None
-                else float(row["context_percent"])
-            ),
-            "compressions": (
-                None if row["compressions"] is None else int(row["compressions"])
-            ),
-            "model": row["model"],
-            "provider": row["provider"],
-            "observedAt": float(row["observed_at"]),
-            "updatedAt": float(row["updated_at"]),
-        }
-
-    # -- queries -----------------------------------------------------------
-
-    def get_attachment(self, attachment_id: int) -> Optional[dict[str, Any]]:
-        conn = self.init()
-        row = conn.execute(
-            "SELECT * FROM attachments WHERE id=?", (attachment_id,)
-        ).fetchone()
-        return _row_to_attachment(row) if row else None
-
-    def get_object_storage_name(self, sha256: str) -> Optional[str]:
-        conn = self.init()
-        row = conn.execute(
-            "SELECT storage_name FROM objects WHERE sha256=?", (sha256,)
-        ).fetchone()
-        return row["storage_name"] if row else None
-
-    def query_attachments(
-        self,
-        *,
-        sender: Optional[str] = None,
-        kind: Optional[str] = None,
-        session_id: Optional[str] = None,
-        search: Optional[str] = None,
-        limit: int = 50,
-        cursor: Optional[int] = None,
-    ) -> tuple[list[dict[str, Any]], Optional[int], int]:
-        """Page over filtered attachments newest-first.
-
-        ``cursor`` is the last returned id. ``total`` is the full filtered
-        count and therefore does not shrink as callers move through pages.
-        """
-        conn = self.init()
-        where, params = _attachment_filter_sql(
-            sender=sender,
-            kind=kind,
-            session_id=session_id,
-            search=search,
-        )
-        where_sql = (" WHERE " + " AND ".join(where)) if where else ""
-        total = int(
-            conn.execute(
-                "SELECT COUNT(*) FROM attachments" + where_sql,
-                params,
-            ).fetchone()[0]
-        )
-
-        page_where = list(where)
-        page_params = list(params)
-        if cursor:
-            page_where.append("id < ?")
-            page_params.append(cursor)
-        page_where_sql = (
-            " WHERE " + " AND ".join(page_where) if page_where else ""
-        )
-        page_limit = max(1, int(limit))
-        page_params.append(page_limit + 1)
-        rows = conn.execute(
-            "SELECT * FROM attachments"
-            + page_where_sql
-            + " ORDER BY id DESC LIMIT ?",
-            page_params,
-        ).fetchall()
-
-        has_more = len(rows) > page_limit
-        items = [_row_to_attachment(row) for row in rows[:page_limit]]
-        next_cursor = items[-1]["id"] if has_more and items else None
-        return items, next_cursor, total
-
-    def query_message_files(self, message_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
-        """Group attachments by source_message_id."""
-        if not message_ids:
-            return {}
-        conn = self.init()
-        placeholders = ",".join("?" * len(message_ids))
-        rows = conn.execute(
-            f"SELECT * FROM attachments WHERE source_message_id IN ({placeholders}) "
-            "ORDER BY source_message_id, id",
-            message_ids,
-        ).fetchall()
-        out: dict[int, list[dict[str, Any]]] = {}
-        for r in rows:
-            out.setdefault(r["source_message_id"], []).append(_row_to_attachment(r))
-        return out
-
-    def stats(self) -> dict[str, Any]:
-        conn = self.init()
-        total_att = conn.execute("SELECT COUNT(*) FROM attachments").fetchone()[0]
-        total_obj = conn.execute("SELECT COUNT(*) FROM objects").fetchone()[0]
-        total_bytes = conn.execute("SELECT COALESCE(SUM(byte_count),0) FROM objects").fetchone()[0]
-        by_sender = {
-            r["sender"]: r["c"]
-            for r in conn.execute(
-                "SELECT sender, COUNT(*) c FROM attachments GROUP BY sender"
-            ).fetchall()
-        }
-        by_profile = {
-            r["owner_profile"]: r["c"]
-            for r in conn.execute(
-                "SELECT owner_profile, COUNT(*) c FROM attachments GROUP BY owner_profile"
-            ).fetchall()
-        }
-        return {
-            "totalAttachments": total_att,
-            "totalObjects": total_obj,
-            "totalBytes": total_bytes,
-            "bySender": by_sender,
-            "byProfile": by_profile,
-        }
-
-
-# ---------------------------------------------------------------------------
-# Module-level cache of per-data_root Store instances
-# ---------------------------------------------------------------------------
-_STORE_LOCK = threading.Lock()
-_STORES: dict[str, Store] = {}
-
-
-def get_store(data_root: Optional[Path] = None) -> Store:
-    """Return the (cached) Store for ``data_root`` (default profile if None)."""
-    root = Path(data_root) if data_root is not None else DEFAULT_DATA_ROOT
-    key = str(root.resolve())
-    with _STORE_LOCK:
-        st = _STORES.get(key)
-        if st is None:
-            st = Store(root)
-            _STORES[key] = st
-        return st
-
-
-def data_root_for_profile(profile: Optional[str]) -> Path:
-    """Resolve the plugin data dir for a profile name.
-
-    Legacy data is moved to ``<profile_home>/plugin-data/yaoyao`` before the
-    path is returned. A conflicting pair stays on the legacy tree so existing
-    data remains visible and the install coordinator can refuse replacement.
-    """
-    if not profile or profile == "default":
-        return DEFAULT_DATA_ROOT
-    try:
-        from hermes_constants import get_default_hermes_root  # type: ignore
-    except Exception:
-        get_default_hermes_root = None
-    try:
-        from hermes_cli.profiles import get_profile_dir  # type: ignore
-        home = get_profile_dir(profile)
-    except Exception:
-        # Fallback: ~/.hermes/profiles/<name> (matches get_profile_dir's logic)
-        try:
-            if get_default_hermes_root is not None:
-                base = get_default_hermes_root()
-            else:
-                env = os.environ.get("HERMES_HOME", "").strip()
-                base = Path(env) if env else Path.home() / ".hermes"
-        except Exception:
-            base = Path.home() / ".hermes"
-        home = base / "profiles" / profile
-    return ensure_durable_data_root(home).data_root
-
-
-# ---------------------------------------------------------------------------
-# Back-compat module-level functions (default profile).
-#
-# Keep the old call surface working for the duplex-voice section below and any
-# stragglers. New code should use get_store(data_root).ingest(...).
-# ---------------------------------------------------------------------------
-
-def _default_store() -> Store:
-    return get_store(DEFAULT_DATA_ROOT)
-
-
-def init() -> sqlite3.Connection:
-    """Back-compat: init the DEFAULT profile's store. Returns its connection."""
-    return _default_store().init()
-
-
-def ingest(
-    src_path: str,
-    *,
-    sender: str,
-    source_kind: str,
-    source_message_id: Optional[int],
-    session_id: Optional[str],
-    tool_name: Optional[str] = None,
-    display_name: Optional[str] = None,
-    owner_profile: str = "default",
-    discovered_at: Optional[int] = None,
-) -> Optional[int]:
-    """Back-compat: ingest into the DEFAULT profile's store."""
-    return _default_store().ingest(
-        src_path,
-        sender=sender,
-        source_kind=source_kind,
-        source_message_id=source_message_id,
-        session_id=session_id,
-        tool_name=tool_name,
-        display_name=display_name,
-        owner_profile=owner_profile,
-        discovered_at=discovered_at,
-    )
-
-
-def get_attachment(attachment_id: int) -> Optional[dict[str, Any]]:
-    return _default_store().get_attachment(attachment_id)
-
-
-def get_object_storage_name(sha256: str) -> Optional[str]:
-    return _default_store().get_object_storage_name(sha256)
-
-
-def query_attachments(
-    *,
-    sender: Optional[str] = None,
-    kind: Optional[str] = None,
-    session_id: Optional[str] = None,
-    search: Optional[str] = None,
-    limit: int = 50,
-    cursor: Optional[int] = None,
-) -> tuple[list[dict[str, Any]], Optional[int], int]:
-    return _default_store().query_attachments(
-        sender=sender, kind=kind, session_id=session_id,
-        search=search, limit=limit, cursor=cursor,
-    )
-
-
-def query_message_files(message_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
-    return _default_store().query_message_files(message_ids)
-
-
-def stats() -> dict[str, Any]:
-    return _default_store().stats()
-
-
-# ---------------------------------------------------------------------------
-# Content-type + kind inference (module-level, data_root-independent)
-# ---------------------------------------------------------------------------
-
-_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".tiff", ".tif"}
-_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".m4v", ".wmv", ".flv"}
-_TEXT_EXTS = {".txt", ".md", ".json", ".yaml", ".yml", ".csv", ".log", ".py", ".js", ".ts", ".html", ".xml", ".rst"}
-
-
-def _attachment_kind_sql() -> str:
-    def suffixes(values: set[str]) -> str:
-        return " OR ".join(
-            f"lower(display_name) LIKE '%{extension}'"
-            for extension in sorted(values)
-        )
-
-    image = (
-        "lower(COALESCE(content_type, '')) LIKE 'image/%' OR "
-        f"({suffixes(_IMAGE_EXTS)})"
-    )
-    video = (
-        "lower(COALESCE(content_type, '')) LIKE 'video/%' OR "
-        f"({suffixes(_VIDEO_EXTS)})"
-    )
-    text = (
-        "lower(COALESCE(content_type, '')) LIKE 'text/%' OR "
-        f"({suffixes(_TEXT_EXTS)})"
-    )
-    return (
-        "CASE "
-        f"WHEN ({image}) THEN 'image' "
-        f"WHEN ({video}) THEN 'video' "
-        f"WHEN ({text}) THEN 'text' "
-        "ELSE 'file' END"
-    )
-
-
-def _attachment_filter_sql(
-    *,
-    sender: Optional[str],
-    kind: Optional[str],
-    session_id: Optional[str],
-    search: Optional[str],
-) -> tuple[list[str], list[Any]]:
-    where: list[str] = []
-    params: list[Any] = []
-    if sender:
-        where.append("sender = ?")
-        params.append(sender)
-    if session_id:
-        where.append("session_id = ?")
-        params.append(session_id)
-    if search:
-        where.append("instr(lower(display_name), lower(?)) > 0")
-        params.append(search)
-    if kind:
-        where.append(f"({_attachment_kind_sql()}) = ?")
-        params.append(kind)
-    return where, params
-
-
-def guess_content_type(path: str, display_name: str = "") -> str:
-    name = display_name or os.path.basename(path)
-    ct, _ = mimetypes.guess_type(name)
-    if ct:
-        return ct
-    ext = Path(name).suffix.lower()
-    if ext in _IMAGE_EXTS:
-        return "image/png" if ext == ".png" else "application/octet-stream"
-    return "application/octet-stream"
-
-
-def infer_kind(display_name: str, content_type: str) -> str:
-    """Return one of: image / video / text / file."""
-    ext = Path(display_name).suffix.lower()
-    if content_type.startswith("image/") or ext in _IMAGE_EXTS:
-        return "image"
-    if content_type.startswith("video/") or ext in _VIDEO_EXTS:
-        return "video"
-    if content_type.startswith("text/") or ext in _TEXT_EXTS:
-        return "text"
-    return "file"
-
-
-# ---------------------------------------------------------------------------
-# Content-addressed helpers (module-level, take objects_dir)
-# ---------------------------------------------------------------------------
-
-def _sha256_of_file(path: Path) -> tuple[str, int]:
-    h = hashlib.sha256()
-    size = 0
-    with path.open("rb") as f:
-        for chunk in iter(lambda: f.read(1 << 20), b""):
-            h.update(chunk)
-            size += len(chunk)
-    return h.hexdigest(), size
-
-
-def _storage_name(sha256: str, ext: str) -> str:
-    return f"{sha256}{ext}"
-
-
-def _copy_to_objects(src: Path, sha256: str, display_name: str, objects_dir: Path) -> str:
-    """Copy ``src`` into objects/ as <sha256><ext>. Returns storage_name."""
-    ext = Path(display_name).suffix.lower() or Path(src).suffix.lower()
-    storage_name = _storage_name(sha256, ext)
-    dest = objects_dir / storage_name
-    if not dest.exists():
-        tmp = dest.with_suffix(dest.suffix + ".tmp")
-        with src.open("rb") as r, tmp.open("wb") as w:
-            while True:
-                chunk = r.read(1 << 20)
-                if not chunk:
-                    break
-                w.write(chunk)
-        os.replace(tmp, dest)
-    return storage_name
-
-
-def _row_to_attachment(row: sqlite3.Row) -> dict[str, Any]:
-    return {
-        "id": row["id"],
-        "objectSha256": row["object_sha256"],
-        "displayName": row["display_name"],
-        "contentType": row["content_type"] or "application/octet-stream",
-        "byteCount": row["byte_count"],
-        "sender": row["sender"],
-        "sourceKind": row["source_kind"],
-        "sourceMessageId": row["source_message_id"],
-        "sessionId": row["session_id"],
-        "toolName": row["tool_name"],
-        "ownerProfile": row["owner_profile"] if "owner_profile" in row.keys() else "default",
-        "discoveredAt": row["discovered_at"],
-    }
-
-
-# ---------------------------------------------------------------------------
-# Agent display-name settings
-# ---------------------------------------------------------------------------
-# Names are isolated by Hermes profile and kept next to that profile's Yaoyao
-# data.  The value is presentation-only: profile ids remain the stable routing
-# identity everywhere else.
-
-_AGENT_SETTINGS_FILE = "agent_settings.json"
-_AGENT_SETTINGS_LOCK = threading.Lock()
-MAX_AGENT_NAME_LENGTH = 100
-
-
-def _agent_settings_path(profile: Optional[str]) -> Path:
-    return data_root_for_profile(profile) / _AGENT_SETTINGS_FILE
-
-
-def load_agent_settings(profile: Optional[str] = None) -> dict[str, Any]:
-    """Read the configured display name for one Hermes profile."""
-    profile_name = str(profile or "default").strip() or "default"
-    result = {
-        "profile": profile_name,
-        "agentName": "",
-        "updatedAt": 0,
-    }
-    path = _agent_settings_path(profile_name)
-    try:
-        if path.is_file():
-            saved = json.loads(path.read_text(encoding="utf-8"))
-            if isinstance(saved, dict):
-                name = str(saved.get("agentName") or "").strip()
-                if len(name) <= MAX_AGENT_NAME_LENGTH and not any(
-                    ord(character) < 32 or ord(character) == 127
-                    for character in name
-                ) and not is_reserved_mention_alias(name):
-                    result["agentName"] = name
-                result["updatedAt"] = int(saved.get("updatedAt") or 0)
-    except (OSError, TypeError, ValueError, json.JSONDecodeError) as error:
-        log.warning("agent settings load failed for %s: %s", profile_name, error)
-    return result
-
-
-def save_agent_settings(
-    profile: Optional[str],
-    input_data: dict[str, Any],
-) -> dict[str, Any]:
-    """Set or clear one profile's display name and return the saved value."""
-    if not isinstance(input_data, dict) or "agentName" not in input_data:
-        raise ValueError("agentName is required")
-    candidate = input_data["agentName"]
-    if not isinstance(candidate, str):
-        raise ValueError("agentName must be a string")
-    agent_name = candidate.strip()
-    if len(agent_name) > MAX_AGENT_NAME_LENGTH:
-        raise ValueError("agentName is too long")
-    if any(ord(character) < 32 or ord(character) == 127 for character in agent_name):
-        raise ValueError("agentName contains control characters")
-    if is_reserved_mention_alias(agent_name):
-        raise ValueError("agentName is reserved for group mentions")
-
-    profile_name = str(profile or "default").strip() or "default"
-    now = int(time.time() * 1000)
-    saved = {
-        "profile": profile_name,
-        "agentName": agent_name,
-        "updatedAt": now,
-    }
-    path = _agent_settings_path(profile_name)
-    _ensure_dirs(path.parent)
-    temporary = path.with_name(
-        f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp"
-    )
-    with _AGENT_SETTINGS_LOCK:
-        try:
-            temporary.write_text(
-                json.dumps(saved, indent=2, ensure_ascii=False) + "\n",
-                encoding="utf-8",
-            )
-            os.replace(temporary, path)
-        finally:
-            temporary.unlink(missing_ok=True)
-    return saved
-
-
-# ---------------------------------------------------------------------------
-# iOS duplex voice settings (mirrors yaoyao-webui's ios-duplex-voice contract)
-# ---------------------------------------------------------------------------
-# The iOS app connects directly to the TTS provider (e.g. Volcano/doubao) for
-# low-latency duplex voice. This plugin stores the single shared API key +
-# the voice list + the currently selected voice, exactly matching the
-# IosDuplexVoiceSettings schema from yaoyao-webui so the iOS client can talk
-# to either backend interchangeably.
-#
-# These settings are GLOBAL (not per-profile): one shared duplex-voice config
-# for the whole installation. Kept in the default profile's data dir.
-
-_DEFAULT_DUPLEX_VOICES: list[dict[str, str]] = [
-    {"id": "zh_female_xiaohe_uranus_bigtts", "name": "小何 2.0"},
-    {"id": "zh_female_vv_uranus_bigtts", "name": "Vivi 2.0"},
-    {"id": "zh_male_m191_uranus_bigtts", "name": "云舟 2.0"},
-    {"id": "zh_male_taocheng_uranus_bigtts", "name": "小天 2.0"},
-    {"id": "zh_female_qingxinnvsheng_uranus_bigtts", "name": "清新女声 2.0"},
-    {"id": "zh_female_cancan_uranus_bigtts", "name": "知性灿灿 2.0"},
-    {"id": "zh_male_ruyayichen_uranus_bigtts", "name": "儒雅逸辰 2.0"},
-    {"id": "en_female_dacey_uranus_bigtts", "name": "Dacey 2.0"},
-]
-
-_DUPLEX_VOICE_FILE = DEFAULT_DATA_ROOT / "duplex_voice.json"
-
-_DUPLEX_LOCK = threading.Lock()
-
-MAX_DUPLEX_VOICES = 100
-MAX_DUPLEX_VOICE_TEXT = 200
-MAX_DUPLEX_API_KEY = 4000
-
-
-def _duplex_default() -> dict[str, Any]:
-    return {
-        "apiKey": "",
-        "voices": [dict(v) for v in _DEFAULT_DUPLEX_VOICES],
-        "currentVoiceId": _DEFAULT_DUPLEX_VOICES[0]["id"],
-        "updatedAt": 0,
-    }
-
-
-def _normalize_duplex_voices(raw: Any) -> list[dict[str, str]]:
-    """Validate + normalize a voice list (raises ValueError on bad input)."""
-    if not isinstance(raw, list) or len(raw) == 0 or len(raw) > MAX_DUPLEX_VOICES:
-        raise ValueError("voices must contain between 1 and 100 items")
-    seen: set[str] = set()
-    out: list[dict[str, str]] = []
-    for item in raw:
-        if not isinstance(item, dict):
-            raise ValueError("invalid voice")
-        vid = str(item.get("id", "")).strip()
-        name = str(item.get("name", "")).strip()
-        if not vid or len(vid) > MAX_DUPLEX_VOICE_TEXT:
-            raise ValueError("invalid voice id")
-        if not name or len(name) > MAX_DUPLEX_VOICE_TEXT:
-            raise ValueError("invalid voice name")
-        if vid in seen:
-            raise ValueError(f"duplicate voice id: {vid}")
-        seen.add(vid)
-        out.append({"id": vid, "name": name})
-    return out
-
-
-def load_duplex_voice() -> dict[str, Any]:
-    """Read duplex voice settings, deep-merged over defaults."""
-    cfg = _duplex_default()
-    try:
-        if _DUPLEX_VOICE_FILE.is_file():
-            saved = json.loads(_DUPLEX_VOICE_FILE.read_text(encoding="utf-8"))
-            if isinstance(saved, dict):
-                if "apiKey" in saved:
-                    cfg["apiKey"] = str(saved["apiKey"])
-                if "voices" in saved:
-                    cfg["voices"] = _normalize_duplex_voices(saved["voices"])
-                if "currentVoiceId" in saved:
-                    cfg["currentVoiceId"] = str(saved["currentVoiceId"])
-                if "updatedAt" in saved:
-                    cfg["updatedAt"] = int(saved["updatedAt"])
-    except Exception as e:
-        log.warning("duplex voice load failed: %s", e)
-    # Ensure currentVoiceId is valid
-    if not any(v["id"] == cfg["currentVoiceId"] for v in cfg["voices"]):
-        cfg["currentVoiceId"] = cfg["voices"][0]["id"] if cfg["voices"] else ""
-    return cfg
-
-
-def save_duplex_voice(input_data: dict[str, Any]) -> dict[str, Any]:
-    """Partial update of duplex voice settings. Returns the full settings."""
-    current = load_duplex_voice()
-
-    voices = current["voices"]
-    if "voices" in input_data:
-        voices = _normalize_duplex_voices(input_data["voices"])
-
-    current_voice_id = current["currentVoiceId"]
-    if "currentVoiceId" in input_data:
-        current_voice_id = str(input_data["currentVoiceId"]).strip()
-        if not current_voice_id or len(current_voice_id) > MAX_DUPLEX_VOICE_TEXT:
-            raise ValueError("invalid current voice id")
-    # If current voice was removed, fall back to first
-    if not any(v["id"] == current_voice_id for v in voices):
-        current_voice_id = voices[0]["id"] if voices else ""
-
-    api_key = current["apiKey"]
-    if "apiKey" in input_data:
-        candidate = input_data["apiKey"]
-        if not isinstance(candidate, str):
-            raise ValueError("apiKey must be a string")
-        candidate = candidate.strip()
-        if candidate and candidate != "[stored]":
-            if len(candidate) > MAX_DUPLEX_API_KEY:
-                raise ValueError("apiKey is too long")
-            api_key = candidate
-
-    import time as _time
-    now = int(_time.time() * 1000)
-    merged = {
-        "apiKey": api_key,
-        "voices": voices,
-        "currentVoiceId": current_voice_id,
-        "updatedAt": now,
-    }
-    _ensure_dirs(DEFAULT_DATA_ROOT)
-    with _DUPLEX_LOCK:
-        _DUPLEX_VOICE_FILE.write_text(
-            json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8"
-        )
-    return merged
-
-
-def public_duplex_voice() -> dict[str, Any]:
-    """Settings for the dashboard UI (apiKey masked as hasApiKey boolean)."""
-    s = load_duplex_voice()
-    return {
-        "hasApiKey": bool(s["apiKey"]),
-        "voices": s["voices"],
-        "currentVoiceId": s["currentVoiceId"],
-        "updatedAt": s["updatedAt"],
-    }
-
-
-def runtime_duplex_voice() -> dict[str, Any]:
-    """Settings for the iOS app runtime (includes the real apiKey)."""
-    s = load_duplex_voice()
-    return {
-        "apiKey": s["apiKey"],
-        "voices": s["voices"],
-        "currentVoiceId": s["currentVoiceId"],
-        "updatedAt": s["updatedAt"],
-    }

+ 0 - 84
hermes-plugins/yaoyao/dashboard/tests/test_data_paths.py

@@ -1,84 +0,0 @@
-import os
-from pathlib import Path
-import tempfile
-import unittest
-from unittest.mock import patch
-
-from data_paths import ensure_durable_data_root
-from group_node_registry import PairedNodeRegistry
-
-
-class DataPathTests(unittest.TestCase):
-    def setUp(self) -> None:
-        self.temporary = tempfile.TemporaryDirectory()
-        self.root = Path(self.temporary.name).resolve()
-
-    def tearDown(self) -> None:
-        self.temporary.cleanup()
-
-    def test_moves_legacy_tree_to_durable_plugin_data(self) -> None:
-        legacy = self.root / "plugins" / "yaoyao" / "data"
-        legacy.mkdir(parents=True)
-        (legacy / "index.sqlite3").write_bytes(b"database")
-
-        status = ensure_durable_data_root(self.root)
-
-        self.assertTrue(status.ready)
-        self.assertTrue(status.migrated)
-        self.assertEqual(status.data_root, self.root / "plugin-data" / "yaoyao")
-        self.assertEqual(
-            (status.data_root / "index.sqlite3").read_bytes(), b"database"
-        )
-        self.assertFalse(legacy.exists())
-
-    def test_refuses_to_merge_without_falling_back(self) -> None:
-        legacy = self.root / "plugins" / "yaoyao" / "data"
-        durable = self.root / "plugin-data" / "yaoyao"
-        legacy.mkdir(parents=True)
-        durable.mkdir(parents=True)
-        (legacy / "legacy.db").write_bytes(b"legacy")
-        (durable / "current.db").write_bytes(b"current")
-
-        status = ensure_durable_data_root(self.root)
-
-        self.assertFalse(status.ready)
-        self.assertTrue(status.conflict)
-        self.assertEqual(status.data_root, durable)
-        self.assertTrue((legacy / "legacy.db").exists())
-        self.assertTrue((durable / "current.db").exists())
-
-    def test_fresh_profile_uses_durable_location_without_creating_it(self) -> None:
-        status = ensure_durable_data_root(self.root)
-
-        self.assertTrue(status.ready)
-        self.assertFalse(status.migrated)
-        self.assertEqual(status.data_root, self.root / "plugin-data" / "yaoyao")
-        self.assertFalse(status.data_root.exists())
-
-    def test_node_registry_uses_durable_data_root(self) -> None:
-        with patch.dict(os.environ, {"HERMES_HOME": str(self.root)}):
-            registry = PairedNodeRegistry.from_environment()
-
-        self.assertEqual(registry.root, self.root / "plugin-data" / "yaoyao")
-        self.assertTrue(registry.key_path.exists())
-        self.assertFalse((self.root / "plugins" / "yaoyao" / "data").exists())
-
-    def test_node_registry_keeps_durable_authority_during_legacy_conflict(
-        self,
-    ) -> None:
-        durable = self.root / "plugin-data" / "yaoyao"
-        legacy = self.root / "plugins" / "yaoyao" / "data"
-        durable.mkdir(parents=True)
-        legacy.mkdir(parents=True)
-        (legacy / "stale.db").write_bytes(b"stale")
-
-        with patch.dict(os.environ, {"HERMES_HOME": str(self.root)}):
-            registry = PairedNodeRegistry.from_environment()
-
-        self.assertEqual(registry.root, durable)
-        self.assertTrue(registry.key_path.exists())
-        self.assertFalse((legacy / "paired-group-nodes.key").exists())
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 229
hermes-plugins/yaoyao/dashboard/tests/test_file_library_contract.py

@@ -1,229 +0,0 @@
-from __future__ import annotations
-
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-from unittest import mock
-
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-if str(DASHBOARD_DIR) not in sys.path:
-    sys.path.insert(0, str(DASHBOARD_DIR))
-
-import poller  # noqa: E402
-import store  # noqa: E402
-
-with mock.patch.object(poller, "start", return_value=None):
-    import plugin_api  # noqa: E402
-
-
-class FileLibraryContractTests(unittest.TestCase):
-    def test_session_context_snapshot_is_profile_scoped_and_monotonic(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            first = store.Store(Path(directory) / "first")
-            second = store.Store(Path(directory) / "second")
-
-            saved = first.upsert_session_context(
-                "session-history-1",
-                context_used=41_920,
-                context_limit=256_000,
-                context_percent=None,
-                compressions=2,
-                model="gpt-5.6",
-                provider="openai-codex",
-                observed_at=200,
-            )
-            stale = first.upsert_session_context(
-                "session-history-1",
-                context_used=12_000,
-                context_limit=128_000,
-                context_percent=9,
-                compressions=0,
-                model="old-model",
-                provider="old-provider",
-                observed_at=100,
-            )
-
-            self.assertEqual(saved["usedTokens"], 41_920)
-            self.assertAlmostEqual(saved["percent"], 16.375)
-            self.assertEqual(stale["usedTokens"], 41_920)
-            self.assertEqual(stale["model"], "gpt-5.6")
-            self.assertEqual(
-                first.get_session_context("session-history-1"), stale
-            )
-            self.assertIsNone(second.get_session_context("session-history-1"))
-
-    def test_session_context_routes_use_selected_profile_store(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            archive = store.Store(Path(directory) / "profile")
-            requested_profiles: list[str | None] = []
-
-            def resolve(profile: str | None):
-                requested_profiles.append(profile)
-                return archive
-
-            body = plugin_api.SessionContextSnapshotBody.model_validate(
-                {
-                    "usedTokens": 33_600,
-                    "limitTokens": 256_000,
-                    "percent": 13.125,
-                    "compressions": 1,
-                    "model": "claude-sonnet-4-6",
-                    "provider": "anthropic",
-                    "observedAt": 300,
-                }
-            )
-            with mock.patch.object(plugin_api, "_store_for", side_effect=resolve):
-                written = plugin_api.put_session_context(
-                    "session-2", body, profile="planner"
-                )
-                loaded = plugin_api.get_session_context(
-                    "session-2", profile="planner"
-                )
-
-            self.assertEqual(requested_profiles, ["planner", "planner"])
-            self.assertEqual(
-                written["snapshot"]["model"], "claude-sonnet-4-6"
-            )
-            self.assertEqual(loaded, written)
-            paths = {getattr(route, "path", "") for route in plugin_api.router.routes}
-            self.assertIn("/session-context/{session_id}", paths)
-
-    def test_search_and_kind_filter_before_cursor_pagination(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            root = Path(directory)
-            archive = store.Store(root / "library")
-            old_cover = self._ingest(
-                archive,
-                root,
-                display_name="cover-old.png",
-                body=b"old-cover",
-                message_id=1,
-            )
-            new_cover = self._ingest(
-                archive,
-                root,
-                display_name="cover-new.png",
-                body=b"new-cover",
-                message_id=2,
-            )
-            self._ingest(
-                archive,
-                root,
-                display_name="newest-notes.md",
-                body=b"newest-notes",
-                message_id=3,
-            )
-
-            first, next_cursor, total = archive.query_attachments(
-                search="COVER",
-                limit=1,
-            )
-            self.assertEqual([item["id"] for item in first], [new_cover])
-            self.assertEqual(next_cursor, new_cover)
-            self.assertEqual(total, 2)
-
-            second, final_cursor, second_total = archive.query_attachments(
-                search="cover",
-                limit=1,
-                cursor=next_cursor,
-            )
-            self.assertEqual([item["id"] for item in second], [old_cover])
-            self.assertIsNone(final_cursor)
-            self.assertEqual(second_total, 2)
-
-            images, image_cursor, image_total = archive.query_attachments(
-                kind="image",
-                limit=10,
-            )
-            self.assertEqual(
-                [item["displayName"] for item in images],
-                ["cover-new.png", "cover-old.png"],
-            )
-            self.assertIsNone(image_cursor)
-            self.assertEqual(image_total, 2)
-
-    def test_profile_list_payload_and_download_route_contract(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            root = Path(directory)
-            archive = store.Store(root / "yaoer-library")
-            item_id = self._ingest(
-                archive,
-                root,
-                display_name="cover.png",
-                body=b"profile-cover",
-                message_id=41,
-            )
-            other = store.Store(root / "other-library")
-            self._ingest(
-                other,
-                root,
-                display_name="other.txt",
-                body=b"other-profile",
-                message_id=42,
-            )
-            requested_profiles: list[str | None] = []
-
-            def resolve(profile: str | None):
-                requested_profiles.append(profile)
-                return archive if profile == "yaoer" else other
-
-            with mock.patch.object(plugin_api, "_store_for", side_effect=resolve):
-                payload = plugin_api.list_files(
-                    sender=None,
-                    kind=None,
-                    session_id=None,
-                    search=None,
-                    profile="yaoer",
-                    limit=50,
-                    cursor=None,
-                )
-                response = plugin_api.download_item(item_id, profile="yaoer")
-
-            self.assertEqual(requested_profiles, ["yaoer", "yaoer"])
-            self.assertEqual(payload["profile"], "yaoer")
-            self.assertEqual(payload["total"], 1)
-            self.assertIsNone(payload["nextCursor"])
-            self.assertEqual([item["name"] for item in payload["items"]], ["cover.png"])
-            self.assertEqual(
-                payload["items"][0]["path"],
-                f"yaoyao-file-library://archive/{item_id}?name=cover.png",
-            )
-            self.assertEqual(Path(response.path).read_bytes(), b"profile-cover")
-            self.assertIn(
-                "cover.png",
-                response.headers.get("content-disposition", ""),
-            )
-            paths = {getattr(route, "path", "") for route in plugin_api.router.routes}
-            self.assertIn("/files", paths)
-            self.assertIn("/{item_id}/download", paths)
-
-    @staticmethod
-    def _ingest(
-        archive: store.Store,
-        root: Path,
-        *,
-        display_name: str,
-        body: bytes,
-        message_id: int,
-    ) -> int:
-        source = root / f"source-{message_id}"
-        source.write_bytes(body)
-        item_id = archive.ingest(
-            str(source),
-            sender="agent",
-            source_kind="message",
-            source_message_id=message_id,
-            session_id="session-a",
-            display_name=display_name,
-            owner_profile="yaoer",
-            discovered_at=message_id,
-        )
-        if item_id is None:
-            raise AssertionError("fixture was not archived")
-        return item_id
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 27
hermes-plugins/yaoyao/dashboard/tests/test_frontend_contract.py

@@ -1,27 +0,0 @@
-from __future__ import annotations
-
-import re
-import unittest
-from pathlib import Path
-
-
-class DashboardFrontendContractTests(unittest.TestCase):
-    def test_sdk_selects_use_value_callback(self) -> None:
-        source = (
-            Path(__file__).resolve().parents[1] / "dist" / "index.js"
-        ).read_text(encoding="utf-8")
-        select_blocks = re.findall(r"h\(Select, \{(.*?)\},", source, flags=re.S)
-
-        self.assertGreater(len(select_blocks), 0)
-        self.assertFalse(
-            [block for block in select_blocks if "onChange:" in block],
-            "Hermes SDK Select requires onValueChange(value), not onChange(event)",
-        )
-        self.assertTrue(
-            all("onValueChange:" in block for block in select_blocks),
-            "Every Hermes SDK Select must expose its value callback",
-        )
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 1014
hermes-plugins/yaoyao/dashboard/tests/test_group_host_contract.py

@@ -1,1014 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-from concurrent.futures import ThreadPoolExecutor
-import importlib
-import json
-from pathlib import Path
-import sqlite3
-import sys
-import tempfile
-import threading
-import unittest
-import uuid
-
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-if str(DASHBOARD_DIR) not in sys.path:
-    sys.path.insert(0, str(DASHBOARD_DIR))
-
-import group_plugin_api  # noqa: E402
-
-
-PROTOCOL = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_protocol")
-STORE_MODULE = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_store")
-ORCHESTRATOR = importlib.import_module(
-    f"{group_plugin_api._LOCAL_PACKAGE}.group_orchestrator"
-)
-GroupStore = STORE_MODULE.GroupStore
-
-
-def new_id() -> str:
-    return str(uuid.uuid4())
-
-
-class GroupHostContractTests(unittest.TestCase):
-    def test_protocol_v5_host_fields_are_independent_and_compatible(self) -> None:
-        self.assertEqual(PROTOCOL.PROTOCOL_VERSION, 12)
-        legacy = PROTOCOL.CreateRoomRequest.model_validate({
-            "requestId": new_id(),
-            "name": "兼容群",
-            "agents": [{"profile": "legacy", "replyWithoutMention": True}],
-        })
-        self.assertFalse(legacy.agents[0].is_host)
-        self.assertTrue(legacy.agents[0].reply_without_mention)
-        legacy_command = group_plugin_api._create_room_command(legacy)
-        self.assertNotIn("isHost", legacy_command["agents"][0])
-
-        explicit = PROTOCOL.CreateRoomRequest.model_validate({
-            "requestId": new_id(),
-            "name": "v5 群",
-            "agents": [
-                {"profile": "host", "isHost": True},
-                {"profile": "observer", "replyWithoutMention": True},
-            ],
-        })
-        explicit_command = group_plugin_api._create_room_command(explicit)
-        self.assertIs(explicit_command["agents"][0]["isHost"], True)
-        self.assertNotIn("isHost", explicit_command["agents"][1])
-        update = PROTOCOL.UpdateAgentRequest.model_validate({
-            "requestId": new_id(),
-            "isHost": True,
-        })
-        self.assertIs(update.is_host, True)
-        flow = PROTOCOL.UpdateRoomRequest.model_validate({
-            "requestId": new_id(),
-            "orchestrationMode": "host",
-        })
-        self.assertEqual(flow.orchestration_mode, "host")
-
-        with self.assertRaisesRegex(ValueError, "only one administrator"):
-            PROTOCOL.CreateRoomRequest.model_validate({
-                "requestId": new_id(),
-                "name": "非法群",
-                "agents": [
-                    {"profile": "one", "isHost": True},
-                    {"profile": "two", "isHost": True},
-                ],
-            })
-
-    def test_human_routing_uses_host_only_when_no_valid_mention(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "路由群",
-                "cwd": "",
-                "agents": [
-                    {
-                        "profile": "host",
-                        "isHost": True,
-                        "replyWithoutMention": True,
-                    },
-                    {"profile": "automatic", "replyWithoutMention": True},
-                    {"profile": "explicit"},
-                    {"profile": "disabled", "replyWithoutMention": True},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            store.update_agent(
-                room["id"],
-                agents["disabled"]["id"],
-                {"requestId": new_id(), "enabled": False},
-            )
-
-            no_mention = self._send(store, room["id"], "普通消息", [])
-            self.assertEqual(
-                self._run_modes(no_mention),
-                {
-                    agents["host"]["id"]: "automatic",
-                    agents["automatic"]["id"]: "automatic",
-                },
-            )
-            with store.connection() as connection:
-                flags = {
-                    row["agent_id"]: row["required_reply"]
-                    for row in connection.execute(
-                        """SELECT agent_id, required_reply FROM group_agent_runs
-                        WHERE id IN (?, ?)""",
-                        tuple(run["id"] for run in no_mention["runs"]),
-                    )
-                }
-                visibility = {
-                    row["sender_id"]: row["visible"]
-                    for row in connection.execute(
-                        """SELECT sender_id, visible FROM group_messages
-                        WHERE id IN (?, ?)""",
-                        tuple(run["responseMessageId"] for run in no_mention["runs"]),
-                    )
-                }
-            self.assertEqual(
-                flags,
-                {agents["host"]["id"]: 1, agents["automatic"]["id"]: 0},
-            )
-            self.assertEqual(
-                visibility,
-                {agents["host"]["id"]: 1, agents["automatic"]["id"]: 0},
-            )
-
-            explicit = self._send(
-                store, room["id"], "请处理", [agents["explicit"]["id"]]
-            )
-            self.assertEqual(
-                self._run_modes(explicit),
-                {agents["explicit"]["id"]: "mentioned"},
-            )
-            merged = self._send(
-                store,
-                room["id"],
-                "@automatic 一起处理",
-                [agents["explicit"]["id"]],
-            )
-            self.assertEqual(
-                self._run_modes(merged),
-                {
-                    agents["explicit"]["id"]: "mentioned",
-                    agents["automatic"]["id"]: "mentioned",
-                },
-            )
-
-            for content, ids in (
-                ("@不存在 请处理", []),
-                ("失效请求目标", [new_id()]),
-                ("@disabled 请处理", []),
-            ):
-                with self.subTest(content=content):
-                    fallback = self._send(store, room["id"], content, ids)
-                    self.assertEqual(
-                        self._run_modes(fallback),
-                        {
-                            agents["host"]["id"]: "automatic",
-                            agents["automatic"]["id"]: "automatic",
-                        },
-                    )
-
-            everyone = self._send(store, room["id"], "@all 请处理", [])
-            self.assertEqual(
-                set(self._run_modes(everyone)),
-                {
-                    agents["host"]["id"],
-                    agents["automatic"]["id"],
-                    agents["explicit"]["id"],
-                },
-            )
-            self.assertTrue(
-                all(mode == "mentioned" for mode in self._run_modes(everyone).values())
-            )
-
-    def test_agent_cascade_explicit_mentions_exclude_automatic_members(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "级联群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "source", "isHost": True},
-                    {"profile": "automatic", "replyWithoutMention": True},
-                    {"profile": "target"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            explicit_source = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["source"]["id"],
-                content="@target 继续",
-            )
-            explicit = store.complete_cascade(explicit_source)
-            self.assertEqual(
-                {store.get_run(run_id)["agentId"] for run_id in explicit["runIds"]},
-                {agents["target"]["id"]},
-            )
-
-            automatic_source = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["source"]["id"],
-                content="没有明确目标",
-            )
-            automatic = store.complete_cascade(automatic_source)
-            self.assertEqual(
-                {store.get_run(run_id)["agentId"] for run_id in automatic["runIds"]},
-                {agents["automatic"]["id"]},
-            )
-
-    def test_eight_member_no_mention_routing_deduplicates_the_host(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "八成员群",
-                "cwd": "",
-                "agents": [
-                    {
-                        "profile": "host",
-                        "isHost": True,
-                        "replyWithoutMention": True,
-                    },
-                    *[
-                        {
-                            "profile": f"automatic-{index}",
-                            "replyWithoutMention": True,
-                        }
-                        for index in range(1, 8)
-                    ],
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-
-            response = self._send(store, room["id"], "普通消息", [])
-
-            self.assertEqual(len(response["runs"]), 8)
-            self.assertEqual(
-                {run["agentId"] for run in response["runs"]},
-                {agent["id"] for agent in agents.values()},
-            )
-            with store.connection() as connection:
-                flags = connection.execute(
-                    """SELECT agent_id, required_reply FROM group_agent_runs
-                    WHERE root_message_id = ? ORDER BY agent_id""",
-                    (response["message"]["id"],),
-                ).fetchall()
-            self.assertEqual(sum(row["required_reply"] for row in flags), 1)
-            self.assertEqual(
-                next(row["agent_id"] for row in flags if row["required_reply"]),
-                agents["host"]["id"],
-            )
-
-    def test_host_switch_is_atomic_and_idempotent_replay_is_frozen(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "切换群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "one", "isHost": True},
-                    {"profile": "two"},
-                    {"profile": "three"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            with self.assertRaisesRegex(
-                STORE_MODULE.GroupConflictError, "cannot be cleared"
-            ):
-                store.update_agent(
-                    room["id"],
-                    agents["one"]["id"],
-                    {"requestId": new_id(), "isHost": False},
-                )
-
-            before = store.latest_cursor()
-            switch_request = new_id()
-            first = store.update_agent(
-                room["id"],
-                agents["two"]["id"],
-                {"requestId": switch_request, "isHost": True},
-            )
-            self.assertIs(first["isHost"], True)
-            events = store.events_after(before, 10)
-            agent_events = [
-                event for event in events if event["eventType"] == "agent.updated"
-            ]
-            self.assertEqual(
-                [(event["payload"]["id"], event["payload"]["isHost"]) for event in agent_events],
-                [(agents["one"]["id"], False), (agents["two"]["id"], True)],
-            )
-
-            store.update_agent(
-                room["id"],
-                agents["three"]["id"],
-                {"requestId": new_id(), "isHost": True},
-            )
-            replay = store.update_agent(
-                room["id"],
-                agents["two"]["id"],
-                {"requestId": switch_request, "isHost": True},
-            )
-            self.assertEqual(replay, first)
-            self.assertIs(replay["isHost"], True)
-            current = store.get_room(room["id"])["agents"]
-            self.assertEqual(
-                [agent["id"] for agent in current if agent["isHost"]],
-                [agents["three"]["id"]],
-            )
-
-    def test_host_disable_delete_promotion_and_no_replacement_rejection(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "顺延群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "host", "isHost": True},
-                    {"profile": "second"},
-                    {"profile": "third"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            expected_after_disable = min(
-                (agents["second"], agents["third"]),
-                key=lambda agent: (agent["createdAt"], agent["id"]),
-            )
-            store.update_agent(
-                room["id"],
-                agents["host"]["id"],
-                {"requestId": new_id(), "enabled": False},
-            )
-            current = store.get_room(room["id"])["agents"]
-            self.assertEqual(
-                [agent["id"] for agent in current if agent["isHost"]],
-                [expected_after_disable["id"]],
-            )
-
-            store.delete_agent(
-                room["id"], expected_after_disable["id"], {"requestId": new_id()}
-            )
-            current = store.get_room(room["id"])["agents"]
-            self.assertEqual(sum(agent["isHost"] for agent in current), 1)
-            self.assertTrue(next(agent for agent in current if agent["isHost"])["enabled"])
-
-            sole = store.create_room({
-                "requestId": new_id(),
-                "name": "无替代群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "host", "isHost": True},
-                    {"profile": "disabled"},
-                ],
-            })
-            sole_agents = {agent["profile"]: agent for agent in sole["agents"]}
-            store.update_agent(
-                sole["id"],
-                sole_agents["disabled"]["id"],
-                {"requestId": new_id(), "enabled": False},
-            )
-            with self.assertRaisesRegex(
-                STORE_MODULE.GroupConflictError, "enabled replacement"
-            ):
-                store.update_agent(
-                    sole["id"],
-                    sole_agents["host"]["id"],
-                    {"requestId": new_id(), "enabled": False},
-                )
-            with self.assertRaisesRegex(
-                STORE_MODULE.GroupConflictError, "enabled replacement"
-            ):
-                store.delete_agent(
-                    sole["id"],
-                    sole_agents["host"]["id"],
-                    {"requestId": new_id()},
-                )
-
-    def test_enabling_agent_promotes_it_when_migrated_host_is_unavailable(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "恢复群",
-                "cwd": "",
-                "agents": [{"profile": "old"}, {"profile": "new"}],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            with store.connection() as connection:
-                connection.execute(
-                    "UPDATE group_agents SET enabled = 0 WHERE room_id = ?",
-                    (room["id"],),
-                )
-            promoted = store.update_agent(
-                room["id"],
-                agents["new"]["id"],
-                {"requestId": new_id(), "enabled": True},
-            )
-            self.assertIs(promoted["isHost"], True)
-            current = store.get_room(room["id"])["agents"]
-            self.assertEqual(
-                [agent["id"] for agent in current if agent["isHost"]],
-                [agents["new"]["id"]],
-            )
-
-    def test_v4_migration_selects_host_and_preserves_counts(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            store = GroupStore(path)
-            store.initialize()
-            preferred_room = store.create_room({
-                "requestId": new_id(),
-                "name": "优先级群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "plain"},
-                    {"profile": "auto-one", "replyWithoutMention": True},
-                    {"profile": "auto-two", "replyWithoutMention": True},
-                ],
-            })
-            disabled_room = store.create_room({
-                "requestId": new_id(),
-                "name": "全禁用群",
-                "cwd": "",
-                "agents": [{"profile": "old-one"}, {"profile": "old-two"}],
-            })
-            preferred_agents = {
-                agent["profile"]: agent for agent in preferred_room["agents"]
-            }
-            expected_preferred = min(
-                (preferred_agents["auto-one"], preferred_agents["auto-two"]),
-                key=lambda agent: (agent["createdAt"], agent["id"]),
-            )
-            expected_disabled = min(
-                disabled_room["agents"],
-                key=lambda agent: (agent["createdAt"], agent["id"]),
-            )
-            with store.connection() as connection:
-                connection.execute(
-                    "UPDATE group_agents SET enabled = 0 WHERE room_id = ?",
-                    (disabled_room["id"],),
-                )
-                before_counts = {
-                    table: connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
-                    for table in (
-                        "group_rooms",
-                        "group_agents",
-                        "group_messages",
-                        "group_agent_runs",
-                        "group_topics",
-                    )
-                }
-                connection.execute("DROP INDEX idx_group_agents_room_host")
-                connection.execute("ALTER TABLE group_agents DROP COLUMN is_host")
-                connection.execute(
-                    "ALTER TABLE group_agent_runs DROP COLUMN required_reply"
-                )
-                for column in (
-                    "requested_model",
-                    "requested_provider",
-                    "requested_reasoning_effort",
-                    "requested_fast_mode",
-                    "actual_model",
-                    "actual_provider",
-                    "actual_reasoning_effort",
-                    "actual_fast_mode",
-                ):
-                    connection.execute(
-                        f"ALTER TABLE group_agent_runs DROP COLUMN {column}"
-                    )
-                connection.execute(
-                    "UPDATE group_meta SET value = '4' WHERE key = 'schema_version'"
-                )
-
-            migrated = GroupStore(path)
-            migrated.initialize()
-            self.assertEqual(migrated.schema_version(), 14)
-            self.assertTrue(
-                all(
-                    room["orchestrationMode"] == "free"
-                    for room in (
-                        migrated.get_room(preferred_room["id"]),
-                        migrated.get_room(disabled_room["id"]),
-                    )
-                )
-            )
-            with migrated.connection() as connection:
-                after_counts = {
-                    table: connection.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
-                    for table in before_counts
-                }
-                preferred_host = connection.execute(
-                    "SELECT * FROM group_agents WHERE room_id = ? AND is_host = 1",
-                    (preferred_room["id"],),
-                ).fetchone()
-                disabled_host = connection.execute(
-                    "SELECT * FROM group_agents WHERE room_id = ? AND is_host = 1",
-                    (disabled_room["id"],),
-                ).fetchone()
-                replay = json.loads(
-                    connection.execute(
-                        """SELECT response_json FROM group_idempotency
-                        WHERE operation = 'room.created' AND response_json LIKE ?""",
-                        (f'%{preferred_room["id"]}%',),
-                    ).fetchone()[0]
-                )
-                with self.assertRaises(sqlite3.IntegrityError):
-                    connection.execute(
-                        "UPDATE group_agents SET is_host = 1 WHERE id != ? AND room_id = ?",
-                        (preferred_host["id"], preferred_room["id"]),
-                    )
-            self.assertEqual(after_counts, before_counts)
-            self.assertEqual(preferred_host["id"], expected_preferred["id"])
-            self.assertEqual(disabled_host["id"], expected_disabled["id"])
-            self.assertEqual(disabled_host["enabled"], 0)
-            self.assertEqual(sum(agent["isHost"] for agent in replay["agents"]), 1)
-            self.assertEqual(
-                next(agent["id"] for agent in replay["agents"] if agent["isHost"]),
-                expected_preferred["id"],
-            )
-
-    def test_concurrent_host_switches_preserve_unique_host(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "并发群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "host", "isHost": True},
-                    {"profile": "left"},
-                    {"profile": "right"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            barrier = threading.Barrier(2)
-
-            def switch(profile: str) -> dict[str, object]:
-                barrier.wait()
-                return store.update_agent(
-                    room["id"],
-                    agents[profile]["id"],
-                    {"requestId": new_id(), "isHost": True},
-                )
-
-            with ThreadPoolExecutor(max_workers=2) as executor:
-                results = list(executor.map(switch, ("left", "right")))
-            self.assertTrue(all(result["isHost"] for result in results))
-            current = store.get_room(room["id"])["agents"]
-            self.assertEqual(sum(agent["isHost"] for agent in current), 1)
-
-    def test_required_host_prompt_fallback_and_failure_are_visible(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "必答群",
-                "cwd": "",
-                "agents": [{"profile": "host", "isHost": True}],
-            })
-            created = self._send(store, room["id"], "请管理员", [])
-            [run] = created["runs"]
-            claimed = store.claim_next_runnable_run()
-            projection = store.read_run_projection(claimed["id"])
-            self.assertIs(projection["run"]["requiredReply"], True)
-            prompt = ORCHESTRATOR.build_run_prompt(
-                projection, store.get_room(room["id"])["agents"]
-            )
-            envelope = json.loads(prompt.rsplit("GROUP_CONTEXT_JSON=", 1)[1])
-            self.assertIs(envelope["run"]["requiredReply"], True)
-            self.assertIn("唯一管理员", prompt)
-            self.assertNotIn("[[YAOYAO_NO_REPLY_V1]]", prompt)
-
-            before = store.latest_cursor()
-            store.transition_run(run["id"], "failed", error="配置失败")
-            events = store.events_after(before, 10)
-            self.assertTrue(
-                any(event["eventType"] == "message.upsert" for event in events)
-            )
-            response = store.get_message(run["responseMessageId"])
-            self.assertEqual(response["status"], "failed")
-            self.assertEqual(response["error"], "配置失败")
-
-        fallback, clarification = asyncio.run(self._exercise_required_reply_runtime())
-        self.assertEqual(fallback[-1]["content"], ORCHESTRATOR._HOST_FALLBACK_REPLY)
-        self.assertTrue(fallback[-1]["publish"])
-        self.assertEqual(clarification[-1]["content"], "")
-
-    @staticmethod
-    async def _exercise_required_reply_runtime() -> tuple[
-        list[dict[str, object]], list[dict[str, object]]
-    ]:
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(
-                self, _run_id: str, **kwargs: object
-            ) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-            def create_gateway_interaction(
-                self, _run_id: str, **_kwargs: object
-            ) -> dict[str, object]:
-                return {"id": new_id()}
-
-            def expire_interaction(self, interaction_id: str) -> dict[str, object]:
-                return {"id": interaction_id}
-
-        async def complete(*, clarify: bool) -> list[dict[str, object]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=new_id(),
-                room_id=new_id(),
-                topic_id=new_id(),
-                agent_id=new_id(),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="automatic",
-                required_reply=True,
-                automatic_published=True,
-            )
-            if clarify:
-                await orchestrator._apply_runtime_event(
-                    state,
-                    ORCHESTRATOR._GatewayEvent(
-                        runtime_id="runtime",
-                        generation=1,
-                        event_type="clarify.request",
-                        payload={"request_id": "clarify-1", "question": "请补充"},
-                    ),
-                )
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.complete",
-                    payload={
-                        "status": "complete",
-                        "text": "[[YAOYAO_NO_REPLY_V1]]",
-                    },
-                ),
-            )
-            if state.grace_task is not None:
-                state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-            return store.upserts
-
-        return await complete(clarify=False), await complete(clarify=True)
-
-    def test_host_flow_uses_one_turn_token_and_returns_members_to_host(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "管理员协调群",
-                "cwd": "",
-                "orchestrationMode": "host",
-                "agents": [
-                    {"profile": "host", "displayName": "管理员", "isHost": True},
-                    {"profile": "one", "displayName": "成员一"},
-                    {"profile": "two", "displayName": "成员二"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-
-            first = self._send(
-                store,
-                room["id"],
-                "@所有人 按依赖推进",
-                [agents["one"]["id"], agents["two"]["id"]],
-            )
-            second = self._send(store, room["id"], "第二个请求", [])
-            self.assertEqual(
-                self._run_modes(first), {agents["host"]["id"]: "automatic"}
-            )
-            self.assertEqual(
-                self._run_modes(second), {agents["host"]["id"]: "automatic"}
-            )
-            claimed = store.claim_next_runnable_run()
-            self.assertEqual(claimed["rootMessageId"], first["message"]["id"])
-            self.assertIs(
-                store.read_run_projection(claimed["id"])["run"]["requiredReply"],
-                True,
-            )
-            self.assertIsNone(store.claim_next_runnable_run())
-            with self.assertRaisesRegex(
-                STORE_MODULE.GroupConflictError, "runs are active"
-            ):
-                store.update_room(
-                    room["id"],
-                    {"requestId": new_id(), "orchestrationMode": "free"},
-                )
-            store.transition_run(claimed["id"], "failed", error="测试释放令牌")
-            self.assertEqual(
-                store.claim_next_runnable_run()["rootMessageId"],
-                second["message"]["id"],
-            )
-
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "逐步委派群",
-                "cwd": "",
-                "orchestrationMode": "host",
-                "agents": [
-                    {"profile": "host", "displayName": "管理员", "isHost": True},
-                    {"profile": "one", "displayName": "成员一"},
-                    {"profile": "two", "displayName": "成员二"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            source = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["host"]["id"],
-                content="@成员一 调研前端,@成员二 调研后端,并列处理",
-            )
-            delegated = store.complete_cascade(source)
-            self.assertEqual(delegated["runCount"], 2)
-            delegated_runs = [
-                store.get_run(run_id) for run_id in delegated["runIds"]
-            ]
-            self.assertEqual(
-                {run["agentId"] for run in delegated_runs},
-                {agents["one"]["id"], agents["two"]["id"]},
-            )
-            self.assertEqual(
-                {run["triggerMessageId"] for run in delegated_runs},
-                {store.get_run(source)["responseMessageId"]},
-            )
-            with store.connection() as connection:
-                required_replies = connection.execute(
-                    """SELECT required_reply FROM group_agent_runs
-                    WHERE id IN (?, ?)""",
-                    tuple(delegated["runIds"]),
-                ).fetchall()
-            self.assertTrue(all(row[0] == 0 for row in required_replies))
-            self.assertTrue(all(run["depth"] == 1 for run in delegated_runs))
-            self.assertEqual(delegated["systemMessageCount"], 0)
-
-            first_parallel = store.claim_next_runnable_run()
-            second_parallel = store.claim_next_runnable_run()
-            self.assertEqual(
-                {first_parallel["id"], second_parallel["id"]},
-                set(delegated["runIds"]),
-            )
-            self.assertIsNone(store.claim_next_runnable_run())
-            later = self._send(store, room["id"], "这是后续独立请求", [])
-
-            store.upsert_agent_message(
-                first_parallel["id"],
-                content="并列结果一",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-            )
-            store.transition_run(first_parallel["id"], "completed")
-            waiting = store.complete_cascade(first_parallel["id"])
-            self.assertEqual(waiting["runCount"], 0)
-
-            store.upsert_agent_message(
-                second_parallel["id"],
-                content="并列结果二",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-            )
-            store.transition_run(second_parallel["id"], "completed")
-            with self.assertRaisesRegex(
-                STORE_MODULE.GroupConflictError, "runs are active"
-            ):
-                store.update_room(
-                    room["id"],
-                    {"requestId": new_id(), "orchestrationMode": "free"},
-                )
-            joined = store.complete_cascade(second_parallel["id"])
-            self.assertEqual(joined["runCount"], 1)
-            review = store.get_run(joined["runIds"][0])
-            self.assertEqual(review["agentId"], agents["host"]["id"])
-            self.assertEqual(review["depth"], 1)
-            claimed_review = store.claim_next_runnable_run()
-            self.assertEqual(claimed_review["id"], review["id"])
-            projection = store.read_run_projection(review["id"])
-            contents = [message["content"] for message in projection["messages"]]
-            self.assertIn("并列结果一", contents)
-            self.assertIn("并列结果二", contents)
-            self.assertNotIn(later["message"]["content"], contents)
-
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "管理员复核团队",
-                "cwd": "",
-                "orchestrationMode": "host",
-                "agents": [
-                    {"profile": "host", "displayName": "管理员", "isHost": True},
-                    {"profile": "worker", "displayName": "执行者"},
-                    {"profile": "other", "displayName": "其他成员"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            source = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["worker"]["id"],
-                content="结果完成,@其他成员 可以继续",
-            )
-            reviewed = store.complete_cascade(source)
-            self.assertEqual(reviewed["runCount"], 1)
-            review_run = store.get_run(reviewed["runIds"][0])
-            self.assertEqual(review_run["agentId"], agents["host"]["id"])
-            self.assertEqual(review_run["replyMode"], "automatic")
-            self.assertEqual(review_run["depth"], 0)
-            self.assertIs(
-                store.get_message(review_run["responseMessageId"])["visible"], True
-            )
-            claimed = store.claim_next_runnable_run()
-            projection = store.read_run_projection(claimed["id"])
-            self.assertIs(projection["run"]["requiredReply"], True)
-            prompt = ORCHESTRATOR.build_run_prompt(
-                projection, room["agents"]
-            )
-            self.assertIn("当前唯一发言令牌", prompt)
-            self.assertIn("并列执行", prompt)
-
-    def test_v10_migration_adds_free_orchestration_mode(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            store = GroupStore(path)
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "旧版房间",
-                "cwd": "",
-                "agents": [{"profile": "host", "isHost": True}],
-            })
-            with store.connection() as connection:
-                connection.execute(
-                    "ALTER TABLE group_rooms DROP COLUMN orchestration_mode"
-                )
-                connection.execute(
-                    "UPDATE group_meta SET value = '10' WHERE key = 'schema_version'"
-                )
-
-            migrated = GroupStore(path)
-            migrated.initialize()
-            self.assertEqual(migrated.schema_version(), 14)
-            self.assertEqual(
-                migrated.get_room(room["id"])["orchestrationMode"], "free"
-            )
-
-    def test_host_flow_parallel_barrier_returns_failures_to_host(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "并列失败群",
-                "cwd": "",
-                "orchestrationMode": "host",
-                "agents": [
-                    {"profile": "host", "displayName": "管理员", "isHost": True},
-                    {"profile": "one", "displayName": "成员一"},
-                    {"profile": "two", "displayName": "成员二"},
-                ],
-            })
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            source = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["host"]["id"],
-                content="@成员一 检查接口,@成员二 检查数据",
-            )
-            delegated = store.complete_cascade(source)
-            first = store.claim_next_runnable_run()
-            second = store.claim_next_runnable_run()
-            self.assertEqual(
-                {first["id"], second["id"]}, set(delegated["runIds"])
-            )
-
-            store.upsert_agent_message(
-                first["id"],
-                content="接口检查完成",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-            )
-            store.transition_run(first["id"], "completed")
-            self.assertEqual(store.complete_cascade(first["id"])["runCount"], 0)
-
-            store.transition_run(second["id"], "failed", error="数据检查失败")
-            joined = store.complete_cascade(second["id"])
-            self.assertEqual(joined["runCount"], 1)
-            review = store.claim_next_runnable_run()
-            projection = store.read_run_projection(review["id"])
-            self.assertEqual(review["agentId"], agents["host"]["id"])
-            self.assertTrue(
-                any(
-                    message["summary"] == "数据检查失败"
-                    for message in projection["messages"]
-                )
-            )
-
-    @staticmethod
-    def _send(
-        store: GroupStore, room_id: str, content: str, mention_ids: list[str]
-    ) -> dict[str, object]:
-        return store.create_human_message(
-            room_id,
-            request_id=new_id(),
-            client_message_id=new_id(),
-            content=content,
-            mention_agent_ids=mention_ids,
-        )
-
-    @staticmethod
-    def _run_modes(result: dict[str, object]) -> dict[str, str]:
-        return {run["agentId"]: run["replyMode"] for run in result["runs"]}
-
-    @staticmethod
-    def _insert_completed_source(
-        store: GroupStore, room_id: str, agent_id: str, *, content: str
-    ) -> str:
-        message_id, run_id = new_id(), new_id()
-        with store.write_transaction() as connection:
-            now = store._now()
-            store._ensure_topic(connection, room_id, message_id, content, now)
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                 root_message_id, reply_to_message_id, client_message_id,
-                 content, reasoning, tool_state_json, status, error, visible,
-                 created_at, updated_at)
-                VALUES (?, ?, ?, 'agent', ?, 'source', ?, NULL, NULL, ?, '', '[]',
-                        'completed', '', 1, ?, ?)""",
-                (
-                    message_id,
-                    room_id,
-                    message_id,
-                    agent_id,
-                    message_id,
-                    content,
-                    now,
-                    now,
-                ),
-            )
-            connection.execute(
-                """INSERT INTO group_agent_runs
-                (id, room_id, topic_id, agent_id, trigger_message_id,
-                 response_message_id, root_message_id, depth, reply_mode,
-                 required_reply, status, runtime_session_id, error, created_at,
-                 updated_at)
-                VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'mentioned', 0, 'completed',
-                        NULL, '', ?, ?)""",
-                (
-                    run_id,
-                    room_id,
-                    message_id,
-                    agent_id,
-                    message_id,
-                    message_id,
-                    message_id,
-                    now,
-                    now,
-                ),
-            )
-            store._record_cascade_plan(
-                connection,
-                source=store._run_row(connection, run_id),
-                source_message=store._message_row(connection, message_id),
-                created_at=now,
-            )
-        return run_id
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 285
hermes-plugins/yaoyao/dashboard/tests/test_group_merge_contract.py

@@ -1,285 +0,0 @@
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-import subprocess
-import sys
-import tempfile
-import textwrap
-import unittest
-
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-
-
-class GroupMergeContractTests(unittest.TestCase):
-    def test_group_routes_share_yaoyao_plugin_and_lifespan(self) -> None:
-        probe = textwrap.dedent(
-            """
-            import json
-            from pathlib import Path
-            import sys
-            import types
-
-            from fastapi import FastAPI
-            from fastapi.testclient import TestClient
-
-            dashboard_dir = Path(sys.argv[1])
-            sys.path.insert(0, str(dashboard_dir))
-
-            poller = types.ModuleType("poller")
-            poller.start = lambda: None
-            sys.modules["poller"] = poller
-            unrelated_group_api = types.ModuleType("group_plugin_api")
-            sys.modules["group_plugin_api"] = unrelated_group_api
-
-            import plugin_api
-            from hermes_cli import plugins_cmd, web_server
-
-            lifecycle = []
-
-            class FakeOrchestrator:
-                async def start(self):
-                    lifecycle.append("start")
-
-                async def shutdown(self):
-                    lifecycle.append("shutdown")
-
-            class FakeStore:
-                def initialize(self):
-                    return None
-
-                def journal_epoch(self):
-                    return "11111111-1111-4111-8111-111111111111"
-
-                def latest_cursor(self):
-                    return 0
-
-            group_api = plugin_api.group_plugin_api
-            original_plugins = web_server._get_dashboard_plugins
-            original_enabled = plugins_cmd._get_enabled_set
-            original_disabled = plugins_cmd._get_disabled_set
-            web_server._get_dashboard_plugins = lambda: [
-                {"name": "yaoyao", "source": "user"}
-            ]
-            plugins_cmd._get_enabled_set = lambda: {"yaoyao"}
-            plugins_cmd._get_disabled_set = lambda: set()
-            enabled_state = group_api._plugin_runtime_enabled()
-            plugins_cmd._get_disabled_set = lambda: {"yaoyao"}
-            disabled_state = group_api._plugin_runtime_enabled()
-            web_server._get_dashboard_plugins = original_plugins
-            plugins_cmd._get_enabled_set = original_enabled
-            plugins_cmd._get_disabled_set = original_disabled
-
-            group_api.set_store_for_testing(FakeStore())
-            group_api.set_orchestrator_factory_for_testing(
-                lambda _store: FakeOrchestrator()
-            )
-
-            app = FastAPI()
-            app.include_router(
-                plugin_api.router,
-                prefix="/api/plugins/yaoyao",
-            )
-            with TestClient(app) as client:
-                existing_files_status = client.get(
-                    "/api/plugins/yaoyao/files"
-                ).status_code
-                existing_voice_status = client.get(
-                    "/api/plugins/yaoyao/voice/settings"
-                ).status_code
-                capabilities_status = client.get(
-                    "/api/plugins/yaoyao/v1/capabilities"
-                ).status_code
-                lifecycle.append("ready")
-
-            stream = group_api._stream_module
-            stream.PLUGIN_STATE_POLL_SECONDS = 0
-            epoch = "11111111-1111-4111-8111-111111111111"
-
-            class StreamStore:
-                def journal_epoch(self):
-                    return epoch
-
-                def cursor_status(self, _epoch, _cursor):
-                    return "ok"
-
-                def events_after(self, _cursor, _limit):
-                    return []
-
-            class StreamSocket:
-                query_params = {"epoch": epoch, "cursor": "0"}
-
-                def __init__(self):
-                    self.frames = []
-                    self.close_codes = []
-
-                async def accept(self):
-                    return None
-
-                async def send_json(self, frame):
-                    self.frames.append(frame)
-
-                async def close(self, code, reason=None):
-                    self.close_codes.append(code)
-
-                async def receive(self):
-                    import asyncio
-                    await asyncio.Future()
-
-            availability = iter([True, False])
-            socket = StreamSocket()
-            import asyncio
-            asyncio.run(
-                stream.stream_authorized_group_events(
-                    socket,
-                    lambda: StreamStore(),
-                    availability_provider=lambda: next(availability, False),
-                )
-            )
-
-            orchestrator_module = __import__(
-                f"{group_api._LOCAL_PACKAGE}.group_orchestrator",
-                fromlist=["GroupOrchestrator"],
-            )
-            orchestrator_module._WORK_DISABLED_RETRY_SECONDS = 0.01
-
-            class SchedulerStore:
-                def __init__(self):
-                    self.cascade_calls = 0
-                    self.claim_calls = 0
-
-                def initialize(self):
-                    return None
-
-                def recover_after_restart(self):
-                    return []
-
-                def list_pending_cascades(self, *, limit):
-                    self.cascade_calls += 1
-                    return {"items": [], "nextCursor": None}
-
-                def claim_next_runnable_run(self):
-                    self.claim_calls += 1
-                    return None
-
-            class SchedulerTransport:
-                def drain(self, _timeout):
-                    return None
-
-            class SchedulerGateway:
-                transport = SchedulerTransport()
-
-                def shutdown(self):
-                    return None
-
-            async def exercise_scheduler_gate():
-                scheduler_store = SchedulerStore()
-                work_enabled = [False]
-                orchestrator = orchestrator_module.GroupOrchestrator(
-                    scheduler_store,
-                    gateway_factory=lambda _callback: SchedulerGateway(),
-                    work_enabled=lambda: work_enabled[0],
-                )
-                await orchestrator.start()
-                await asyncio.sleep(0.04)
-                disabled_calls = [
-                    scheduler_store.cascade_calls,
-                    scheduler_store.claim_calls,
-                ]
-                work_enabled[0] = True
-                for _ in range(100):
-                    if (
-                        scheduler_store.cascade_calls > 0
-                        and scheduler_store.claim_calls > 0
-                    ):
-                        break
-                    await asyncio.sleep(0.005)
-                enabled_calls = [
-                    scheduler_store.cascade_calls,
-                    scheduler_store.claim_calls,
-                ]
-                await orchestrator.shutdown()
-                return disabled_calls, enabled_calls
-
-            disabled_calls, enabled_calls = asyncio.run(exercise_scheduler_gate())
-
-            class DisabledSocket:
-                def __init__(self):
-                    self.close_codes = []
-
-                async def close(self, code, reason=None):
-                    self.close_codes.append(code)
-
-            original_upgrade_allowed = stream.websocket_upgrade_allowed
-            original_runtime_enabled = group_api._plugin_runtime_enabled
-            stream.websocket_upgrade_allowed = lambda _websocket: (True, 1000)
-            group_api._plugin_runtime_enabled = lambda: False
-            disabled_socket = DisabledSocket()
-            asyncio.run(group_api.stream_events(disabled_socket))
-            stream.websocket_upgrade_allowed = original_upgrade_allowed
-            group_api._plugin_runtime_enabled = original_runtime_enabled
-
-            print(json.dumps({
-                "paths": sorted(
-                    getattr(route, "path", "")
-                    for route in plugin_api.router.routes
-                ),
-                "lifecycle": lifecycle,
-                "storePath": str(group_api.GroupStore.from_environment().path),
-                "moduleIsPrivate": group_api is not unrelated_group_api,
-                "pluginGate": [enabled_state, disabled_state],
-                "streamFrames": socket.frames,
-                "streamCloseCodes": socket.close_codes,
-                "disabledWorkCalls": disabled_calls,
-                "enabledWorkCalls": enabled_calls,
-                "disabledConnectCloseCodes": disabled_socket.close_codes,
-                "statuses": [
-                    existing_files_status,
-                    existing_voice_status,
-                    capabilities_status,
-                ],
-            }))
-            """
-        )
-
-        with tempfile.TemporaryDirectory() as hermes_home:
-            environment = dict(os.environ)
-            environment["HERMES_HOME"] = hermes_home
-            result = subprocess.run(
-                [sys.executable, "-c", probe, str(DASHBOARD_DIR)],
-                check=True,
-                capture_output=True,
-                text=True,
-                env=environment,
-            )
-
-        payload = json.loads(result.stdout.strip().splitlines()[-1])
-        self.assertIn("/files", payload["paths"])
-        self.assertIn("/voice/settings", payload["paths"])
-        self.assertIn("/v1/capabilities", payload["paths"])
-        self.assertIn("/v1/events", payload["paths"])
-        self.assertTrue(payload["moduleIsPrivate"])
-        self.assertEqual(payload["pluginGate"], [True, False])
-        self.assertEqual(payload["streamFrames"][0]["type"], "group.ready")
-        self.assertEqual(payload["streamCloseCodes"], [4404])
-        self.assertEqual(payload["disabledWorkCalls"], [0, 0])
-        self.assertGreater(payload["enabledWorkCalls"][0], 0)
-        self.assertGreater(payload["enabledWorkCalls"][1], 0)
-        self.assertEqual(payload["disabledConnectCloseCodes"], [4404])
-        self.assertEqual(payload["statuses"], [200, 200, 200])
-        self.assertEqual(payload["lifecycle"], ["start", "ready", "shutdown"])
-        self.assertEqual(
-            payload["storePath"],
-            str(
-                Path(hermes_home).resolve()
-                / "plugin-data"
-                / "yaoyao"
-                / "group-chat.db"
-            ),
-        )
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 2384
hermes-plugins/yaoyao/dashboard/tests/test_group_settings_contract.py

@@ -1,2384 +0,0 @@
-from __future__ import annotations
-
-import importlib
-import asyncio
-import base64
-import hashlib
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-import json
-import os
-from pathlib import Path
-import sqlite3
-import sys
-import subprocess
-import tempfile
-import textwrap
-import threading
-import time
-import unittest
-import uuid
-
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-if str(DASHBOARD_DIR) not in sys.path:
-    sys.path.insert(0, str(DASHBOARD_DIR))
-
-import group_plugin_api  # noqa: E402
-
-
-PROTOCOL = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_protocol")
-STORE_MODULE = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_store")
-ORCHESTRATOR = importlib.import_module(
-    f"{group_plugin_api._LOCAL_PACKAGE}.group_orchestrator"
-)
-GATEWAY = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_gateway")
-NODE_WORKER = importlib.import_module(
-    f"{group_plugin_api._LOCAL_PACKAGE}.group_node_worker"
-)
-NODE_REGISTRY = importlib.import_module(
-    f"{group_plugin_api._LOCAL_PACKAGE}.group_node_registry"
-)
-REMOTE_GATEWAY = importlib.import_module(
-    f"{group_plugin_api._LOCAL_PACKAGE}.group_remote_gateway"
-)
-GroupStore = STORE_MODULE.GroupStore
-
-
-def request_id() -> str:
-    return str(uuid.uuid4())
-
-
-class GroupSettingsContractTests(unittest.TestCase):
-    def test_room_accepts_same_profile_from_local_and_paired_node(self) -> None:
-        node_id = request_id()
-        request = PROTOCOL.CreateRoomRequest.model_validate({
-            "requestId": request_id(),
-            "name": "跨节点评审",
-            "agents": [
-                {"profile": "default", "displayName": "本机 Agent"},
-                {
-                    "profile": "default",
-                    "nodeId": node_id,
-                    "nodeLabel": "MacBook Pro",
-                    "displayName": "远端 Agent",
-                },
-            ],
-        })
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                group_plugin_api._create_room_command(request)
-            )
-            agents_by_node = {item["nodeId"]: item for item in room["agents"]}
-            self.assertEqual(set(agents_by_node), {"local", node_id})
-            self.assertEqual(agents_by_node["local"]["profile"], "default")
-            self.assertEqual(agents_by_node[node_id]["profile"], "default")
-            self.assertEqual(agents_by_node[node_id]["nodeLabel"], "MacBook Pro")
-            self.assertEqual(
-                {(item["nodeId"], item["profile"]) for item in room["avatarMembers"]},
-                {("local", "default"), (node_id, "default")},
-            )
-            [summary] = store.list_rooms(limit=50, cursor=None).items
-            self.assertEqual(
-                {(item["nodeId"], item["profile"]) for item in summary["avatarMembers"]},
-                {("local", "default"), (node_id, "default")},
-            )
-            with store.connection() as connection:
-                stored = connection.execute(
-                    "SELECT profile, execution_profile FROM group_agents "
-                    "ORDER BY created_at, id"
-                ).fetchall()
-            self.assertNotEqual(stored[0]["profile"], stored[1]["profile"])
-            self.assertIn("default", {row["execution_profile"] for row in stored})
-
-    def test_add_agent_accepts_and_replays_paired_node_identity(self) -> None:
-        node_id = request_id()
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": request_id(),
-                "name": "跨节点增员",
-                "cwd": "",
-                "agents": [{"profile": "default", "displayName": "本机"}],
-            })
-            request = PROTOCOL.AddAgentRequest.model_validate({
-                "requestId": request_id(),
-                "profile": "default",
-                "nodeId": node_id,
-                "nodeLabel": "Remote Mac",
-                "displayName": "远端 Agent",
-            })
-            command = group_plugin_api._add_agent_command(request)
-
-            created = store.add_agent(room["id"], command)
-            replayed = store.add_agent(room["id"], command)
-
-            self.assertEqual(replayed, created)
-            self.assertEqual(created["nodeId"], node_id)
-            self.assertEqual(created["nodeLabel"], "Remote Mac")
-            self.assertEqual(created["profile"], "default")
-            with store.connection() as connection:
-                stored = connection.execute(
-                    "SELECT profile, node_id, node_label, execution_profile "
-                    "FROM group_agents WHERE id = ?",
-                    (created["id"],),
-                ).fetchone()
-            self.assertEqual(stored["node_id"], node_id)
-            self.assertEqual(stored["node_label"], "Remote Mac")
-            self.assertEqual(stored["execution_profile"], "default")
-            self.assertEqual(stored["profile"], f"node:{node_id}:default")
-
-    def test_paired_node_registry_encrypts_token_and_router_scopes_runtime(self) -> None:
-        node_id = request_id()
-        with tempfile.TemporaryDirectory() as directory:
-            registry = NODE_REGISTRY.PairedNodeRegistry(Path(directory))
-            registered = registry.register({
-                "nodeId": node_id,
-                "name": "远端 Mac",
-                "serverUrl": "https://remote.example/node/11111111-1111-4111-8111-111111111111",
-                "fingerprint": "fingerprint",
-                "accessToken": "top-secret-token",
-                "profiles": [{
-                    "name": "default",
-                    "displayName": "远端 Agent",
-                    "model": "provider/model",
-                    "avatar": "data:image/png;base64,AAAA",
-                    "color": "#336699",
-                }],
-            })
-            self.assertNotIn("accessToken", registered)
-            self.assertEqual(
-                registered["profiles"][0]["avatar"],
-                "data:image/png;base64,AAAA",
-            )
-            persisted = (Path(directory) / "paired-group-nodes.json").read_text()
-            self.assertNotIn("top-secret-token", persisted)
-            self.assertEqual(registry.get(node_id)["accessToken"], "top-secret-token")
-
-            events: list[tuple[str, str, dict[str, object]]] = []
-            remote = _FakeRemoteGateway()
-            router = REMOTE_GATEWAY.GroupGatewayRouter(
-                lambda *event: events.append(event),
-                registry=registry,
-                local=_FakeNodeGateway(),
-                remote_factory=lambda _node, callback: remote.bind(callback),
-            )
-            identity = router.create_session_for_node(
-                node_id, "default", "群聊", "", [], None
-            )
-            self.assertTrue(identity.runtime_id.startswith("remote:"))
-            router.submit_prompt(identity.runtime_id, "执行")
-            self.assertEqual(remote.submissions, [("remote-runtime", "执行")])
-            remote.emit("remote-runtime", "message.delta", {"text": "完成"})
-            self.assertEqual(events, [(identity.runtime_id, "message.delta", {"text": "完成"})])
-            router.shutdown()
-
-    def test_remote_gateway_adapter_calls_paired_worker_and_replays_events(self) -> None:
-        _WorkerHTTPHandler.prompts = []
-        _WorkerHTTPHandler.attachments = []
-        _WorkerHTTPHandler.emitted = False
-        server = ThreadingHTTPServer(("127.0.0.1", 0), _WorkerHTTPHandler)
-        thread = threading.Thread(target=server.serve_forever, daemon=True)
-        thread.start()
-        events: list[tuple[str, str, dict[str, object]]] = []
-        attachments = tempfile.TemporaryDirectory()
-        attachment_root = Path(attachments.name)
-        room_root = attachment_root / "room"
-        room_root.mkdir()
-        attachment_path = room_root / "资料.txt"
-        attachment_path.write_text("跨节点附件", encoding="utf-8")
-        adapter = REMOTE_GATEWAY.RemoteNodeGatewayAdapter(
-            {
-                "serverUrl": (
-                    f"http://127.0.0.1:{server.server_port}"
-                    "/node/11111111-1111-4111-8111-111111111111"
-                ),
-                "accessToken": "worker-token",
-            },
-            lambda *event: events.append(event),
-            poll_interval=0.01,
-            attachment_root=attachment_root,
-        )
-        try:
-            identity = adapter.create_session(
-                "default", "跨节点", "", [], None
-            )
-            self.assertEqual(identity.runtime_id, "runtime-http")
-            adapter.submit_prompt(
-                identity.runtime_id,
-                f"开始\n\n[资料](<{attachment_path}>)",
-            )
-            deadline = time.time() + 2
-            while not events and time.time() < deadline:
-                time.sleep(0.01)
-            self.assertEqual(
-                events,
-                [("runtime-http", "message.complete", {"text": "远端完成"})],
-            )
-            self.assertIn("开始", _WorkerHTTPHandler.prompts[0])
-            self.assertIn("attachment://", _WorkerHTTPHandler.prompts[0])
-            self.assertEqual(
-                _WorkerHTTPHandler.attachments,
-                [("资料.txt", "跨节点附件".encode("utf-8"))],
-            )
-        finally:
-            adapter.shutdown()
-            server.shutdown()
-            server.server_close()
-            thread.join(timeout=2)
-            attachments.cleanup()
-
-    def test_orchestrator_dispatches_remote_agent_through_node_router(self) -> None:
-        node_id = request_id()
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": request_id(),
-                "name": "远程执行",
-                "cwd": directory,
-                "agents": [{
-                    "profile": "default",
-                    "nodeId": node_id,
-                    "nodeLabel": "Remote Mac",
-                    "displayName": "远端 Agent",
-                }],
-            })
-            [agent] = room["agents"]
-            created = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="执行远端任务",
-                mention_agent_ids=[agent["id"]],
-            )
-            run_id = created["runs"][0]["id"]
-            gateway_holder: list[_CrossNodeOrchestratorGateway] = []
-
-            async def exercise() -> None:
-                def factory(callback):
-                    gateway = _CrossNodeOrchestratorGateway(callback)
-                    gateway_holder.append(gateway)
-                    return gateway
-
-                orchestrator = ORCHESTRATOR.GroupOrchestrator(
-                    store,
-                    gateway_factory=factory,
-                    completion_timeout=2,
-                )
-                await orchestrator.start()
-                orchestrator.wake()
-                deadline = asyncio.get_running_loop().time() + 3
-                while store.get_run(run_id)["status"] not in {
-                    "completed", "failed", "interrupted"
-                }:
-                    if asyncio.get_running_loop().time() >= deadline:
-                        self.fail("Remote Agent run did not settle")
-                    await asyncio.sleep(0.01)
-                await orchestrator.shutdown()
-
-            asyncio.run(exercise())
-            [gateway] = gateway_holder
-            self.assertEqual(gateway.remote_opens[0][:2], (node_id, "default"))
-            self.assertEqual(gateway.remote_opens[0][2], "")
-            self.assertEqual(store.get_run(run_id)["status"], "completed")
-            messages = store.list_messages(room["id"])
-            self.assertEqual(messages[-1]["content"], "远端完成")
-
-    def test_node_worker_routes_and_bounded_event_replay(self) -> None:
-        gateway = _FakeNodeGateway()
-        worker = NODE_WORKER.NodeGatewayWorker(gateway=gateway)
-        opened = worker.open_session(
-            NODE_WORKER.NodeWorkerOpenRequest.model_validate({
-                "profile": "remote-agent",
-                "title": "跨节点群聊",
-                "cwd": "",
-            })
-        )
-        self.assertEqual(opened["storedSessionId"], "stored-1")
-        self.assertEqual(opened["runtimeSessionId"], "runtime-1")
-
-        worker.submit_prompt(
-            "runtime-1",
-            NODE_WORKER.NodeWorkerPromptRequest(text="请分析"),
-        )
-        self.assertEqual(gateway.submissions, [("runtime-1", "请分析")])
-        worker.attach_file(
-            "runtime-1",
-            name="资料.txt",
-            mime_type="text/plain",
-            content="附件内容".encode("utf-8"),
-        )
-        self.assertEqual(gateway.requests[0][0], "file.attach")
-        self.assertTrue(
-            gateway.requests[0][1]["data_url"].startswith(
-                "data:text/plain;base64,"
-            )
-        )
-        worker._on_event("runtime-1", "message.delta", {"text": "结果"})
-        page = worker.events(after=0, runtime_id="runtime-1", limit=100)
-        self.assertEqual(page["latestCursor"], 1)
-        self.assertEqual(page["items"][0]["payload"], {"text": "结果"})
-        self.assertFalse(page["reset"])
-        self.assertEqual(
-            worker.events(
-                after=0,
-                runtime_id=None,
-                limit=100,
-                client_id="another-client",
-            )["items"],
-            [],
-        )
-        with self.assertRaises(NODE_WORKER.NodeWorkerError):
-            worker.interrupt("runtime-1", client_id="another-client")
-
-        paths = {getattr(route, "path", "") for route in group_plugin_api.router.routes}
-        self.assertIn("/v1/node-worker/sessions", paths)
-        self.assertIn("/v1/node-worker/events", paths)
-        worker.shutdown()
-        self.assertTrue(gateway.shutdown_called)
-
-    def test_room_instructions_round_trip_into_agent_prompt(self) -> None:
-        create = PROTOCOL.CreateRoomRequest.model_validate({
-            "requestId": request_id(),
-            "name": "规则群",
-            "instructions": "  先核对事实。\r\n结论使用中文。  ",
-            "agents": [{"profile": "default"}],
-        })
-        self.assertEqual(create.instructions, "先核对事实。\n结论使用中文。")
-        self.assertEqual(
-            PROTOCOL.limits_payload()["maxRoomInstructionsLength"], 4_000
-        )
-        with self.assertRaises(ValueError):
-            PROTOCOL.UpdateRoomRequest.model_validate({
-                "requestId": request_id(),
-                "instructions": "x" * 4_001,
-            })
-
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": request_id(),
-                "name": "规则群",
-                "cwd": "",
-                "instructions": create.instructions,
-                "agents": [{"profile": "default"}],
-            })
-            self.assertEqual(room["instructions"], create.instructions)
-            [agent] = room["agents"]
-            created = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="请执行",
-                mention_agent_ids=[agent["id"]],
-            )
-            claimed = store.claim_next_runnable_run()
-            self.assertEqual(claimed["id"], created["runs"][0]["id"])
-            projection = store.read_run_projection(claimed["id"])
-            self.assertEqual(
-                projection["room"]["instructions"], create.instructions
-            )
-            prompt = ORCHESTRATOR.build_run_prompt(projection, room["agents"])
-            self.assertIn("长期说明、协作规则和形式准则", prompt)
-            self.assertIn("先核对事实", prompt)
-
-            updated = store.update_room(
-                room["id"],
-                {"requestId": request_id(), "instructions": ""},
-            )
-            self.assertEqual(updated["instructions"], "")
-
-    def test_v11_database_migrates_empty_room_instructions(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            store = GroupStore(path)
-            store.initialize()
-            room = store.create_room({
-                "requestId": request_id(),
-                "name": "旧房间",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            with store.connection() as connection:
-                connection.execute("ALTER TABLE group_rooms DROP COLUMN instructions")
-                connection.execute(
-                    "UPDATE group_meta SET value = '11' WHERE key = 'schema_version'"
-                )
-
-            migrated = GroupStore(path)
-            migrated.initialize()
-            self.assertEqual(migrated.schema_version(), 14)
-            self.assertEqual(migrated.get_room(room["id"])["instructions"], "")
-
-    def test_terminal_session_info_captures_effective_model_for_settlement(self) -> None:
-        async def exercise() -> tuple[object, dict[str, object]]:
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(object())
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=request_id(),
-                room_id=request_id(),
-                topic_id=request_id(),
-                agent_id=request_id(),
-                runtime_id="runtime-effective-model",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored-before",
-                expected_context_seq=0,
-                through_seq=0,
-                profile="default",
-                complete_seen=True,
-                complete_index=1,
-                event_index=2,
-                terminal_status="completed",
-            )
-            captured: dict[str, object] = {}
-
-            async def capture(_state: object, **kwargs: object) -> None:
-                captured.update(kwargs)
-
-            orchestrator._finalize_state_locked = capture  # type: ignore[method-assign]
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id=state.runtime_id,
-                    generation=state.generation,
-                    event_type="session.info",
-                    payload={
-                        "running": False,
-                        "stored_session_id": "stored-after",
-                        "profile_name": "default",
-                        "model": "claude-sonnet-4-6",
-                        "provider": "anthropic",
-                        "reasoning_effort": "xhigh",
-                        "fast": True,
-                    },
-                ),
-            )
-            return state, captured
-
-        state, captured = asyncio.run(exercise())
-        self.assertEqual(state.actual_model, "claude-sonnet-4-6")
-        self.assertEqual(state.actual_provider, "anthropic")
-        self.assertEqual(state.actual_reasoning_effort, "xhigh")
-        self.assertTrue(state.actual_fast_mode)
-        self.assertEqual(captured["outcome"], "completed")
-        self.assertEqual(captured["stored_session_id"], "stored-after")
-
-    def test_run_records_configured_and_effective_model_on_topic_message(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "模型记录群",
-                    "cwd": "",
-                    "agents": [
-                        {
-                            "profile": "default",
-                            "model": "gpt-5.6",
-                            "provider": "openai-codex",
-                            "reasoningEffort": "high",
-                            "fastMode": False,
-                        }
-                    ],
-                }
-            )
-            created = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="请回答",
-                mention_agent_ids=[room["agents"][0]["id"]],
-            )
-            run = created["runs"][0]
-            self.assertEqual(run["requestedModel"], "gpt-5.6")
-            self.assertEqual(run["requestedProvider"], "openai-codex")
-            self.assertEqual(run["requestedReasoningEffort"], "high")
-            self.assertFalse(run["requestedFastMode"])
-            self.assertIsNone(run["actualModel"])
-
-            claimed = store.claim_next_runnable_run()
-            self.assertEqual(claimed["id"], run["id"])
-            store.bind_run_runtime(run["id"], "runtime-model-attribution")
-            store.upsert_agent_message(
-                run["id"],
-                content="已使用备用模型完成",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-            )
-            settled = store.settle_run(
-                run["id"],
-                runtime_session_id="runtime-model-attribution",
-                expected_stored_session_id=None,
-                stored_session_id="stored-model-attribution",
-                outcome="completed",
-                actual_model="claude-sonnet-4-6",
-                actual_provider="anthropic",
-                actual_reasoning_effort="xhigh",
-                actual_fast_mode=True,
-            )
-            self.assertEqual(
-                settled["run"]["actualModel"], "claude-sonnet-4-6"
-            )
-            self.assertEqual(settled["run"]["actualProvider"], "anthropic")
-            self.assertEqual(settled["run"]["actualReasoningEffort"], "xhigh")
-            self.assertTrue(settled["run"]["actualFastMode"])
-
-            messages = store.list_messages(
-                room["id"], topic_id=created["message"]["topicId"], limit=100
-            )
-            response = next(item for item in messages if item["senderKind"] == "agent")
-            self.assertEqual(
-                response["execution"],
-                {
-                    "requestedModel": "gpt-5.6",
-                    "requestedProvider": "openai-codex",
-                    "requestedReasoningEffort": "high",
-                    "requestedFastMode": False,
-                    "actualModel": "claude-sonnet-4-6",
-                    "actualProvider": "anthropic",
-                    "actualReasoningEffort": "xhigh",
-                    "actualFastMode": True,
-                },
-            )
-
-    def test_gateway_session_create_receives_agent_configuration(self) -> None:
-        captured: dict[str, object] = {}
-        adapter = GATEWAY.GroupGatewayAdapter(dispatcher=lambda *_: None)
-
-        def request(method: str, params: dict[str, object]) -> dict[str, object]:
-            captured["method"] = method
-            captured["params"] = params
-            return {
-                "session_id": "runtime-1",
-                "stored_session_id": "stored-1",
-                "running": False,
-                "info": {"profile_name": "yaoyao"},
-            }
-
-        adapter.request = request
-        try:
-            adapter.create_session(
-                "yaoyao",
-                "群聊",
-                "",
-                [],
-                {
-                    "model": "gpt-5.6-sol",
-                    "provider": "openai-codex",
-                    "reasoning_effort": "high",
-                    "fast": True,
-                },
-            )
-        finally:
-            adapter.shutdown()
-
-        self.assertEqual(captured["method"], "session.create")
-        params = captured["params"]
-        self.assertEqual(params["model"], "gpt-5.6-sol")
-        self.assertEqual(params["provider"], "openai-codex")
-        self.assertEqual(params["reasoning_effort"], "high")
-        self.assertIs(params["fast"], True)
-
-    def test_agent_configuration_round_trips_and_rotates_on_next_run(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "配置群",
-                    "cwd": "",
-                    "agents": [{
-                        "profile": "yaoyao",
-                        "model": "gpt-5.6-sol",
-                        "provider": "openai-codex",
-                        "reasoningEffort": "high",
-                        "fastMode": True,
-                    }],
-                }
-            )
-            [agent] = room["agents"]
-            self.assertEqual(agent["model"], "gpt-5.6-sol")
-            self.assertEqual(agent["provider"], "openai-codex")
-            self.assertEqual(agent["reasoningEffort"], "high")
-            self.assertIs(agent["fastMode"], True)
-
-            with store.connection() as connection:
-                connection.execute(
-                    """UPDATE group_agents
-                    SET stored_session_id = 'stored-old',
-                        last_context_message_seq = 9,
-                        session_config_json = '{}'
-                    WHERE id = ?""",
-                    (agent["id"],),
-                )
-            store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="开始",
-                mention_agent_ids=[agent["id"]],
-            )
-            claimed = store.claim_next_runnable_run()
-            configuration = {
-                "model": "gpt-5.6-sol",
-                "provider": "openai-codex",
-                "reasoning_effort": "high",
-                "fast": True,
-            }
-            self.assertTrue(
-                store.prepare_run_session_configuration(claimed["id"], configuration)
-            )
-            refreshed = store.get_room(room["id"])["agents"][0]
-            self.assertIsNone(refreshed["storedSessionId"])
-            self.assertEqual(refreshed["lastContextMessageSeq"], 0)
-            self.assertFalse(
-                store.prepare_run_session_configuration(claimed["id"], configuration)
-            )
-
-            cleared = store.update_agent(
-                room["id"],
-                agent["id"],
-                {
-                    "requestId": request_id(),
-                    "model": None,
-                    "provider": None,
-                    "reasoningEffort": None,
-                    "fastMode": None,
-                },
-            )
-            self.assertIsNone(cleared["model"])
-            self.assertIsNone(cleared["provider"])
-            self.assertIsNone(cleared["reasoningEffort"])
-            self.assertIsNone(cleared["fastMode"])
-
-        with self.assertRaisesRegex(ValueError, "model and provider"):
-            PROTOCOL.AddAgentRequest.model_validate({
-                "requestId": request_id(),
-                "profile": "broken",
-                "model": "gpt-5.6-sol",
-            })
-        with self.assertRaisesRegex(ValueError, "model and provider"):
-            PROTOCOL.UpdateAgentRequest.model_validate({
-                "requestId": request_id(),
-                "model": None,
-            })
-
-    def test_run_prompt_accepts_empty_agent_description(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "无职责描述群",
-                    "cwd": "",
-                    "agents": [{"profile": "default"}],
-                }
-            )
-            [agent] = room["agents"]
-            store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="请回复",
-                mention_agent_ids=[agent["id"]],
-            )
-            claimed = store.claim_next_runnable_run()
-            self.assertIsNotNone(claimed)
-            projection = store.read_run_projection(claimed["id"])
-
-            prompt = ORCHESTRATOR.build_run_prompt(
-                projection,
-                store.get_room(room["id"])["agents"],
-            )
-
-            envelope = json.loads(prompt.rsplit("GROUP_CONTEXT_JSON=", 1)[1])
-            self.assertEqual(envelope["agent"]["description"], "")
-
-            invalid_projection = dict(projection)
-            invalid_agent = dict(projection["agent"])
-            invalid_agent["description"] = 1
-            invalid_projection["agent"] = invalid_agent
-            with self.assertRaisesRegex(
-                ORCHESTRATOR.GroupOrchestratorError,
-                "projection.agent.description must be a string",
-            ):
-                ORCHESTRATOR.build_run_prompt(
-                    invalid_projection,
-                    store.get_room(room["id"])["agents"],
-                )
-
-    def test_protocol_v5_advertises_reply_round_contract(self) -> None:
-        self.assertEqual(PROTOCOL.PROTOCOL_VERSION, 12)
-        self.assertEqual(
-            PROTOCOL.limits_payload()["defaultMaxReplyRounds"], 3
-        )
-        self.assertEqual(
-            PROTOCOL.limits_payload()["unlimitedReplyRoundsValue"], -1
-        )
-        self.assertEqual(
-            PROTOCOL.limits_payload()["maxAgentDisplayNameLength"], 100
-        )
-
-        create = PROTOCOL.CreateRoomRequest.model_validate(
-            {
-                "requestId": request_id(),
-                "name": "研发群",
-                "agents": [{"profile": "planner"}],
-            }
-        )
-        self.assertEqual(create.max_reply_rounds, 3)
-        self.assertIsNone(create.agents[0].display_name)
-        self.assertFalse(create.agents[0].reply_without_mention)
-        self.assertFalse(create.agents[0].is_host)
-        for invalid in (0, -2, 101, True, "3"):
-            with self.subTest(invalid=invalid), self.assertRaises(ValueError):
-                PROTOCOL.CreateRoomRequest.model_validate(
-                    {
-                        "requestId": request_id(),
-                        "name": "研发群",
-                        "maxReplyRounds": invalid,
-                        "agents": [{"profile": "planner"}],
-                    }
-                )
-
-    def test_room_avatar_persists_and_auto_mode_exposes_members(self) -> None:
-        avatar = "data:image/png;base64,AA=="
-        request = PROTOCOL.CreateRoomRequest.model_validate({
-            "requestId": request_id(),
-            "name": "头像团队",
-            "avatar": avatar,
-            "agents": [
-                {"profile": "planner", "displayName": "策划"},
-                {"profile": "reviewer", "displayName": "评审"},
-            ],
-        })
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                group_plugin_api._create_room_command(request)
-            )
-            self.assertEqual(room["avatar"], avatar)
-            self.assertEqual(
-                {item["displayName"] for item in room["avatarMembers"]},
-                {"策划", "评审"},
-            )
-
-            [summary] = store.list_rooms(limit=50, cursor=None).items
-            self.assertEqual(summary["avatar"], avatar)
-            self.assertEqual(
-                {item["profile"] for item in summary["avatarMembers"]},
-                {"planner", "reviewer"},
-            )
-
-            updated = store.update_room(room["id"], {
-                "requestId": request_id(),
-                "avatar": "",
-            })
-            self.assertEqual(updated["avatar"], "")
-            self.assertEqual(len(updated["avatarMembers"]), 2)
-
-        for invalid in (
-            "https://example.com/avatar.png",
-            "builtin:team-animal:unknown",
-            "data:image/svg+xml;base64,AA==",
-            "data:image/png;base64,***",
-        ):
-            with self.subTest(invalid=invalid), self.assertRaises(ValueError):
-                PROTOCOL.CreateRoomRequest.model_validate({
-                    "requestId": request_id(),
-                    "name": "头像团队",
-                    "avatar": invalid,
-                    "agents": [{"profile": "planner"}],
-                })
-
-    def test_builtin_team_avatars_are_valid_room_values(self) -> None:
-        for avatar in PROTOCOL.BUILTIN_TEAM_AVATARS:
-            with self.subTest(avatar=avatar):
-                request = PROTOCOL.CreateRoomRequest.model_validate({
-                    "requestId": request_id(),
-                    "name": "动物头像团队",
-                    "avatar": avatar,
-                    "agents": [{"profile": "planner"}],
-                })
-                self.assertEqual(request.avatar, avatar)
-
-    def test_reserved_all_aliases_cannot_be_agent_display_names(self) -> None:
-        model_payloads = (
-            (
-                PROTOCOL.CreateRoomRequest,
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "agents": [{"profile": "planner", "displayName": "所有人"}],
-                },
-            ),
-            (
-                PROTOCOL.AddAgentRequest,
-                {
-                    "requestId": request_id(),
-                    "profile": "planner",
-                    "displayName": " all ",
-                },
-            ),
-            (
-                PROTOCOL.UpdateAgentRequest,
-                {"requestId": request_id(), "displayName": "所有人"},
-            ),
-        )
-        for model, payload in model_payloads:
-            with self.subTest(model=model.__name__), self.assertRaisesRegex(
-                ValueError, "reserved"
-            ):
-                model.model_validate(payload)
-
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(
-                Path(directory) / "group.db",
-                agent_name_resolver=lambda _profile: "所有人",
-            )
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "cwd": "",
-                    "agents": [{"profile": "planner"}],
-                }
-            )
-            [planner] = room["agents"]
-            self.assertEqual(planner["displayName"], "planner")
-
-            with self.assertRaisesRegex(ValueError, "reserved"):
-                store.add_agent(
-                    room["id"],
-                    {
-                        "requestId": request_id(),
-                        "profile": "coder",
-                        "displayName": "所有人",
-                    },
-                )
-            with self.assertRaisesRegex(ValueError, "reserved"):
-                store.update_agent(
-                    room["id"],
-                    planner["id"],
-                    {"requestId": request_id(), "displayName": "所有人"},
-                )
-
-    def test_agent_name_api_rejects_and_filters_reserved_all_aliases(self) -> None:
-        probe = textwrap.dedent(
-            """
-            import json
-            from pathlib import Path
-            import sys
-            import types
-
-            from fastapi import FastAPI
-            from fastapi.testclient import TestClient
-
-            dashboard = Path(sys.argv[1])
-            settings_path = Path(sys.argv[2]) / "agent_settings.json"
-            sys.path.insert(0, str(dashboard))
-            poller = types.ModuleType("poller")
-            poller.start = lambda: None
-            sys.modules["poller"] = poller
-
-            import plugin_api
-            plugin_api._store_for = lambda _profile: object()
-            plugin_api.store._agent_settings_path = lambda _profile: settings_path
-
-            app = FastAPI()
-            app.include_router(plugin_api.router)
-            with TestClient(app) as client:
-                rejected = client.put(
-                    "/agent/settings",
-                    json={"agentName": "所有人"},
-                )
-                accepted = client.put(
-                    "/agent/settings",
-                    json={"agentName": "策划"},
-                )
-                settings_path.write_text(
-                    json.dumps(
-                        {"profile": "default", "agentName": "all", "updatedAt": 1}
-                    ),
-                    encoding="utf-8",
-                )
-                loaded = client.get("/agent/settings")
-            print(json.dumps({
-                "rejectedStatus": rejected.status_code,
-                "acceptedStatus": accepted.status_code,
-                "loadedStatus": loaded.status_code,
-                "loaded": loaded.json(),
-            }, ensure_ascii=False))
-            """
-        )
-        with tempfile.TemporaryDirectory() as directory:
-            result = subprocess.run(
-                [sys.executable, "-c", probe, str(DASHBOARD_DIR), directory],
-                check=True,
-                capture_output=True,
-                text=True,
-            )
-        payload = json.loads(result.stdout.strip().splitlines()[-1])
-        self.assertEqual(payload["rejectedStatus"], 400)
-        self.assertEqual(payload["acceptedStatus"], 200)
-        self.assertEqual(payload["loadedStatus"], 200)
-        self.assertEqual(payload["loaded"]["agentName"], "")
-
-    def test_configured_name_then_profile_fallback_and_all_mention_aliases(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(
-                Path(directory) / "group.db",
-                agent_name_resolver=lambda profile: "策划" if profile == "planner" else "",
-            )
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "cwd": "",
-                    "agents": [
-                        {"profile": "planner", "description": "规划"},
-                        {"profile": "coder", "description": "开发"},
-                        {"profile": "other", "displayName": "planner"},
-                    ],
-                }
-            )
-            by_profile = {agent["profile"]: agent for agent in room["agents"]}
-            planner, coder = by_profile["planner"], by_profile["coder"]
-            self.assertEqual(planner["displayName"], "策划")
-            self.assertEqual(coder["displayName"], "coder")
-
-            with store.connection() as connection:
-                rows = connection.execute(
-                    "SELECT * FROM group_agents WHERE room_id = ? ORDER BY created_at, id",
-                    (room["id"],),
-                ).fetchall()
-            for token, expected in (
-                ("@策划", planner["id"]),
-                ("@planner", planner["id"]),
-                (f"@{planner['id']}", planner["id"]),
-                ("@coder", coder["id"]),
-            ):
-                targets, warnings = store._plan_cascade_mentions(
-                    token, rows, source_agent_id=str(uuid.uuid4())
-                )
-                self.assertEqual(targets, [expected])
-                self.assertEqual(warnings, [])
-
-    def test_initialize_syncs_only_legacy_fallback_names_once(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            legacy = GroupStore(path)
-            legacy.initialize()
-            room = legacy.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "旧群",
-                    "cwd": "",
-                    "agents": [
-                        {"profile": "planner"},
-                        {"profile": "coder", "displayName": "代码员"},
-                        {"profile": "reviewer"},
-                    ],
-                }
-            )
-            before = legacy.latest_cursor()
-
-            configured_names = {
-                "planner": "策划",
-                "coder": "后端",
-                "reviewer": "代码员",
-            }
-            current = GroupStore(
-                path,
-                agent_name_resolver=lambda profile: configured_names.get(profile, ""),
-            )
-            current.initialize()
-
-            refreshed = current.get_room(room["id"])
-            names = {
-                agent["profile"]: agent["displayName"]
-                for agent in refreshed["agents"]
-            }
-            self.assertEqual(
-                names,
-                {
-                    "planner": "策划",
-                    "coder": "代码员",
-                    "reviewer": "reviewer",
-                },
-            )
-            events = current.events_after(before, 20)
-            self.assertEqual(
-                [event["eventType"] for event in events],
-                ["agent.updated", "room.updated"],
-            )
-            planner = next(
-                agent for agent in refreshed["agents"] if agent["profile"] == "planner"
-            )
-            self.assertEqual(events[0]["payload"], planner)
-            summary = current.list_rooms(limit=100, cursor=None).items[0]
-            for key in ("activeRunCount", "unreadCount", "lastMessage"):
-                summary.pop(key)
-            self.assertEqual(events[1]["payload"], summary)
-
-            after_first_initialize = current.latest_cursor()
-            current.initialize()
-            self.assertEqual(current.latest_cursor(), after_first_initialize)
-            self.assertEqual(current.get_room(room["id"]), refreshed)
-
-    def test_reserved_all_mention_precedes_profile_alias_for_human_and_cascade(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "全员群",
-                    "cwd": "",
-                    "agents": [
-                        {"profile": "all", "displayName": "全能"},
-                        {"profile": "所有人", "displayName": "中文全能"},
-                        {"profile": "planner"},
-                        {"profile": "coder"},
-                    ],
-                }
-            )
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            all_ids = {agent["id"] for agent in room["agents"]}
-
-            for token in ("@all 请处理", "@所有人 请处理"):
-                with self.subTest(token=token):
-                    human_all = store.create_human_message(
-                        room["id"],
-                        request_id=request_id(),
-                        client_message_id=request_id(),
-                        content=token,
-                        mention_agent_ids=[],
-                    )
-                    self.assertEqual(
-                        {run["agentId"] for run in human_all["runs"]}, all_ids
-                    )
-                    self.assertTrue(
-                        all(
-                            run["replyMode"] == "mentioned"
-                            for run in human_all["runs"]
-                        )
-                    )
-
-            for token, expected in (
-                ("@planner", agents["planner"]["id"]),
-                (f"@{agents['all']['id']}", agents["all"]["id"]),
-            ):
-                with self.subTest(token=token):
-                    created = store.create_human_message(
-                        room["id"],
-                        request_id=request_id(),
-                        client_message_id=request_id(),
-                        content=token,
-                        mention_agent_ids=[],
-                    )
-                    self.assertEqual(
-                        [run["agentId"] for run in created["runs"]], [expected]
-                    )
-
-            for token in ("@all 继续", "@所有人 继续"):
-                with self.subTest(cascade=token):
-                    source_run_id = self._insert_completed_source(
-                        store,
-                        room["id"],
-                        agents["planner"]["id"],
-                        content=token,
-                        depth=0,
-                    )
-                    cascade = store.complete_cascade(source_run_id)
-                    self.assertEqual(
-                        {
-                            store.get_run(run_id)["agentId"]
-                            for run_id in cascade["runIds"]
-                        },
-                        all_ids - {agents["planner"]["id"]},
-                    )
-
-    def test_implicit_agent_run_is_hidden_and_explicit_wins(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "cwd": "",
-                    "maxReplyRounds": 3,
-                    "agents": [
-                        {
-                            "profile": "planner",
-                            "replyWithoutMention": True,
-                        },
-                        {
-                            "profile": "coder",
-                            "replyWithoutMention": True,
-                        },
-                    ],
-                }
-            )
-            by_profile = {agent["profile"]: agent for agent in room["agents"]}
-            planner = by_profile["planner"]
-            created = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="请看一下",
-                mention_agent_ids=[planner["id"]],
-            )
-            modes = {run["agentId"]: run["replyMode"] for run in created["runs"]}
-            self.assertEqual(modes, {planner["id"]: "mentioned"})
-            listed = store.list_messages(room["id"])
-            self.assertEqual([message["senderId"] for message in listed], ["human", planner["id"]])
-
-    def test_v1_database_migrates_atomically_and_preserves_rows(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            self._create_v1_database(path)
-            store = GroupStore(path)
-            store.initialize()
-            self.assertEqual(store.schema_version(), 14)
-            self.assertEqual(store.journal_epoch(), "11111111-1111-4111-8111-111111111111")
-            with store.connection() as connection:
-                room = connection.execute("SELECT * FROM group_rooms").fetchone()
-                agent = connection.execute("SELECT * FROM group_agents").fetchone()
-                run = connection.execute("SELECT * FROM group_agent_runs").fetchone()
-                message = connection.execute("SELECT * FROM group_messages").fetchone()
-                ledger = connection.execute("SELECT * FROM group_idempotency").fetchone()
-            self.assertEqual(room["max_reply_rounds"], 3)
-            self.assertEqual(agent["reply_without_mention"], 0)
-            self.assertEqual(agent["is_host"], 1)
-            self.assertEqual(run["reply_mode"], "mentioned")
-            self.assertEqual(run["required_reply"], 0)
-            self.assertEqual(message["visible"], 1)
-            self.assertEqual(ledger["response_json"], "{}")
-
-    def test_automatic_no_reply_token_is_internal(self) -> None:
-        self.assertTrue(ORCHESTRATOR._is_no_reply_content("  [[YAOYAO_NO_REPLY_V1]]\n"))
-        self.assertFalse(ORCHESTRATOR._is_no_reply_content("正常回复"))
-
-    def test_v2_schema_with_wrong_defaults_fails_closed(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            self._create_v1_database(path)
-            connection = sqlite3.connect(path)
-            connection.execute(
-                "ALTER TABLE group_rooms ADD COLUMN max_reply_rounds INTEGER NOT NULL DEFAULT 4"
-            )
-            connection.execute(
-                "ALTER TABLE group_agents ADD COLUMN reply_without_mention INTEGER NOT NULL DEFAULT 0"
-            )
-            connection.execute(
-                "ALTER TABLE group_messages ADD COLUMN visible INTEGER NOT NULL DEFAULT 1"
-            )
-            connection.execute(
-                "ALTER TABLE group_agent_runs ADD COLUMN reply_mode TEXT NOT NULL DEFAULT 'mentioned'"
-            )
-            connection.execute(
-                "UPDATE group_meta SET value='2' WHERE key='schema_version'"
-            )
-            connection.commit()
-            connection.close()
-            with self.assertRaises(STORE_MODULE.GroupStoreError):
-                GroupStore(path).initialize()
-
-    def test_v2_room_round_value_corruption_fails_closed(self) -> None:
-        self._assert_v2_value_corruption_fails_closed(
-            "UPDATE group_rooms SET max_reply_rounds = 0"
-        )
-
-    def test_v2_agent_reply_flag_corruption_fails_closed(self) -> None:
-        self._assert_v2_value_corruption_fails_closed(
-            "UPDATE group_agents SET reply_without_mention = 2"
-        )
-
-    def test_v2_message_visibility_corruption_fails_closed(self) -> None:
-        self._assert_v2_value_corruption_fails_closed(
-            "UPDATE group_messages SET visible = 2"
-        )
-
-    def test_v2_run_reply_mode_corruption_fails_closed(self) -> None:
-        self._assert_v2_value_corruption_fails_closed(
-            "UPDATE group_agent_runs SET reply_mode = 'invalid'"
-        )
-
-    def test_v1_create_and_add_ledgers_replay_after_v2_route_dump(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            self._create_v1_database(path)
-            create_id, add_id = request_id(), request_id()
-            legacy_create = {
-                "requestId": create_id,
-                "name": "旧客户端群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "legacy", "displayName": None, "description": ""}
-                ],
-            }
-            connection = sqlite3.connect(path)
-            room_id = connection.execute("SELECT id FROM group_rooms").fetchone()[0]
-            legacy_add = {
-                "requestId": add_id,
-                "profile": "legacy-added",
-                "displayName": None,
-                "description": "",
-            }
-            create_response = {"replayed": "create-v1"}
-            add_response = {"replayed": "add-v1"}
-            ledgers = (
-                (create_id, "room.created", legacy_create, create_response),
-                (
-                    add_id,
-                    "agent.created",
-                    {"body": legacy_add, "roomId": room_id},
-                    add_response,
-                ),
-            )
-            for ledger_id, operation, payload, response in ledgers:
-                canonical_payload = GroupStore._canonical_json(payload)
-                connection.execute(
-                    """INSERT INTO group_idempotency
-                    (request_id, operation, request_hash, response_json, created_at)
-                    VALUES (?, ?, ?, ?, 1)""",
-                    (
-                        ledger_id,
-                        operation,
-                        hashlib.sha256(canonical_payload.encode()).hexdigest(),
-                        GroupStore._canonical_json(response),
-                    ),
-                )
-            connection.commit()
-            connection.close()
-
-            store = GroupStore(path)
-            store.initialize()
-            implicit_create = PROTOCOL.CreateRoomRequest.model_validate(legacy_create)
-            implicit_add = PROTOCOL.AddAgentRequest.model_validate(legacy_add)
-            create_command = group_plugin_api._create_room_command(implicit_create)
-            add_command = group_plugin_api._add_agent_command(implicit_add)
-            self.assertNotIn("maxReplyRounds", create_command)
-            self.assertNotIn("replyWithoutMention", create_command["agents"][0])
-            self.assertNotIn("replyWithoutMention", add_command)
-            self.assertEqual(store.create_room(create_command), create_response)
-            self.assertEqual(store.add_agent(room_id, add_command), add_response)
-
-            explicit_create = PROTOCOL.CreateRoomRequest.model_validate(
-                {**legacy_create, "requestId": request_id(), "maxReplyRounds": 3,
-                 "agents": [{**legacy_create["agents"][0], "replyWithoutMention": False}]}
-            )
-            explicit_add = PROTOCOL.AddAgentRequest.model_validate(
-                {**legacy_add, "requestId": request_id(), "replyWithoutMention": False}
-            )
-            self.assertEqual(
-                group_plugin_api._create_room_command(explicit_create)["maxReplyRounds"],
-                3,
-            )
-            self.assertFalse(
-                group_plugin_api._create_room_command(explicit_create)["agents"][0][
-                    "replyWithoutMention"
-                ]
-            )
-            self.assertFalse(
-                group_plugin_api._add_agent_command(explicit_add)["replyWithoutMention"]
-            )
-
-    def test_plugin_loader_uses_hermes_bot_name_not_legacy_agent_setting(self) -> None:
-        probe = textwrap.dedent(
-            """
-            import json
-            import os
-            from pathlib import Path
-            import sys
-            import types
-
-            hermes_home = Path(os.environ["HERMES_HOME"])
-            hermes_home.mkdir(parents=True, exist_ok=True)
-            (hermes_home / "profile.yaml").write_text(
-                "ui_meta:\\n  hermes-bots:\\n    title: Hermes 名称\\n",
-                encoding="utf-8",
-            )
-            dashboard = Path(sys.argv[1])
-            sys.path.insert(0, str(dashboard))
-            poller = types.ModuleType("poller")
-            poller.start = lambda: None
-            poller._discover_profiles = lambda: [("default", hermes_home)]
-            sys.modules["poller"] = poller
-            import plugin_api
-            plugin_api.store.load_agent_settings = lambda profile: {
-                "profile": profile,
-                "agentName": "现有名称",
-                "updatedAt": 1,
-            }
-            group = plugin_api.group_plugin_api
-            group.set_store_for_testing(None)
-            instance = group._store_instance()
-            instance.initialize()
-            room = instance.create_room({
-                "requestId": "11111111-1111-4111-8111-111111111111",
-                "name": "群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            print(json.dumps({
-                "room": room,
-                "profiles": plugin_api.list_profiles()["profiles"],
-            }, ensure_ascii=False))
-            """
-        )
-        with tempfile.TemporaryDirectory() as hermes_home:
-            environment = dict(os.environ)
-            environment["HERMES_HOME"] = hermes_home
-            result = subprocess.run(
-                [sys.executable, "-c", probe, str(DASHBOARD_DIR)],
-                check=True,
-                capture_output=True,
-                text=True,
-                env=environment,
-            )
-        payload = json.loads(result.stdout.strip().splitlines()[-1])
-        self.assertEqual(payload["room"]["agents"][0]["displayName"], "Hermes 名称")
-        self.assertEqual(payload["profiles"][0]["botName"], "Hermes 名称")
-        self.assertEqual(payload["profiles"][0]["agentName"], "Hermes 名称")
-
-    def test_cascade_freezes_reply_modes_across_rename_and_setting_change(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "cwd": "",
-                    "agents": [
-                        {"profile": "source"},
-                        {"profile": "reviewer", "replyWithoutMention": True},
-                        {"profile": "coder", "displayName": "开发"},
-                    ],
-                }
-            )
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            source_run_id = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["source"]["id"],
-                content="@开发 请继续",
-                depth=0,
-            )
-            store.update_agent(
-                room["id"],
-                agents["coder"]["id"],
-                {"requestId": request_id(), "displayName": "新开发"},
-            )
-            store.update_agent(
-                room["id"],
-                agents["reviewer"]["id"],
-                {"requestId": request_id(), "replyWithoutMention": False},
-            )
-            result = store.complete_cascade(source_run_id)
-            modes = {
-                store.get_run(run_id)["agentId"]: store.get_run(run_id)["replyMode"]
-                for run_id in result["runIds"]
-            }
-            self.assertEqual(
-                modes,
-                {agents["coder"]["id"]: "mentioned"},
-            )
-
-    def test_round_limit_and_unlimited_mode(self) -> None:
-        for max_rounds, depth, expected in ((3, 2, 0), (-1, 20, 1)):
-            with self.subTest(max_rounds=max_rounds), tempfile.TemporaryDirectory() as directory:
-                store = GroupStore(Path(directory) / "group.db")
-                store.initialize()
-                room = store.create_room(
-                    {
-                        "requestId": request_id(),
-                        "name": "研发群",
-                        "cwd": "",
-                        "maxReplyRounds": max_rounds,
-                        "agents": [{"profile": "source"}, {"profile": "target"}],
-                    }
-                )
-                agents = {agent["profile"]: agent for agent in room["agents"]}
-                source_run_id = self._insert_completed_source(
-                    store,
-                    room["id"],
-                    agents["source"]["id"],
-                    content="@target",
-                    depth=depth,
-                )
-                result = store.complete_cascade(source_run_id)
-                self.assertEqual(result["runCount"], expected)
-
-    def test_legacy_v1_pending_cascade_replays_after_schema_migration(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "cwd": "",
-                    "agents": [{"profile": "source"}, {"profile": "target"}],
-                }
-            )
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            source_run_id = self._insert_completed_source(
-                store,
-                room["id"],
-                agents["source"]["id"],
-                content="@target",
-                depth=0,
-            )
-            with store.write_transaction() as connection:
-                ledger = connection.execute(
-                    "SELECT response_json FROM group_idempotency WHERE request_id = ?",
-                    (store._cascade_request_id(source_run_id),),
-                ).fetchone()
-                current = json.loads(ledger["response_json"])
-                legacy = {
-                    "parseVersion": 1,
-                    "sourceMessageId": current["sourceMessageId"],
-                    "sourceRunId": source_run_id,
-                    "state": "pending",
-                    "targetAgentIds": [agents["target"]["id"]],
-                    "version": 1,
-                    "warnings": [],
-                }
-                connection.execute(
-                    """UPDATE group_idempotency SET request_hash = ?, response_json = ?
-                    WHERE request_id = ?""",
-                    (
-                        store._cascade_request_hash(source_run_id, parse_version=1),
-                        store._canonical_json(legacy),
-                        store._cascade_request_id(source_run_id),
-                    ),
-                )
-            first = store.complete_cascade(source_run_id)
-            second = store.complete_cascade(source_run_id)
-            self.assertEqual(first, second)
-            self.assertEqual(first["runCount"], 1)
-            self.assertEqual(store.get_run(first["runIds"][0])["replyMode"], "mentioned")
-
-    def test_automatic_no_reply_buffers_and_never_publishes(self) -> None:
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(self, _run_id: str, **kwargs: object) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-        async def exercise() -> list[dict[str, object]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=str(uuid.uuid4()),
-                room_id=str(uuid.uuid4()),
-                topic_id=str(uuid.uuid4()),
-                agent_id=str(uuid.uuid4()),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="automatic",
-            )
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.delta",
-                    payload={"text": "[[YAOYAO_"},
-                ),
-            )
-            self.assertEqual(store.upserts, [])
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.complete",
-                    payload={"status": "complete", "text": "[[YAOYAO_NO_REPLY_V1]]"},
-                ),
-            )
-            if state.grace_task is not None:
-                state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-            return store.upserts
-
-        [upsert] = asyncio.run(exercise())
-        self.assertEqual(upsert["content"], "")
-        self.assertEqual(upsert["reasoning"], "")
-        self.assertEqual(upsert["tool_state"], [])
-        self.assertEqual(upsert["status"], "completed")
-        self.assertFalse(upsert["publish"])
-
-    def test_automatic_promotion_never_publishes_no_reply_marker(self) -> None:
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(
-                self, _run_id: str, **kwargs: object
-            ) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-            def create_gateway_interaction(
-                self, _run_id: str, **_kwargs: object
-            ) -> dict[str, object]:
-                return {"id": str(uuid.uuid4())}
-
-        async def exercise(
-            content: str,
-            reasoning: str,
-            event_type: str,
-            payload: dict[str, object],
-        ) -> list[dict[str, object]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=str(uuid.uuid4()),
-                room_id=str(uuid.uuid4()),
-                topic_id=str(uuid.uuid4()),
-                agent_id=str(uuid.uuid4()),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="automatic",
-                content=content,
-                reasoning=reasoning,
-                stream_dirty=True,
-            )
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type=event_type,
-                    payload=payload,
-                ),
-            )
-            return store.upserts
-
-        promotions = (
-            ("tool.start", {"tool_id": "tool-1", "name": "检索"}),
-            ("approval.request", {"choices": ["once", "deny"]}),
-            ("clarify.request", {"request_id": "clarify-1", "question": "请确认"}),
-        )
-        marker_cases = (
-            ("[[YAOYAO_NO_REPLY_V1]]", ""),
-            ("正文[[YAOYAO_NO_REPLY_V1]]尾", "正文尾"),
-            ("正文[[YAOYAO_", "正文"),
-            ("正文[[YAOYAO_尾", "正文尾"),
-        )
-        for event_type, payload in promotions:
-            for buffered, expected in marker_cases:
-                with self.subTest(event_type=event_type, buffered=buffered):
-                    upserts = asyncio.run(exercise(buffered, "", event_type, payload))
-                    self.assertTrue(upserts)
-                    self.assertTrue(
-                        all("[[YAOYAO" not in item["content"] for item in upserts)
-                    )
-                    self.assertTrue(
-                        all(item["content"].strip() == expected for item in upserts)
-                    )
-
-            for buffered, expected in marker_cases:
-                reasoning = buffered.replace("正文", "推理")
-                expected_reasoning = expected.replace("正文", "推理")
-                with self.subTest(event_type=event_type, reasoning=reasoning):
-                    upserts = asyncio.run(
-                        exercise("正常正文", reasoning, event_type, payload)
-                    )
-                    self.assertTrue(upserts)
-                    self.assertTrue(
-                        all("[[YAOYAO" not in item["reasoning"] for item in upserts)
-                    )
-                    self.assertTrue(
-                        all(
-                            item["reasoning"].strip() == expected_reasoning
-                            for item in upserts
-                        )
-                    )
-
-            normal = asyncio.run(exercise("正常正文", "正常推理", event_type, payload))
-            self.assertTrue(normal)
-            self.assertTrue(all(item["content"] == "正常正文" for item in normal))
-            self.assertTrue(all(item["reasoning"] == "正常推理" for item in normal))
-            self.assertTrue(all(item["publish"] for item in normal))
-
-    def test_automatic_terminal_never_publishes_reasoning_marker(self) -> None:
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(
-                self, _run_id: str, **kwargs: object
-            ) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-        async def exercise(
-            status: str, reasoning: str
-        ) -> list[dict[str, object]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=str(uuid.uuid4()),
-                room_id=str(uuid.uuid4()),
-                topic_id=str(uuid.uuid4()),
-                agent_id=str(uuid.uuid4()),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="automatic",
-                automatic_published=status != "complete",
-                content="正常正文",
-                reasoning=reasoning,
-                stream_dirty=True,
-            )
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.complete",
-                    payload={
-                        "status": status,
-                        "text": "正常正文",
-                        "reasoning": reasoning,
-                        "error": "失败",
-                    },
-                ),
-            )
-            if state.grace_task is not None:
-                state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-            return store.upserts
-
-        marker_cases = (
-            ("[[YAOYAO_NO_REPLY_V1]]", ""),
-            ("推理[[YAOYAO_NO_REPLY_V1]]尾", "推理尾"),
-            ("推理[[YAOYAO_", "推理"),
-            ("推理[[YAOYAO_尾", "推理尾"),
-        )
-        for status in ("complete", "error", "interrupted"):
-            for reasoning, expected in marker_cases:
-                with self.subTest(status=status, reasoning=reasoning):
-                    upserts = asyncio.run(exercise(status, reasoning))
-                    self.assertTrue(upserts)
-                    self.assertTrue(
-                        all("[[YAOYAO" not in item["reasoning"] for item in upserts)
-                    )
-                    self.assertTrue(
-                        all(item["reasoning"].strip() == expected for item in upserts)
-                    )
-
-    def test_mentioned_reply_preserves_no_reply_text_verbatim(self) -> None:
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(
-                self, _run_id: str, **kwargs: object
-            ) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-        async def exercise() -> list[dict[str, object]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            content = "正文[[YAOYAO_尾"
-            reasoning = "推理[[YAOYAO_NO_REPLY_V1]]尾"
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=str(uuid.uuid4()),
-                room_id=str(uuid.uuid4()),
-                topic_id=str(uuid.uuid4()),
-                agent_id=str(uuid.uuid4()),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="mentioned",
-            )
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.complete",
-                    payload={
-                        "status": "complete",
-                        "text": content,
-                        "reasoning": reasoning,
-                    },
-                ),
-            )
-            if state.grace_task is not None:
-                state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-            return store.upserts
-
-        upserts = asyncio.run(exercise())
-        self.assertTrue(upserts)
-        self.assertEqual(upserts[-1]["content"], "正文[[YAOYAO_尾")
-        self.assertEqual(upserts[-1]["reasoning"], "推理[[YAOYAO_NO_REPLY_V1]]尾")
-
-    def test_unpublished_automatic_failure_discards_buffer_without_message_event(self) -> None:
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(
-                self, _run_id: str, **kwargs: object
-            ) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-        async def exercise(status: str, content: str) -> tuple[object, list[dict[str, object]]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=str(uuid.uuid4()),
-                room_id=str(uuid.uuid4()),
-                topic_id=str(uuid.uuid4()),
-                agent_id=str(uuid.uuid4()),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="automatic",
-                content=content,
-                reasoning="内部推理",
-                tool_state=[{"id": "internal", "status": "running"}],
-                stream_dirty=True,
-            )
-            await orchestrator._apply_runtime_event(
-                state,
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.complete",
-                    payload={"status": status, "text": content, "error": "失败"},
-                ),
-            )
-            if state.grace_task is not None:
-                state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-            return state, store.upserts
-
-        for status in ("error", "interrupted"):
-            for content in ("未完成正文", "正文[[YAOYAO_NO_REPLY_V1]]尾", "[[YAOYAO_"):
-                with self.subTest(status=status, content=content):
-                    state, upserts = asyncio.run(exercise(status, content))
-                    self.assertFalse(state.automatic_published)
-                    self.assertEqual(len(upserts), 1)
-                    self.assertEqual(upserts[0]["content"], "")
-                    self.assertEqual(upserts[0]["reasoning"], "")
-                    self.assertEqual(upserts[0]["tool_state"], [])
-                    self.assertFalse(upserts[0]["publish"])
-
-    def test_hidden_queued_message_blocks_context_watermark_until_terminal(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "乱序群",
-                    "cwd": "",
-                    "agents": [
-                        {"profile": "slow", "replyWithoutMention": True},
-                        {"profile": "fast", "replyWithoutMention": True},
-                        {"profile": "observer"},
-                    ],
-                }
-            )
-            agents = {agent["profile"]: agent for agent in room["agents"]}
-            first = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="并行开始",
-                mention_agent_ids=[],
-            )
-            self.assertEqual(len(first["runs"]), 2)
-            with store.connection() as connection:
-                connection.execute(
-                    "UPDATE group_agents SET reply_without_mention = 0 WHERE room_id = ?",
-                    (room["id"],),
-                )
-                response_seqs = {
-                    run["id"]: int(
-                        connection.execute(
-                            "SELECT seq FROM group_messages WHERE id = ?",
-                            (run["responseMessageId"],),
-                        ).fetchone()["seq"]
-                    )
-                    for run in first["runs"]
-                }
-            slow_id, fast_id = sorted(response_seqs, key=response_seqs.get)
-            claimed = {
-                run["id"]: run
-                for _ in range(2)
-                if (run := store.claim_next_runnable_run()) is not None
-            }
-            self.assertEqual(set(claimed), {slow_id, fast_id})
-
-            def bind(run_id: str, label: str, expected: str | None = None) -> tuple[str, str]:
-                stored, runtime = f"{label}-stored", f"{label}-runtime"
-                store.bind_run_session(
-                    run_id,
-                    expected_stored_session_id=expected,
-                    stored_session_id=stored,
-                    runtime_session_id=runtime,
-                )
-                return stored, runtime
-
-            slow_stored, slow_runtime = bind(slow_id, "slow")
-            fast_stored, fast_runtime = bind(fast_id, "fast")
-            store.upsert_agent_message(
-                fast_id,
-                content="先到正文",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-                publish=True,
-            )
-            store.settle_run(
-                fast_id,
-                runtime_session_id=fast_runtime,
-                expected_stored_session_id=fast_stored,
-                stored_session_id=fast_stored,
-                outcome="completed",
-            )
-
-            observer_first = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="第一次检查",
-                mention_agent_ids=[agents["observer"]["id"]],
-            )["runs"][0]
-            claimed_observer = store.claim_next_runnable_run()
-            self.assertEqual(claimed_observer["id"], observer_first["id"])
-            observer_stored, observer_runtime = bind(observer_first["id"], "observer-1")
-            projection = store.read_run_projection(observer_first["id"])
-            self.assertEqual(projection["throughSeq"], 1)
-            store.advance_run_context(
-                observer_first["id"],
-                runtime_session_id=observer_runtime,
-                expected_context_seq=0,
-                through_seq=projection["throughSeq"],
-            )
-            store.settle_run(
-                observer_first["id"],
-                runtime_session_id=observer_runtime,
-                expected_stored_session_id=observer_stored,
-                stored_session_id=observer_stored,
-                outcome="failed",
-                error="测试结束",
-            )
-
-            store.upsert_agent_message(
-                slow_id,
-                content="迟到正文",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-                publish=True,
-            )
-            store.settle_run(
-                slow_id,
-                runtime_session_id=slow_runtime,
-                expected_stored_session_id=slow_stored,
-                stored_session_id=slow_stored,
-                outcome="completed",
-            )
-
-            observer_second = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="第二次检查",
-                mention_agent_ids=[agents["observer"]["id"]],
-            )["runs"][0]
-            claimed_observer = store.claim_next_runnable_run()
-            self.assertEqual(claimed_observer["id"], observer_second["id"])
-            bind(
-                observer_second["id"],
-                "observer-2",
-                expected=observer_stored,
-            )
-            future = store.read_run_projection(observer_second["id"])
-            self.assertIn("迟到正文", [message["content"] for message in future["messages"]])
-
-    def test_hidden_automatic_failure_emits_run_only_and_replays_exactly(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "研发群",
-                    "cwd": "",
-                    "agents": [
-                        {"profile": "host"},
-                        {"profile": "reviewer", "replyWithoutMention": True},
-                    ],
-                }
-            )
-            created = store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="普通消息",
-                mention_agent_ids=[],
-            )
-            reviewer = next(
-                agent for agent in room["agents"] if agent["profile"] == "reviewer"
-            )
-            run = next(
-                item for item in created["runs"] if item["agentId"] == reviewer["id"]
-            )
-            before = store.latest_cursor()
-            first = store.transition_run(run["id"], "failed", error="失败")
-            second = store.transition_run(run["id"], "failed", error="失败")
-            self.assertEqual(first, second)
-            self.assertEqual(first["replyMode"], "automatic")
-            self.assertNotIn("bufferedResponse", first)
-            events = store.events_after(before, 20)
-            self.assertTrue(
-                any(event["eventType"] == "run.updated" for event in events)
-            )
-            self.assertFalse(
-                any(event["eventType"] == "message.upsert" for event in events)
-            )
-            self.assertEqual(
-                [message["senderId"] for message in store.list_messages(room["id"])],
-                [
-                    "human",
-                    next(agent["id"] for agent in room["agents"] if agent["isHost"]),
-                ],
-            )
-
-    def test_automatic_consumer_waits_without_zero_timeout_and_accepts_terminal(self) -> None:
-        class CountingQueue(asyncio.Queue):
-            def __init__(self) -> None:
-                super().__init__()
-                self.get_calls = 0
-
-            async def get(self):  # type: ignore[override]
-                self.get_calls += 1
-                return await super().get()
-
-        class FakeStore:
-            def __init__(self) -> None:
-                self.upserts: list[dict[str, object]] = []
-
-            def upsert_agent_message(self, _run_id: str, **kwargs: object) -> dict[str, object]:
-                self.upserts.append(dict(kwargs))
-                return dict(kwargs)
-
-        async def exercise() -> tuple[int, list[dict[str, object]]]:
-            store = FakeStore()
-            orchestrator = ORCHESTRATOR.GroupOrchestrator(store)
-            queue = CountingQueue()
-            state = ORCHESTRATOR._RuntimeState(
-                run_id=str(uuid.uuid4()),
-                room_id=str(uuid.uuid4()),
-                topic_id=str(uuid.uuid4()),
-                agent_id=str(uuid.uuid4()),
-                runtime_id="runtime",
-                generation=1,
-                expected_stored_id=None,
-                session_stored_id="stored",
-                expected_context_seq=0,
-                through_seq=0,
-                reply_mode="automatic",
-                pending_events=queue,
-                prompt_committed=True,
-            )
-            orchestrator._runtime_states[state.runtime_id] = (state.generation, state)
-            state.prompt_ready.set()
-            task = asyncio.create_task(orchestrator._consume_runtime_events(state))
-            await queue.put(
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.delta",
-                    payload={"text": "正常"},
-                )
-            )
-            await asyncio.sleep(0.12)
-            calls_after_idle = queue.get_calls
-            await queue.put(
-                ORCHESTRATOR._GatewayEvent(
-                    runtime_id="runtime",
-                    generation=1,
-                    event_type="message.complete",
-                    payload={"status": "complete", "text": "正常回复"},
-                )
-            )
-            for _ in range(100):
-                if store.upserts:
-                    break
-                await asyncio.sleep(0.002)
-            state.finished.set()
-            await queue.put(None)
-            await asyncio.wait_for(task, timeout=1)
-            if state.grace_task is not None:
-                state.grace_task.cancel()
-                await asyncio.gather(state.grace_task, return_exceptions=True)
-            return calls_after_idle, store.upserts
-
-        calls, upserts = asyncio.run(exercise())
-        self.assertLessEqual(calls, 4)
-        self.assertEqual(upserts[-1]["content"], "正常回复")
-        self.assertTrue(upserts[-1]["publish"])
-
-    @staticmethod
-    def _insert_completed_source(
-        store: GroupStore,
-        room_id: str,
-        agent_id: str,
-        *,
-        content: str,
-        depth: int,
-    ) -> str:
-        message_id, run_id = str(uuid.uuid4()), str(uuid.uuid4())
-        with store.write_transaction() as connection:
-            now = 10.0
-            store._ensure_topic(connection, room_id, message_id, content, now)
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, topic_id, sender_kind, sender_id, sender_name, root_message_id,
-                 reply_to_message_id, client_message_id, content, reasoning,
-                 tool_state_json, status, error, visible, created_at, updated_at)
-                VALUES (?, ?, ?, 'agent', ?, 'source', ?, NULL, NULL, ?, '', '[]',
-                        'completed', '', 1, ?, ?)""",
-                (
-                    message_id,
-                    room_id,
-                    message_id,
-                    agent_id,
-                    message_id,
-                    content,
-                    now,
-                    now,
-                ),
-            )
-            connection.execute(
-                """INSERT INTO group_agent_runs
-                (id, room_id, topic_id, agent_id, trigger_message_id, response_message_id,
-                 root_message_id, depth, reply_mode, status, runtime_session_id,
-                 error, created_at, updated_at)
-                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'mentioned', 'completed', NULL, '', ?, ?)""",
-                (
-                    run_id,
-                    room_id,
-                    message_id,
-                    agent_id,
-                    message_id,
-                    message_id,
-                    message_id,
-                    depth,
-                    now,
-                    now,
-                ),
-            )
-            store._record_cascade_plan(
-                connection,
-                source=store._run_row(connection, run_id),
-                source_message=store._message_row(connection, message_id),
-                created_at=now,
-            )
-        return run_id
-
-    def _assert_v2_value_corruption_fails_closed(self, mutation: str) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            store = GroupStore(path)
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": request_id(),
-                    "name": "值域门禁",
-                    "cwd": "",
-                    "agents": [{"profile": "default"}],
-                }
-            )
-            [agent] = room["agents"]
-            store.create_human_message(
-                room["id"],
-                request_id=request_id(),
-                client_message_id=request_id(),
-                content="触发",
-                mention_agent_ids=[agent["id"]],
-            )
-            with store.connection() as connection:
-                connection.execute(mutation)
-            with self.assertRaises(STORE_MODULE.GroupStoreError):
-                GroupStore(path).initialize()
-
-    @staticmethod
-    def _create_v1_database(path: Path) -> None:
-        connection = sqlite3.connect(path)
-        statements = (
-            "CREATE TABLE group_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
-            "CREATE TABLE group_rooms (id TEXT PRIMARY KEY, name TEXT NOT NULL, cwd TEXT NOT NULL DEFAULT '', created_at REAL NOT NULL, updated_at REAL NOT NULL, archived INTEGER NOT NULL DEFAULT 0)",
-            "CREATE TABLE group_agents (id TEXT PRIMARY KEY, room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE, profile TEXT NOT NULL, display_name TEXT NOT NULL, display_name_key TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', stored_session_id TEXT, last_context_message_seq INTEGER NOT NULL DEFAULT 0, enabled INTEGER NOT NULL DEFAULT 1, created_at REAL NOT NULL, updated_at REAL NOT NULL, UNIQUE(room_id, profile), UNIQUE(room_id, display_name_key))",
-            "CREATE TABLE group_messages (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE, sender_kind TEXT NOT NULL, sender_id TEXT NOT NULL, sender_name TEXT NOT NULL, root_message_id TEXT NOT NULL, reply_to_message_id TEXT, client_message_id TEXT UNIQUE, content TEXT NOT NULL DEFAULT '', reasoning TEXT NOT NULL DEFAULT '', tool_state_json TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL, error TEXT NOT NULL DEFAULT '', created_at REAL NOT NULL, updated_at REAL NOT NULL)",
-            "CREATE TABLE group_agent_runs (id TEXT PRIMARY KEY, room_id TEXT NOT NULL, agent_id TEXT NOT NULL, trigger_message_id TEXT NOT NULL, response_message_id TEXT NOT NULL, root_message_id TEXT NOT NULL, depth INTEGER NOT NULL, status TEXT NOT NULL, runtime_session_id TEXT, error TEXT NOT NULL DEFAULT '', created_at REAL NOT NULL, updated_at REAL NOT NULL)",
-            "CREATE TABLE group_interactions (id TEXT PRIMARY KEY, room_id TEXT NOT NULL, agent_id TEXT NOT NULL, run_id TEXT NOT NULL, kind TEXT NOT NULL, payload_json TEXT NOT NULL, status TEXT NOT NULL, created_at REAL NOT NULL, resolved_at REAL)",
-            "CREATE TABLE group_events (cursor INTEGER PRIMARY KEY AUTOINCREMENT, epoch TEXT NOT NULL, room_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at REAL NOT NULL)",
-            "CREATE TABLE group_idempotency (request_id TEXT PRIMARY KEY, operation TEXT NOT NULL, request_hash TEXT NOT NULL, response_json TEXT NOT NULL, created_at REAL NOT NULL)",
-        )
-        for statement in statements:
-            connection.execute(statement)
-        room_id, agent_id, message_id, run_id = (str(uuid.uuid4()) for _ in range(4))
-        connection.executemany(
-            "INSERT INTO group_meta(key,value) VALUES (?,?)",
-            (("schema_version", "1"), ("journal_epoch", "11111111-1111-4111-8111-111111111111")),
-        )
-        connection.execute("INSERT INTO group_rooms VALUES (?,?,?,?,?,?)", (room_id, "旧群", "", 1.0, 1.0, 0))
-        connection.execute("INSERT INTO group_agents VALUES (?,?,?,?,?,?,?,?,?,?,?)", (agent_id, room_id, "default", "旧名", "旧名", "", None, 0, 1, 1.0, 1.0))
-        connection.execute("INSERT INTO group_messages VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (message_id, room_id, "human", "human", "你", message_id, None, str(uuid.uuid4()), "旧消息", "", "[]", "completed", "", 1.0, 1.0))
-        connection.execute("INSERT INTO group_agent_runs VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (run_id, room_id, agent_id, message_id, message_id, message_id, 0, "completed", None, "", 1.0, 1.0))
-        connection.execute("INSERT INTO group_idempotency VALUES (?,?,?,?,?)", (str(uuid.uuid4()), "test", "hash", json.dumps({}), 1.0))
-        connection.commit()
-        connection.close()
-
-
-class _WorkerHTTPHandler(BaseHTTPRequestHandler):
-    prompts: list[str] = []
-    attachments: list[tuple[str, bytes]] = []
-    emitted = False
-
-    def do_POST(self) -> None:  # noqa: N802 - stdlib callback spelling
-        if self.headers.get("Authorization") != "Bearer worker-token":
-            self._json(401, {"error": "unauthorized"})
-            return
-        length = int(self.headers.get("Content-Length", "0"))
-        raw_body = self.rfile.read(length)
-        if self.path.endswith("/sessions/runtime-http/attachments"):
-            encoded_name = self.headers["X-File-Name-B64"]
-            name = base64.urlsafe_b64decode(
-                encoded_name + "=" * (-len(encoded_name) % 4)
-            ).decode()
-            self.attachments.append((name, raw_body))
-            self._json(200, {"attached": True})
-            return
-        body = json.loads(raw_body or b"{}")
-        if self.path.endswith("/node-worker/sessions"):
-            self._json(200, {
-                "storedSessionId": "stored-http",
-                "runtimeSessionId": "runtime-http",
-                "running": False,
-            })
-            return
-        if self.path.endswith("/sessions/runtime-http/prompt"):
-            self.prompts.append(body["text"])
-            self._json(200, {"status": "streaming"})
-            return
-        self._json(404, {"error": "not found"})
-
-    def do_GET(self) -> None:  # noqa: N802 - stdlib callback spelling
-        if self.headers.get("Authorization") != "Bearer worker-token":
-            self._json(401, {"error": "unauthorized"})
-            return
-        if "/node-worker/events?" not in self.path:
-            self._json(404, {"error": "not found"})
-            return
-        items = []
-        if not self.emitted:
-            type(self).emitted = True
-            items = [{
-                "cursor": 1,
-                "runtimeSessionId": "runtime-http",
-                "type": "message.complete",
-                "payload": {"text": "远端完成"},
-            }]
-        self._json(200, {
-            "items": items,
-            "latestCursor": 1 if self.emitted else 0,
-            "oldestCursor": 1,
-            "reset": False,
-        })
-
-    def log_message(self, format: str, *args: object) -> None:
-        _ = (format, args)
-
-    def _json(self, status: int, value: object) -> None:
-        encoded = json.dumps(value).encode()
-        self.send_response(status)
-        self.send_header("Content-Type", "application/json")
-        self.send_header("Content-Length", str(len(encoded)))
-        self.end_headers()
-        self.wfile.write(encoded)
-
-
-class _FakeNodeGateway:
-    def __init__(self) -> None:
-        self.submissions: list[tuple[str, str]] = []
-        self.requests: list[tuple[str, dict[str, object]]] = []
-        self.shutdown_called = False
-
-    def create_session(
-        self,
-        profile: str,
-        title: str,
-        cwd: str,
-        messages: list[dict[str, object]],
-        configuration: dict[str, object],
-    ) -> object:
-        _ = (profile, title, cwd, messages, configuration)
-        return GATEWAY.SessionIdentity("stored-1", "runtime-1", False)
-
-    def resume_session(self, profile: str, stored_id: str) -> object:
-        _ = profile
-        return GATEWAY.SessionIdentity(stored_id, "runtime-1", False)
-
-    def submit_prompt(self, runtime_id: str, text: str) -> None:
-        self.submissions.append((runtime_id, text))
-
-    def request(
-        self, method: str, params: dict[str, object]
-    ) -> dict[str, object]:
-        self.requests.append((method, params))
-        return {"attached": True}
-
-    def interrupt(self, runtime_id: str) -> None:
-        _ = runtime_id
-
-    def close(self, runtime_id: str) -> bool:
-        _ = runtime_id
-        return True
-
-    def respond_approval(self, runtime_id: str, choice: str) -> int:
-        _ = (runtime_id, choice)
-        return 1
-
-    def respond_clarification(self, request_id: str, answer: str) -> str:
-        _ = (request_id, answer)
-        return "ok"
-
-    def shutdown(self) -> None:
-        self.shutdown_called = True
-
-
-class _FakeRemoteGateway(_FakeNodeGateway):
-    def __init__(self) -> None:
-        super().__init__()
-        self.callback = None
-
-    def bind(self, callback):
-        self.callback = callback
-        return self
-
-    def create_session(
-        self,
-        profile: str,
-        title: str,
-        cwd: str,
-        messages: list[dict[str, object]],
-        configuration: dict[str, object] | None,
-    ) -> object:
-        _ = (profile, title, cwd, messages, configuration)
-        return GATEWAY.SessionIdentity(
-            "remote-stored", "remote-runtime", False
-        )
-
-    def emit(
-        self, runtime_id: str, event_type: str, payload: dict[str, object]
-    ) -> None:
-        assert self.callback is not None
-        self.callback(runtime_id, event_type, payload)
-
-    def owns_clarification(self, request_id: str) -> bool:
-        _ = request_id
-        return False
-
-
-class _CrossNodeOrchestratorGateway(_FakeNodeGateway):
-    transport = type(
-        "DrainTransport",
-        (),
-        {"drain": lambda self, timeout=None: True},
-    )()
-
-    def __init__(self, callback) -> None:
-        super().__init__()
-        self.callback = callback
-        self.remote_opens: list[tuple[str, str, str]] = []
-
-    def create_session_for_node(
-        self,
-        node_id: str,
-        profile: str,
-        title: str,
-        cwd: str,
-        messages: list[dict[str, object]],
-        configuration: dict[str, object] | None,
-    ) -> object:
-        _ = (title, messages, configuration)
-        self.remote_opens.append((node_id, profile, cwd))
-        return GATEWAY.SessionIdentity(
-            "remote-stored", "remote:runtime", False
-        )
-
-    def resume_session_for_node(
-        self, node_id: str, profile: str, stored_id: str
-    ) -> object:
-        self.remote_opens.append((node_id, profile, ""))
-        return GATEWAY.SessionIdentity(stored_id, "remote:runtime", False)
-
-    def submit_prompt(self, runtime_id: str, text: str) -> None:
-        self.submissions.append((runtime_id, text))
-        self.callback(runtime_id, "message.delta", {"text": "远端完成"})
-        self.callback(
-            runtime_id,
-            "message.complete",
-            {"status": "complete", "text": "远端完成"},
-        )
-        self.callback(
-            runtime_id,
-            "session.info",
-            {
-                "running": False,
-                "stored_session_id": "remote-stored",
-                "profile_name": "default",
-            },
-        )
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 1965
hermes-plugins/yaoyao/dashboard/tests/test_group_topics_contract.py

@@ -1,1965 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import hashlib
-import importlib
-import json
-import sqlite3
-import sys
-import tempfile
-import unittest
-import uuid
-from io import BytesIO
-from pathlib import Path
-from unittest.mock import AsyncMock, patch
-
-from fastapi import UploadFile
-from starlette.datastructures import Headers
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-if str(DASHBOARD_DIR) not in sys.path:
-    sys.path.insert(0, str(DASHBOARD_DIR))
-
-import group_plugin_api  # noqa: E402
-
-PROTOCOL = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_protocol")
-STORE_MODULE = importlib.import_module(f"{group_plugin_api._LOCAL_PACKAGE}.group_store")
-ORCHESTRATOR = importlib.import_module(
-    f"{group_plugin_api._LOCAL_PACKAGE}.group_orchestrator"
-)
-SETTINGS_TESTS = importlib.import_module("dashboard.tests.test_group_settings_contract")
-GroupStore = STORE_MODULE.GroupStore
-
-
-def new_id() -> str:
-    return str(uuid.uuid4())
-
-
-class GroupTopicsContractTests(unittest.TestCase):
-    def test_protocol_and_router_advertise_topics(self) -> None:
-        self.assertEqual(PROTOCOL.PROTOCOL_VERSION, 12)
-        self.assertIn("topic.updated", PROTOCOL.EVENT_TYPES)
-        self.assertIn("room.activity", PROTOCOL.EVENT_TYPES)
-        request = PROTOCOL.SendMessageRequest.model_validate({
-            "requestId": new_id(),
-            "clientMessageId": new_id(),
-            "topicId": new_id(),
-            "content": "继续",
-            "mentionAgentIds": [],
-        })
-        self.assertIsNotNone(request.topic_id)
-        route_methods = {
-            (route.path, tuple(sorted(route.methods or ())))
-            for route in group_plugin_api.router.routes
-            if hasattr(route, "methods")
-        }
-        self.assertIn(("/v1/rooms/{room_id}/topics", ("GET",)), route_methods)
-        self.assertIn(("/v1/topics", ("GET",)), route_methods)
-        self.assertIn(
-            ("/v1/rooms/{room_id}/topics/{topic_id}", ("PATCH",)),
-            route_methods,
-        )
-        self.assertIn(
-            ("/v1/rooms/{room_id}/topics/{topic_id}/read", ("PATCH",)),
-            route_methods,
-        )
-        read_request = PROTOCOL.MarkTopicReadRequest.model_validate({
-            "requestId": new_id(),
-            "throughSeq": 12,
-        })
-        self.assertEqual(read_request.through_seq, 12)
-        self.assertIn(
-            ("/v1/rooms/{room_id}/uploads", ("POST",)), route_methods
-        )
-
-    def test_capabilities_advertise_global_topics(self) -> None:
-        with patch.object(
-            group_plugin_api,
-            "_store_call",
-            new_callable=AsyncMock,
-            side_effect=[new_id(), 0],
-        ):
-            payload = asyncio.run(group_plugin_api.capabilities())
-        self.assertIn("globalTopics", payload["features"])
-
-    def test_global_topics_are_stably_paginated_and_exclude_archived_scope(
-        self,
-    ) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-
-            def make_room(name: str) -> dict[str, object]:
-                return store.create_room({
-                    "requestId": new_id(),
-                    "name": name,
-                    "cwd": "",
-                    "agents": [{"profile": "default"}],
-                })
-
-            def make_topic(room_id: str, title: str) -> str:
-                created = store.create_human_message(
-                    room_id,
-                    request_id=new_id(),
-                    client_message_id=new_id(),
-                    topic_id=new_id(),
-                    content=title,
-                    mention_agent_ids=[],
-                )
-                return created["message"]["topicId"]
-
-            room_a = make_room("设计团队")
-            room_b = make_room("发布团队")
-            archived_room = make_room("归档团队")
-            pinned_id = make_topic(room_a["id"], "置顶但较早")
-            recent_a_id = make_topic(room_a["id"], "最近二")
-            archived_topic_id = make_topic(room_a["id"], "归档话题")
-            recent_b_id = make_topic(room_b["id"], "最近一")
-            hidden_room_topic_id = make_topic(archived_room["id"], "隐藏团队话题")
-
-            with store.write_transaction() as connection:
-                values = {
-                    pinned_id: (1, 100.0, 0),
-                    recent_a_id: (0, 300.0, 0),
-                    archived_topic_id: (1, 500.0, 1),
-                    recent_b_id: (0, 300.0, 0),
-                    hidden_room_topic_id: (1, 600.0, 0),
-                }
-                for topic_id, (pinned, updated_at, archived) in values.items():
-                    connection.execute(
-                        "UPDATE group_topics SET pinned = ?, updated_at = ?, archived = ? WHERE id = ?",
-                        (pinned, updated_at, archived, topic_id),
-                    )
-                connection.execute(
-                    "UPDATE group_rooms SET archived = 1 WHERE id = ?",
-                    (archived_room["id"],),
-                )
-
-            first = store.list_global_topics(limit=2, cursor=None)
-            second = store.list_global_topics(limit=2, cursor=first.next_cursor)
-            ordered_recent = sorted(
-                [recent_a_id, recent_b_id], reverse=True
-            )
-            self.assertEqual(
-                [item["id"] for item in first.items],
-                [pinned_id, ordered_recent[0]],
-            )
-            self.assertEqual(
-                [item["id"] for item in second.items],
-                [ordered_recent[1]],
-            )
-            self.assertIsNotNone(first.next_cursor)
-            self.assertIsNone(second.next_cursor)
-            self.assertNotIn(archived_topic_id, {
-                item["id"] for item in [*first.items, *second.items]
-            })
-            self.assertNotIn(hidden_room_topic_id, {
-                item["id"] for item in [*first.items, *second.items]
-            })
-            with self.assertRaisesRegex(ValueError, "cursor is malformed"):
-                store.list_global_topics(limit=2, cursor="not-a-valid-cursor")
-
-    def test_group_upload_persists_server_readable_attachment(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room(
-                {
-                    "requestId": new_id(),
-                    "name": "附件群",
-                    "cwd": "",
-                    "agents": [{"profile": "default"}],
-                }
-            )
-            [agent] = room["agents"]
-            room_id = room["id"]
-            result = asyncio.run(
-                group_plugin_api._persist_group_uploads(
-                    room_id,
-                    [
-                        UploadFile(
-                            filename="../photo.png",
-                            file=BytesIO(b"fixture-image"),
-                            headers=Headers({"content-type": "image/png"}),
-                        )
-                    ],
-                    root=Path(directory) / "uploads",
-                )
-            )
-
-            [uploaded] = result
-            path = Path(uploaded["path"])
-            self.assertEqual(
-                path.parent,
-                Path(directory).resolve() / "uploads" / room_id,
-            )
-            self.assertEqual(path.suffix, ".png")
-            self.assertEqual(path.read_bytes(), b"fixture-image")
-            self.assertEqual(path.stat().st_mode & 0o777, 0o600)
-            self.assertEqual(uploaded["name"], "photo.png")
-            self.assertEqual(uploaded["mimeType"], "image/png")
-            self.assertEqual(uploaded["size"], len(b"fixture-image"))
-
-            created = store.create_human_message(
-                room_id,
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=new_id(),
-                content=f"请查看图片\n\n![photo.png](<{path}>)",
-                mention_agent_ids=[agent["id"]],
-            )
-            [run] = created["runs"]
-            self.assertEqual(store.claim_next_runnable_run()["id"], run["id"])
-            projection = store.read_run_projection(run["id"])
-            prompt = ORCHESTRATOR.build_run_prompt(
-                projection,
-                store.get_room(room_id)["agents"],
-            )
-            self.assertIn(str(path), prompt)
-            self.assertTrue(path.is_file())
-
-    def test_group_upload_rejects_oversize_and_removes_partial_files(self) -> None:
-        room_id = new_id()
-        with (
-            tempfile.TemporaryDirectory() as directory,
-            patch.object(group_plugin_api, "_MAX_GROUP_UPLOAD_FILE_BYTES", 4),
-        ):
-            with self.assertRaises(group_plugin_api.GroupAPIError) as raised:
-                asyncio.run(
-                    group_plugin_api._persist_group_uploads(
-                        room_id,
-                        [
-                            UploadFile(
-                                filename="too-large.bin",
-                                file=BytesIO(b"12345"),
-                                headers=Headers(
-                                    {"content-type": "application/octet-stream"}
-                                ),
-                            )
-                        ],
-                        root=Path(directory),
-                    )
-                )
-
-            self.assertEqual(raised.exception.status_code, 413)
-            self.assertEqual(
-                [path for path in Path(directory).rglob("*") if path.is_file()],
-                [],
-            )
-
-    def test_room_settings_still_update_without_changing_agents(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "原房间",
-                "cwd": "",
-                "maxReplyRounds": 3,
-                "agents": [{"profile": "default", "description": "保留职责"}],
-            })
-            before_agent = room["agents"][0]
-            updated = store.update_room(
-                room["id"],
-                {
-                    "requestId": new_id(),
-                    "name": "新房间",
-                    "maxReplyRounds": 5,
-                },
-            )
-            self.assertEqual(updated["name"], "新房间")
-            self.assertEqual(updated["maxReplyRounds"], 5)
-            self.assertEqual(updated["agents"], [before_agent])
-
-    def test_topic_title_update_is_idempotent_and_emits_topic_event(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "话题群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            created = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=new_id(),
-                content="原始标题",
-                mention_agent_ids=[],
-            )
-            topic_id = created["message"]["topicId"]
-            request_id = new_id()
-            before = store.latest_cursor()
-
-            renamed = store.update_topic(
-                room["id"],
-                topic_id,
-                {"requestId": request_id, "title": "  新的\n话题标题  "},
-            )
-            repeated = store.update_topic(
-                room["id"],
-                topic_id,
-                {"requestId": request_id, "title": "  新的\n话题标题  "},
-            )
-
-            self.assertEqual(renamed["title"], "新的 话题标题")
-            self.assertEqual(repeated, renamed)
-            events = store.events_after(before, 10)
-            self.assertEqual(len(events), 1)
-            self.assertEqual(events[0]["eventType"], "topic.updated")
-            self.assertEqual(events[0]["payload"]["title"], "新的 话题标题")
-
-    def test_schema_v7_migrates_topic_read_position_without_data_loss(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            store = GroupStore(path)
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "迁移群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            created = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=new_id(),
-                content="保留消息",
-                mention_agent_ids=[],
-            )
-            topic_id = created["message"]["topicId"]
-            with store.connection() as connection:
-                original_message_count = connection.execute(
-                    "SELECT COUNT(*) FROM group_messages"
-                ).fetchone()[0]
-                original_latest_visible_seq = connection.execute(
-                    """SELECT COALESCE(MAX(seq), 0) FROM group_messages
-                    WHERE topic_id = ? AND visible = 1""",
-                    (topic_id,),
-                ).fetchone()[0]
-            with store.write_transaction() as connection:
-                columns = {
-                    row["name"]
-                    for row in connection.execute("PRAGMA table_info(group_topics)")
-                }
-                if "last_read_message_seq" in columns:
-                    connection.execute(
-                        "ALTER TABLE group_topics DROP COLUMN last_read_message_seq"
-                    )
-                connection.execute(
-                    "UPDATE group_meta SET value = '7' WHERE key = 'schema_version'"
-                )
-
-            migrated = GroupStore(path)
-            migrated.initialize()
-
-            self.assertEqual(migrated.schema_version(), 14)
-            with migrated.connection() as connection:
-                topic = connection.execute(
-                    "SELECT * FROM group_topics WHERE id = ?", (topic_id,)
-                ).fetchone()
-                message_count = connection.execute(
-                    "SELECT COUNT(*) FROM group_messages"
-                ).fetchone()[0]
-            self.assertEqual(
-                topic["last_read_message_seq"],
-                original_latest_visible_seq,
-            )
-            self.assertEqual(message_count, original_message_count)
-            self.assertEqual(migrated.room_activity(room["id"])["unreadCount"], 0)
-
-    def test_room_activity_counts_active_runs_and_unread_agent_messages(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "活动群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            agent = room["agents"][0]
-            topic_id = new_id()
-            created = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_id,
-                content="用户问题",
-                mention_agent_ids=[agent["id"]],
-            )
-            trigger = created["message"]
-            run = created["runs"][0]
-            with store.write_transaction() as connection:
-                connection.execute(
-                    "UPDATE group_agent_runs SET status = 'running' WHERE id = ?",
-                    (run["id"],),
-                )
-                visible_ids = [new_id(), new_id()]
-                for index, message_id in enumerate(visible_ids, start=2):
-                    connection.execute(
-                        """INSERT INTO group_messages
-                        (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                         root_message_id, content, status, visible, created_at, updated_at)
-                        VALUES (?, ?, ?, 'agent', ?, '夭夭', ?, ?, 'completed', 1, ?, ?)""",
-                        (
-                            message_id,
-                            room["id"],
-                            topic_id,
-                            agent["id"],
-                            trigger["rootMessageId"],
-                            f"回复 {index}",
-                            index,
-                            index,
-                        ),
-                    )
-                connection.execute(
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                     root_message_id, content, status, visible, created_at, updated_at)
-                    VALUES (?, ?, ?, 'agent', ?, '夭夭', ?, '隐藏', 'completed', 0, 4, 4)""",
-                    (
-                        new_id(), room["id"], topic_id, agent["id"],
-                        trigger["rootMessageId"],
-                    ),
-                )
-
-            activity = store.room_activity(room["id"])
-
-            self.assertEqual(activity["activeRunCount"], 1)
-            self.assertEqual(activity["unreadCount"], 2)
-            self.assertEqual(activity["lastMessage"]["id"], visible_ids[-1])
-
-    def test_mark_topic_read_is_monotonic_idempotent_and_emits_activity(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "已读群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            agent = room["agents"][0]
-            topic_id = new_id()
-            trigger = store.create_human_message(
-                room["id"], request_id=new_id(), client_message_id=new_id(),
-                topic_id=topic_id, content="问题", mention_agent_ids=[],
-            )["message"]
-            with store.write_transaction() as connection:
-                connection.execute(
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                     root_message_id, content, status, visible, created_at, updated_at)
-                    VALUES (?, ?, ?, 'agent', ?, '夭夭', ?, '回复', 'completed', 1, 2, 2)""",
-                    (
-                        new_id(), room["id"], topic_id, agent["id"],
-                        trigger["rootMessageId"],
-                    ),
-                )
-                through_seq = connection.execute(
-                    "SELECT MAX(seq) FROM group_messages WHERE topic_id = ?",
-                    (topic_id,),
-                ).fetchone()[0]
-            request_id = new_id()
-            before = store.latest_cursor()
-
-            first = store.mark_topic_read(
-                room["id"], topic_id,
-                {"requestId": request_id, "throughSeq": through_seq},
-            )
-            repeated = store.mark_topic_read(
-                room["id"], topic_id,
-                {"requestId": request_id, "throughSeq": through_seq},
-            )
-            stale = store.mark_topic_read(
-                room["id"], topic_id,
-                {"requestId": new_id(), "throughSeq": through_seq - 1},
-            )
-
-            self.assertEqual(first, repeated)
-            self.assertEqual(first["topic"]["lastReadMessageSeq"], through_seq)
-            self.assertEqual(stale["room"]["unreadCount"], 0)
-            events = store.events_after(before, 10)
-            self.assertEqual(
-                [event["eventType"] for event in events],
-                ["topic.updated", "room.activity"],
-            )
-            with self.assertRaises(ValueError):
-                store.mark_topic_read(
-                    room["id"], topic_id,
-                    {"requestId": new_id(), "throughSeq": through_seq + 100},
-                )
-
-    def test_topics_page_filter_compatibility_and_event_order(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "话题群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            topic_a, topic_b = new_id(), new_id()
-            with self.assertRaises(STORE_MODULE.GroupNotFoundError):
-                store.list_messages(room["id"], topic_id=new_id())
-            before = store.latest_cursor()
-            first = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_a,
-                content="第一个话题",
-                mention_agent_ids=[],
-            )
-            events = store.events_after(before, 10)
-            self.assertEqual(
-                [event["eventType"] for event in events],
-                [
-                    "message.upsert",
-                    "topic.updated",
-                    "room.activity",
-                    "message.upsert",
-                    "topic.updated",
-                    "run.updated",
-                    "room.activity",
-                ],
-            )
-            self.assertEqual(events[0]["payload"]["topicId"], topic_a)
-            self.assertEqual(
-                set(events[1]["payload"]),
-                {
-                    "id",
-                    "roomId",
-                    "title",
-                    "preview",
-                    "messageCount",
-                    "unreadCount",
-                    "latestMessageSeq",
-                    "lastReadMessageSeq",
-                    "archived",
-                    "pinned",
-                    "createdAt",
-                    "updatedAt",
-                },
-            )
-            self.assertEqual(events[1]["payload"]["id"], topic_a)
-            self.assertEqual(events[2]["payload"]["roomId"], room["id"])
-            self.assertEqual(events[2]["payload"]["activeRunCount"], 0)
-            self.assertEqual(events[-1]["payload"]["activeRunCount"], 1)
-
-            second = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_a,
-                content="第一个话题的后续",
-                mention_agent_ids=[],
-            )
-            store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_b,
-                content="第二个话题",
-                mention_agent_ids=[],
-            )
-            compatibility_first = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                content="旧客户端消息",
-                mention_agent_ids=[],
-            )
-            compatibility_second = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                content="旧客户端继续",
-                mention_agent_ids=[],
-            )
-            self.assertEqual(
-                compatibility_first["message"]["topicId"],
-                compatibility_second["message"]["topicId"],
-            )
-            self.assertEqual(
-                compatibility_first["message"]["topicId"],
-                store._compatibility_topic_id(room["id"]),
-            )
-
-            topic_a_messages = store.list_messages(room["id"], topic_id=topic_a)
-            self.assertEqual(
-                [
-                    message["id"]
-                    for message in topic_a_messages
-                    if message["senderKind"] == "human"
-                ],
-                [first["message"]["id"], second["message"]["id"]],
-            )
-            self.assertEqual(
-                sum(
-                    message["senderKind"] == "human"
-                    for message in store.list_messages(room["id"])
-                ),
-                5,
-            )
-            page_one = store.list_topics(room["id"], limit=2, cursor=None)
-            page_two = store.list_topics(
-                room["id"], limit=2, cursor=page_one.next_cursor
-            )
-            self.assertIsNotNone(page_one.next_cursor)
-            summaries = [*page_one.items, *page_two.items]
-            self.assertEqual(len(summaries), 3)
-            summary_a = next(item for item in summaries if item["id"] == topic_a)
-            self.assertEqual(summary_a["title"], "第一个话题")
-            self.assertEqual(summary_a["preview"], "第一个话题的后续")
-            self.assertEqual(summary_a["messageCount"], 4)
-
-            other_room = store.create_room({
-                "requestId": new_id(),
-                "name": "另一个群",
-                "cwd": "",
-                "agents": [{"profile": "other"}],
-            })
-            with self.assertRaisesRegex(ValueError, "does not belong to room"):
-                store.list_topics(
-                    other_room["id"], limit=2, cursor=page_one.next_cursor
-                )
-            with self.assertRaises(STORE_MODULE.GroupConflictError):
-                store.create_human_message(
-                    other_room["id"],
-                    request_id=new_id(),
-                    client_message_id=new_id(),
-                    topic_id=topic_a,
-                    content="错误归属",
-                    mention_agent_ids=[],
-                )
-
-    def test_topic_context_watermarks_room_session_and_rotation(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "上下文群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            [agent] = room["agents"]
-            topic_a, topic_b = new_id(), new_id()
-
-            run_a = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_a,
-                content="A-1",
-                mention_agent_ids=[agent["id"]],
-            )["runs"][0]
-            self.assertEqual(store.claim_next_runnable_run()["id"], run_a["id"])
-            projection_a = store.read_run_projection(run_a["id"])
-            self.assertEqual(
-                [message["content"] for message in projection_a["messages"]], ["A-1"]
-            )
-            prompt_a = ORCHESTRATOR.build_run_prompt(
-                projection_a, store.get_room(room["id"])["agents"]
-            )
-            envelope_a = json.loads(prompt_a.rsplit("GROUP_CONTEXT_JSON=", 1)[1])
-            self.assertEqual(envelope_a["run"]["topicId"], topic_a)
-            self._submit_and_settle(
-                store, projection_a, runtime="runtime-a", stored="stored-room"
-            )
-
-            run_b = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_b,
-                content="B-1",
-                mention_agent_ids=[agent["id"]],
-            )["runs"][0]
-            self.assertEqual(store.claim_next_runnable_run()["id"], run_b["id"])
-            projection_b = store.read_run_projection(run_b["id"])
-            self.assertFalse(projection_b["initial"])
-            self.assertEqual(projection_b["agent"]["storedSessionId"], "stored-room")
-            self.assertEqual(
-                [message["content"] for message in projection_b["messages"]], ["B-1"]
-            )
-            prompt_b = ORCHESTRATOR.build_run_prompt(
-                projection_b, store.get_room(room["id"])["agents"]
-            )
-            envelope_b = json.loads(prompt_b.rsplit("GROUP_CONTEXT_JSON=", 1)[1])
-            self.assertEqual(envelope_b["run"]["topicId"], topic_b)
-            self.assertNotEqual(
-                envelope_a["run"]["topicId"], envelope_b["run"]["topicId"]
-            )
-            self._submit_and_settle(
-                store, projection_b, runtime="runtime-b", stored="stored-room"
-            )
-
-            run_a2 = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_a,
-                content="A-2",
-                mention_agent_ids=[agent["id"]],
-            )["runs"][0]
-            self.assertEqual(store.claim_next_runnable_run()["id"], run_a2["id"])
-            incremental = store.read_run_projection(run_a2["id"])
-            self.assertEqual(
-                [message["content"] for message in incremental["messages"]], ["A-2"]
-            )
-            self.assertTrue(
-                store.prepare_run_session_configuration(
-                    run_a2["id"],
-                    {
-                        "model": None,
-                        "provider": None,
-                        "reasoning_effort": None,
-                        "fast": None,
-                    },
-                )
-            )
-            rebuilt = store.read_run_projection(run_a2["id"])
-            self.assertTrue(rebuilt["initial"])
-            rebuilt_contents = [message["content"] for message in rebuilt["messages"]]
-            self.assertEqual(rebuilt_contents, ["A-1", "A-2"])
-            self.assertNotIn("B-1", rebuilt_contents)
-            with store.connection() as connection:
-                watermarks = connection.execute(
-                    """SELECT topic_id, last_context_message_seq
-                    FROM group_agent_topic_state WHERE agent_id = ?""",
-                    (agent["id"],),
-                ).fetchall()
-            self.assertEqual(
-                {
-                    row["topic_id"]: row["last_context_message_seq"]
-                    for row in watermarks
-                },
-                {topic_a: 0, topic_b: 0},
-            )
-
-    def test_cross_topic_runs_interactions_and_cascades_keep_topic(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "并发群",
-                "cwd": "",
-                "agents": [
-                    {"profile": "one", "displayName": "一号"},
-                    {"profile": "two", "displayName": "二号"},
-                ],
-            })
-            first_agent, second_agent = room["agents"]
-            topic_a, topic_b = new_id(), new_id()
-            first_run = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_a,
-                content="请一号回复",
-                mention_agent_ids=[first_agent["id"]],
-            )["runs"][0]
-            second_run = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_b,
-                content="请二号回复",
-                mention_agent_ids=[second_agent["id"]],
-            )["runs"][0]
-            claimed = {
-                store.claim_next_runnable_run()["id"],
-                store.claim_next_runnable_run()["id"],
-            }
-            self.assertEqual(claimed, {first_run["id"], second_run["id"]})
-            interaction = store.create_interaction(
-                "approval-topic-test",
-                first_run["id"],
-                kind="approval",
-                payload={"tool": "test"},
-            )
-            self.assertEqual(interaction["topicId"], topic_a)
-
-            store.transition_run(first_run["id"], "running")
-            store.upsert_agent_message(
-                first_run["id"],
-                content="@二号 继续",
-                reasoning="",
-                tool_state=[],
-                status="completed",
-            )
-            store.transition_run(first_run["id"], "completed")
-            cascade = store.enqueue_cascade_runs(
-                first_run["id"], agent_ids=[second_agent["id"]], warnings=[]
-            )
-            [cascade_run] = cascade["runs"]
-            self.assertEqual(cascade_run["topicId"], topic_a)
-
-    def test_v2_stored_default_session_preserves_session_and_watermark(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            room_id, agent_id, topic_id = self._create_legacy_database(
-                path, version=2, stored_session_id="stored-v2"
-            )
-            store = GroupStore(path)
-            store.initialize()
-            with store.connection() as connection:
-                agent = connection.execute(
-                    "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
-                ).fetchone()
-            self.assertEqual(
-                agent["session_config_json"],
-                '{"fast":null,"model":null,"provider":null,"reasoning_effort":null}',
-            )
-            run = self._claim_legacy_topic_continuation(
-                store, room_id, agent_id, topic_id
-            )
-            self.assertFalse(
-                store.prepare_run_session_configuration(
-                    run["id"], self._default_session_configuration()
-                )
-            )
-            with store.connection() as connection:
-                refreshed = connection.execute(
-                    "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
-                ).fetchone()
-                state = connection.execute(
-                    """SELECT * FROM group_agent_topic_state
-                    WHERE agent_id = ? AND topic_id = ?""",
-                    (agent_id, topic_id),
-                ).fetchone()
-            self.assertEqual(refreshed["stored_session_id"], "stored-v2")
-            self.assertEqual(state["last_context_message_seq"], 1)
-
-    def test_v2_without_stored_session_rotates_default_generation(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            room_id, agent_id, topic_id = self._create_legacy_database(
-                path, version=2, stored_session_id=None
-            )
-            store = GroupStore(path)
-            store.initialize()
-            with store.connection() as connection:
-                agent = connection.execute(
-                    "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
-                ).fetchone()
-            self.assertIsNone(agent["session_config_json"])
-            run = self._claim_legacy_topic_continuation(
-                store, room_id, agent_id, topic_id
-            )
-            self.assertTrue(
-                store.prepare_run_session_configuration(
-                    run["id"], self._default_session_configuration()
-                )
-            )
-            with store.connection() as connection:
-                state = connection.execute(
-                    """SELECT * FROM group_agent_topic_state
-                    WHERE agent_id = ? AND topic_id = ?""",
-                    (agent_id, topic_id),
-                ).fetchone()
-            self.assertEqual(state["last_context_message_seq"], 0)
-
-    def test_v3_dirty_null_session_configuration_still_rotates(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            room_id, agent_id, topic_id = self._create_legacy_database(
-                path, version=3, stored_session_id="stored-dirty-v3"
-            )
-            store = GroupStore(path)
-            store.initialize()
-            with store.connection() as connection:
-                agent = connection.execute(
-                    "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
-                ).fetchone()
-            self.assertIsNone(agent["session_config_json"])
-            run = self._claim_legacy_topic_continuation(
-                store, room_id, agent_id, topic_id
-            )
-            self.assertTrue(
-                store.prepare_run_session_configuration(
-                    run["id"], self._default_session_configuration()
-                )
-            )
-            self.assertIsNone(store.get_room(room_id)["agents"][0]["storedSessionId"])
-
-    def test_legacy_agent_status_and_failed_interaction_replay_shapes(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "兼容群",
-                "cwd": "",
-                "agents": [{"profile": "default"}],
-            })
-            [agent] = room["agents"]
-            topic_id = new_id()
-            run = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_id,
-                content="需要审批",
-                mention_agent_ids=[agent["id"]],
-            )["runs"][0]
-            claimed = store.claim_next_runnable_run()
-            self.assertEqual(claimed["id"], run["id"])
-            status_events = [
-                event
-                for event in store.events_after(0, 100)
-                if event["eventType"] == "agent.status"
-            ]
-            self.assertTrue(status_events)
-            self.assertEqual(
-                set(status_events[-1]["payload"]),
-                {"roomId", "agentId", "status", "runId"},
-            )
-            store.bind_run_runtime(run["id"], "runtime-legacy-shape")
-            interaction = store.create_interaction(
-                "approval-legacy-shape",
-                run["id"],
-                kind="approval",
-                payload={"choices": ["once"]},
-            )
-            response_request = new_id()
-            response = {"choice": "once", "permanent": False}
-            store.begin_interaction_response(
-                room["id"],
-                interaction["id"],
-                request_id=response_request,
-                kind="approval",
-                response=response,
-            )
-            failed = store.fail_interaction_response(
-                response_request,
-                reason="Gateway outcome unknown",
-                uncertain=True,
-            )
-            self.assertNotIn("topicId", failed["run"])
-            self.assertEqual(
-                set(failed["run"]),
-                {
-                    "id",
-                    "roomId",
-                    "agentId",
-                    "triggerMessageId",
-                    "responseMessageId",
-                    "rootMessageId",
-                    "depth",
-                    "replyMode",
-                    "status",
-                    "runtimeSessionId",
-                    "error",
-                    "createdAt",
-                    "updatedAt",
-                },
-            )
-            replay = store.begin_interaction_response(
-                room["id"],
-                interaction["id"],
-                request_id=response_request,
-                kind="approval",
-                response=response,
-            )
-            self.assertEqual(replay, failed)
-            run_events = [
-                event
-                for event in store.events_after(0, 200)
-                if event["eventType"] == "run.updated"
-            ]
-            self.assertEqual(run_events[-1]["payload"]["topicId"], topic_id)
-
-    def test_composite_topic_foreign_keys_reject_cross_room_rows(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            store = GroupStore(Path(directory) / "group.db")
-            store.initialize()
-            first_room = store.create_room({
-                "requestId": new_id(),
-                "name": "房间一",
-                "cwd": "",
-                "agents": [{"profile": "one"}],
-            })
-            second_room = store.create_room({
-                "requestId": new_id(),
-                "name": "房间二",
-                "cwd": "",
-                "agents": [{"profile": "two"}],
-            })
-            topic_id = new_id()
-            first_message = store.create_human_message(
-                first_room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=topic_id,
-                content="归属房间一",
-                mention_agent_ids=[],
-            )["message"]
-            [second_agent] = second_room["agents"]
-            invalid_statements = (
-                (
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                     root_message_id, reply_to_message_id, client_message_id,
-                     content, reasoning, tool_state_json, status, error, visible,
-                     created_at, updated_at)
-                    VALUES (?, ?, ?, 'human', 'human', '你', ?, NULL, ?, '错误',
-                            '', '[]', 'completed', '', 1, 1, 1)""",
-                    (
-                        new_id(),
-                        second_room["id"],
-                        topic_id,
-                        new_id(),
-                        new_id(),
-                    ),
-                ),
-                (
-                    """INSERT INTO group_agent_runs
-                    (id, room_id, topic_id, agent_id, trigger_message_id,
-                     response_message_id, root_message_id, depth, reply_mode,
-                     status, runtime_session_id, error, created_at, updated_at)
-                    VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'mentioned', 'completed',
-                            NULL, '', 1, 1)""",
-                    (
-                        new_id(),
-                        second_room["id"],
-                        topic_id,
-                        second_agent["id"],
-                        first_message["id"],
-                        first_message["id"],
-                        first_message["rootMessageId"],
-                    ),
-                ),
-                (
-                    """INSERT INTO group_interactions
-                    (id, room_id, topic_id, agent_id, run_id, kind, payload_json,
-                     status, created_at, resolved_at)
-                    VALUES (?, ?, ?, ?, ?, 'approval', '{}', 'pending', 1, NULL)""",
-                    (
-                        "cross-room-interaction",
-                        second_room["id"],
-                        topic_id,
-                        second_agent["id"],
-                        new_id(),
-                    ),
-                ),
-            )
-            for statement, parameters in invalid_statements:
-                with self.subTest(table=statement.split()[2]):
-                    with self.assertRaises(sqlite3.IntegrityError):
-                        with store.write_transaction() as connection:
-                            connection.execute(statement, parameters)
-
-    def test_v3_migration_topic_order_ignores_newer_hidden_messages(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            room_id, _agent_id, first_topic = self._create_legacy_database(
-                path, version=3, stored_session_id=None
-            )
-            second_topic, hidden_topic = new_id(), new_id()
-            connection = sqlite3.connect(path)
-            connection.execute(
-                """UPDATE group_messages
-                SET visible = 1, created_at = 1, updated_at = 10
-                WHERE root_message_id = ?""",
-                (first_topic,),
-            )
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
-                 reply_to_message_id, client_message_id, content, reasoning,
-                 tool_state_json, status, error, visible, created_at, updated_at)
-                VALUES (?, ?, 'agent', 'hidden', '隐藏', ?, NULL, NULL,
-                        '隐藏更新', '', '[]', 'completed', '', 0, 2, 100)""",
-                (new_id(), room_id, first_topic),
-            )
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
-                 reply_to_message_id, client_message_id, content, reasoning,
-                 tool_state_json, status, error, visible, created_at, updated_at)
-                VALUES (?, ?, 'human', 'human', '你', ?, NULL, ?,
-                        '第二可见话题', '', '[]', 'completed', '', 1, 3, 50)""",
-                (second_topic, room_id, second_topic, new_id()),
-            )
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
-                 reply_to_message_id, client_message_id, content, reasoning,
-                 tool_state_json, status, error, visible, created_at, updated_at)
-                VALUES (?, ?, 'agent', 'hidden', '隐藏', ?, NULL, NULL,
-                        '仅隐藏话题', '', '[]', 'completed', '', 0, 4, 75)""",
-                (hidden_topic, room_id, hidden_topic),
-            )
-            connection.commit()
-            connection.close()
-
-            store = GroupStore(path)
-            store.initialize()
-            topics = store.list_topics(room_id, limit=10, cursor=None).items
-            self.assertEqual(
-                [topic["id"] for topic in topics],
-                [hidden_topic, second_topic, first_topic],
-            )
-            self.assertEqual(
-                {topic["id"]: topic["updatedAt"] for topic in topics},
-                {hidden_topic: 75, second_topic: 50, first_topic: 10},
-            )
-
-    def test_v3_migration_rejects_orphan_run_messages_and_interactions(self) -> None:
-        for column in ("trigger_message_id", "response_message_id"):
-            with (
-                self.subTest(orphan=column),
-                tempfile.TemporaryDirectory() as directory,
-            ):
-                path = Path(directory) / "group.db"
-                self._create_legacy_database(path, version=3, stored_session_id=None)
-                connection = sqlite3.connect(path)
-                connection.execute(
-                    f"UPDATE group_agent_runs SET {column} = ?", (new_id(),)
-                )
-                connection.commit()
-                connection.close()
-                with self.assertRaisesRegex(
-                    STORE_MODULE.GroupStoreError, "run messages are orphaned"
-                ):
-                    GroupStore(path).initialize()
-                self._assert_legacy_schema_rolled_back(path)
-
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            room_id, agent_id, _topic_id = self._create_legacy_database(
-                path, version=3, stored_session_id=None
-            )
-            connection = sqlite3.connect(path)
-            connection.execute(
-                """INSERT INTO group_interactions
-                (id, room_id, agent_id, run_id, kind, payload_json, status,
-                 created_at, resolved_at)
-                VALUES ('orphan-interaction', ?, ?, ?, 'approval', '{}',
-                        'pending', 1, NULL)""",
-                (room_id, agent_id, new_id()),
-            )
-            connection.commit()
-            connection.close()
-            with self.assertRaisesRegex(
-                STORE_MODULE.GroupStoreError, "interaction run is orphaned"
-            ):
-                GroupStore(path).initialize()
-            self._assert_legacy_schema_rolled_back(path)
-
-    def test_v4_validation_rejects_missing_run_trigger_or_response(self) -> None:
-        for column in ("trigger_message_id", "response_message_id"):
-            with (
-                self.subTest(orphan=column),
-                tempfile.TemporaryDirectory() as directory,
-            ):
-                path = Path(directory) / "group.db"
-                store = GroupStore(path)
-                store.initialize()
-                room = store.create_room({
-                    "requestId": new_id(),
-                    "name": "损坏群",
-                    "cwd": "",
-                    "agents": [{"profile": "default"}],
-                })
-                [agent] = room["agents"]
-                topic_id = new_id()
-                message = store.create_human_message(
-                    room["id"],
-                    request_id=new_id(),
-                    client_message_id=new_id(),
-                    topic_id=topic_id,
-                    content="有效消息",
-                    mention_agent_ids=[],
-                )["message"]
-                trigger_id = (
-                    new_id() if column == "trigger_message_id" else message["id"]
-                )
-                response_id = (
-                    new_id() if column == "response_message_id" else message["id"]
-                )
-                with store.connection() as connection:
-                    connection.execute(
-                        """INSERT INTO group_agent_runs
-                        (id, room_id, topic_id, agent_id, trigger_message_id,
-                         response_message_id, root_message_id, depth, reply_mode,
-                         status, runtime_session_id, error, created_at, updated_at)
-                        VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'mentioned', 'completed',
-                                NULL, '', 1, 1)""",
-                        (
-                            new_id(),
-                            room["id"],
-                            topic_id,
-                            agent["id"],
-                            trigger_id,
-                            response_id,
-                            message["rootMessageId"],
-                        ),
-                    )
-                with self.assertRaisesRegex(
-                    STORE_MODULE.GroupStoreError, "stored values are corrupt"
-                ):
-                    GroupStore(path).initialize()
-
-    def test_early_v4_draft_repairs_losslessly_and_is_idempotent(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            store = GroupStore(path)
-            store.initialize()
-            room = store.create_room({
-                "requestId": new_id(),
-                "name": "早期 v4 群",
-                "cwd": "",
-                "agents": [{"profile": "default", "description": "保留设置"}],
-            })
-            [agent] = room["agents"]
-            visible_topic, hidden_topic = new_id(), new_id()
-            created = store.create_human_message(
-                room["id"],
-                request_id=new_id(),
-                client_message_id=new_id(),
-                topic_id=visible_topic,
-                content="可见话题",
-                mention_agent_ids=[agent["id"]],
-            )
-            [run] = created["runs"]
-            self.assertEqual(store.claim_next_runnable_run()["id"], run["id"])
-            store.bind_run_runtime(run["id"], "runtime-early-v4")
-            interaction = store.create_interaction(
-                "approval-early-v4",
-                run["id"],
-                kind="approval",
-                payload={"choices": ["once"]},
-            )
-            failed_request = new_id()
-            with store.write_transaction() as connection:
-                connection.execute(
-                    """UPDATE group_messages SET created_at = 1, updated_at = 10
-                    WHERE topic_id = ?""",
-                    (visible_topic,),
-                )
-                connection.execute(
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                     root_message_id, reply_to_message_id, client_message_id,
-                     content, reasoning, tool_state_json, status, error, visible,
-                     created_at, updated_at)
-                    VALUES (?, ?, ?, 'agent', ?, '隐藏', ?, NULL, NULL,
-                            '隐藏更新', '', '[]', 'completed', '', 0, 2, 100)""",
-                    (
-                        new_id(),
-                        room["id"],
-                        visible_topic,
-                        agent["id"],
-                        created["message"]["rootMessageId"],
-                    ),
-                )
-                store._ensure_topic(
-                    connection, room["id"], hidden_topic, "仅隐藏话题", 4
-                )
-                connection.execute(
-                    """INSERT INTO group_messages
-                    (id, room_id, topic_id, sender_kind, sender_id, sender_name,
-                     root_message_id, reply_to_message_id, client_message_id,
-                     content, reasoning, tool_state_json, status, error, visible,
-                     created_at, updated_at)
-                    VALUES (?, ?, ?, 'agent', ?, '隐藏', ?, NULL, NULL,
-                            '仅隐藏消息', '', '[]', 'completed', '', 0, 4, 75)""",
-                    (hidden_topic, room["id"], hidden_topic, agent["id"], hidden_topic),
-                )
-                connection.execute("UPDATE group_topics SET updated_at = 999")
-                status_events = connection.execute(
-                    """SELECT cursor, payload_json FROM group_events
-                    WHERE event_type = 'agent.status'"""
-                ).fetchall()
-                for event in status_events:
-                    payload = json.loads(event["payload_json"])
-                    payload["topicId"] = visible_topic
-                    connection.execute(
-                        "UPDATE group_events SET payload_json = ? WHERE cursor = ?",
-                        (GroupStore._canonical_json(payload), event["cursor"]),
-                    )
-                failed_run = store._run_wire(store._run_row(connection, run["id"]))
-                connection.execute(
-                    """INSERT INTO group_idempotency
-                    (request_id, operation, request_hash, response_json, created_at)
-                    VALUES (?, ?, 'early-v4-failed-hash', ?, 5)""",
-                    (
-                        failed_request,
-                        f"interaction.approval.response:{interaction['id']}",
-                        GroupStore._canonical_json({
-                            "state": "failed",
-                            "reason": "early failure",
-                            "runtimeSessionIds": ["runtime-early-v4"],
-                            "run": failed_run,
-                        }),
-                    ),
-                )
-
-            with store.connection() as connection:
-                expected_room = dict(
-                    connection.execute(
-                        "SELECT * FROM group_rooms WHERE id = ?", (room["id"],)
-                    ).fetchone()
-                )
-                expected_agent = dict(
-                    connection.execute(
-                        "SELECT * FROM group_agents WHERE id = ?", (agent["id"],)
-                    ).fetchone()
-                )
-                expected_counts = {
-                    table: connection.execute(
-                        f"SELECT COUNT(*) FROM {table}"
-                    ).fetchone()[0]
-                    for table in (
-                        "group_messages",
-                        "group_agent_runs",
-                        "group_interactions",
-                        "group_topics",
-                        "group_agent_topic_state",
-                    )
-                }
-                expected_states = [
-                    tuple(row)
-                    for row in connection.execute(
-                        """SELECT * FROM group_agent_topic_state
-                        ORDER BY agent_id, topic_id"""
-                    )
-                ]
-                self._downgrade_to_early_v4(connection)
-                self.assertEqual(
-                    {
-                        table: GroupStore._topic_foreign_key_kind(connection, table)
-                        for table in (
-                            "group_messages",
-                            "group_agent_runs",
-                            "group_interactions",
-                        )
-                    },
-                    {
-                        "group_messages": "early",
-                        "group_agent_runs": "early",
-                        "group_interactions": "early",
-                    },
-                )
-
-            repaired = GroupStore(path)
-            repaired.initialize()
-            with repaired.connection() as connection:
-                self.assertEqual(
-                    {
-                        table: GroupStore._topic_foreign_key_kind(connection, table)
-                        for table in (
-                            "group_messages",
-                            "group_agent_runs",
-                            "group_interactions",
-                        )
-                    },
-                    {
-                        "group_messages": "final",
-                        "group_agent_runs": "final",
-                        "group_interactions": "final",
-                    },
-                )
-                self.assertEqual(
-                    dict(
-                        connection.execute(
-                            "SELECT * FROM group_rooms WHERE id = ?", (room["id"],)
-                        ).fetchone()
-                    ),
-                    expected_room,
-                )
-                self.assertEqual(
-                    dict(
-                        connection.execute(
-                            "SELECT * FROM group_agents WHERE id = ?", (agent["id"],)
-                        ).fetchone()
-                    ),
-                    expected_agent,
-                )
-                actual_counts = {
-                    table: connection.execute(
-                        f"SELECT COUNT(*) FROM {table}"
-                    ).fetchone()[0]
-                    for table in expected_counts
-                }
-                self.assertEqual(actual_counts, expected_counts)
-                max_message_seq = connection.execute(
-                    "SELECT MAX(seq) FROM group_messages"
-                ).fetchone()[0]
-                message_sequence = connection.execute(
-                    "SELECT seq FROM sqlite_sequence WHERE name = 'group_messages'"
-                ).fetchone()[0]
-                self.assertEqual(message_sequence, max_message_seq)
-                self.assertEqual(
-                    [
-                        tuple(row)
-                        for row in connection.execute(
-                            """SELECT * FROM group_agent_topic_state
-                            ORDER BY agent_id, topic_id"""
-                        )
-                    ],
-                    expected_states,
-                )
-                topics = {
-                    row["id"]: dict(row)
-                    for row in connection.execute(
-                        "SELECT * FROM group_topics ORDER BY id"
-                    )
-                }
-                self.assertEqual(topics[visible_topic]["updated_at"], 10)
-                self.assertEqual(topics[hidden_topic]["updated_at"], 75)
-                for event in connection.execute(
-                    """SELECT payload_json FROM group_events
-                    WHERE event_type = 'agent.status'"""
-                ):
-                    self.assertNotIn("topicId", json.loads(event["payload_json"]))
-                failed = json.loads(
-                    connection.execute(
-                        """SELECT response_json FROM group_idempotency
-                        WHERE request_id = ?""",
-                        (failed_request,),
-                    ).fetchone()[0]
-                )
-                self.assertNotIn("topicId", failed["run"])
-                first_snapshot = self._repair_snapshot(connection)
-
-            repaired.initialize()
-            with repaired.connection() as connection:
-                self.assertEqual(self._repair_snapshot(connection), first_snapshot)
-
-    def test_v3_migration_preserves_room_agent_and_rewrites_topic_wires(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            SETTINGS_TESTS.GroupSettingsContractTests._create_v1_database(path)
-            connection = sqlite3.connect(path)
-            connection.row_factory = sqlite3.Row
-            GroupStore._migrate_v1_to_v2(connection)
-            GroupStore._migrate_v2_to_v3(connection)
-            room_id = connection.execute("SELECT id FROM group_rooms").fetchone()[0]
-            agent_id = connection.execute("SELECT id FROM group_agents").fetchone()[0]
-            first_message = connection.execute(
-                "SELECT * FROM group_messages ORDER BY seq LIMIT 1"
-            ).fetchone()
-            connection.execute(
-                """UPDATE group_rooms SET name = '保留群', max_reply_rounds = 7,
-                archived = 1 WHERE id = ?""",
-                (room_id,),
-            )
-            connection.execute(
-                """UPDATE group_agents
-                SET display_name = '保留名', display_name_key = '保留名',
-                    description = '保留职责', stored_session_id = 'stored-old',
-                    last_context_message_seq = 2, enabled = 0,
-                    reply_without_mention = 1, model_override = 'model-old',
-                    provider_override = 'provider-old',
-                    reasoning_effort_override = 'high', fast_mode_override = 1,
-                    session_config_json = '{"fast":true}'
-                WHERE id = ?""",
-                (agent_id,),
-            )
-            expected_room = dict(
-                connection.execute(
-                    "SELECT * FROM group_rooms WHERE id = ?", (room_id,)
-                ).fetchone()
-            )
-            expected_agent = dict(
-                connection.execute(
-                    "SELECT * FROM group_agents WHERE id = ?", (agent_id,)
-                ).fetchone()
-            )
-            second_message, second_run = new_id(), new_id()
-            connection.execute(
-                """INSERT INTO group_messages
-                (id, room_id, sender_kind, sender_id, sender_name, root_message_id,
-                 reply_to_message_id, client_message_id, content, reasoning,
-                 tool_state_json, status, error, visible, created_at, updated_at)
-                VALUES (?, ?, 'human', 'human', '你', ?, NULL, ?, '第二话题', '',
-                        '[]', 'completed', '', 1, 2, 2)""",
-                (second_message, room_id, second_message, new_id()),
-            )
-            connection.execute(
-                """INSERT INTO group_agent_runs
-                (id, room_id, agent_id, trigger_message_id, response_message_id,
-                 root_message_id, depth, reply_mode, status, runtime_session_id,
-                 error, created_at, updated_at)
-                VALUES (?, ?, ?, ?, ?, ?, 0, 'mentioned', 'running',
-                        'runtime-old', '', 2, 2)""",
-                (
-                    second_run,
-                    room_id,
-                    agent_id,
-                    second_message,
-                    second_message,
-                    second_message,
-                ),
-            )
-            connection.execute(
-                """INSERT INTO group_interactions
-                (id, room_id, agent_id, run_id, kind, payload_json, status,
-                 created_at, resolved_at)
-                VALUES ('legacy-interaction', ?, ?, ?, 'approval', '{}',
-                        'pending', 2, NULL)""",
-                (room_id, agent_id, second_run),
-            )
-            failed_interaction_request = new_id()
-            connection.execute(
-                """INSERT INTO group_idempotency
-                (request_id, operation, request_hash, response_json, created_at)
-                VALUES (?, 'interaction.approval.response:legacy-interaction',
-                        'legacy-failed-hash', ?, 2)""",
-                (
-                    failed_interaction_request,
-                    GroupStore._canonical_json({
-                        "state": "failed",
-                        "reason": "legacy failure",
-                        "runtimeSessionIds": [],
-                        "run": {
-                            "id": second_run,
-                            "triggerMessageId": second_message,
-                        },
-                    }),
-                ),
-            )
-            replay_request = new_id()
-            old_payload = {
-                "roomId": room_id,
-                "clientMessageId": first_message["client_message_id"],
-                "content": first_message["content"],
-                "mentionAgentIds": [],
-            }
-            old_response = {
-                "message": {"id": first_message["id"], "senderKind": "human"},
-                "runs": [],
-            }
-            connection.execute(
-                """INSERT INTO group_idempotency
-                (request_id, operation, request_hash, response_json, created_at)
-                VALUES (?, 'message.create', ?, ?, 1)""",
-                (
-                    replay_request,
-                    hashlib.sha256(
-                        GroupStore._canonical_json(old_payload).encode()
-                    ).hexdigest(),
-                    GroupStore._canonical_json(old_response),
-                ),
-            )
-            connection.execute(
-                """INSERT INTO group_events
-                (epoch, room_id, event_type, payload_json, created_at)
-                VALUES ('11111111-1111-4111-8111-111111111111', ?,
-                        'message.upsert', ?, 1)""",
-                (room_id, GroupStore._canonical_json(old_response["message"])),
-            )
-            connection.execute(
-                """INSERT INTO group_events
-                (epoch, room_id, event_type, payload_json, created_at)
-                VALUES ('11111111-1111-4111-8111-111111111111', ?,
-                        'run.updated', ?, 2)""",
-                (
-                    room_id,
-                    GroupStore._canonical_json({
-                        "id": second_run,
-                        "triggerMessageId": second_message,
-                    }),
-                ),
-            )
-            connection.execute(
-                """INSERT INTO group_events
-                (epoch, room_id, event_type, payload_json, created_at)
-                VALUES ('11111111-1111-4111-8111-111111111111', ?,
-                        'interaction.requested', ?, 2)""",
-                (
-                    room_id,
-                    GroupStore._canonical_json({
-                        "id": "legacy-interaction",
-                        "runId": second_run,
-                        "kind": "approval",
-                    }),
-                ),
-            )
-            connection.commit()
-            connection.close()
-
-            store = GroupStore(path)
-            store.initialize()
-            self.assertEqual(store.schema_version(), 14)
-            with store.connection() as migrated:
-                room = migrated.execute("SELECT * FROM group_rooms").fetchone()
-                agent = migrated.execute("SELECT * FROM group_agents").fetchone()
-                topics = migrated.execute(
-                    "SELECT * FROM group_topics ORDER BY created_at, id"
-                ).fetchall()
-                states = migrated.execute(
-                    """SELECT * FROM group_agent_topic_state
-                    WHERE agent_id = ? ORDER BY topic_id""",
-                    (agent_id,),
-                ).fetchall()
-                interaction = migrated.execute(
-                    "SELECT * FROM group_interactions WHERE id = 'legacy-interaction'"
-                ).fetchone()
-                active_run = migrated.execute(
-                    "SELECT * FROM group_agent_runs WHERE id = ?", (second_run,)
-                ).fetchone()
-                failed_interaction_replay = json.loads(
-                    migrated.execute(
-                        """SELECT response_json FROM group_idempotency
-                        WHERE request_id = ?""",
-                        (failed_interaction_request,),
-                    ).fetchone()[0]
-                )
-            self.assertEqual(
-                dict(room), {
-                    **expected_room,
-                    "orchestration_mode": "free",
-                    "instructions": "",
-                    "avatar_data_url": "",
-                }
-            )
-            self.assertEqual(
-                dict(agent),
-                {
-                    **expected_agent,
-                    "is_host": 1,
-                    "node_id": "local",
-                    "node_label": "",
-                    "execution_profile": None,
-                },
-            )
-            self.assertEqual(
-                (room["name"], room["max_reply_rounds"], room["archived"]),
-                ("保留群", 7, 1),
-            )
-            self.assertEqual(
-                (
-                    agent["profile"],
-                    agent["display_name"],
-                    agent["description"],
-                    agent["stored_session_id"],
-                    agent["last_context_message_seq"],
-                    agent["enabled"],
-                    agent["reply_without_mention"],
-                    agent["model_override"],
-                    agent["provider_override"],
-                    agent["reasoning_effort_override"],
-                    agent["fast_mode_override"],
-                    agent["session_config_json"],
-                ),
-                (
-                    "default",
-                    "保留名",
-                    "保留职责",
-                    "stored-old",
-                    2,
-                    0,
-                    1,
-                    "model-old",
-                    "provider-old",
-                    "high",
-                    1,
-                    '{"fast":true}',
-                ),
-            )
-            self.assertEqual(
-                {topic["id"] for topic in topics},
-                {first_message["root_message_id"], second_message},
-            )
-            self.assertEqual(
-                {
-                    state["topic_id"]: state["last_context_message_seq"]
-                    for state in states
-                },
-                {first_message["root_message_id"]: 1, second_message: 2},
-            )
-            self.assertEqual(interaction["topic_id"], second_message)
-            self.assertEqual(active_run["topic_id"], second_message)
-            self.assertEqual(active_run["runtime_session_id"], "runtime-old")
-            self.assertNotIn("topicId", failed_interaction_replay["run"])
-            replay = store.create_human_message(
-                room_id,
-                request_id=replay_request,
-                client_message_id=first_message["client_message_id"],
-                content=first_message["content"],
-                mention_agent_ids=[],
-            )
-            self.assertEqual(
-                replay["message"]["topicId"], first_message["root_message_id"]
-            )
-            historical_events = store.events_after(0, 3)
-            self.assertEqual(
-                [event["payload"]["topicId"] for event in historical_events],
-                [
-                    first_message["root_message_id"],
-                    second_message,
-                    second_message,
-                ],
-            )
-
-    def test_v3_migration_rolls_back_atomically_on_invalid_topic_identity(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            path = Path(directory) / "group.db"
-            SETTINGS_TESTS.GroupSettingsContractTests._create_v1_database(path)
-            connection = sqlite3.connect(path)
-            connection.row_factory = sqlite3.Row
-            GroupStore._migrate_v1_to_v2(connection)
-            GroupStore._migrate_v2_to_v3(connection)
-            connection.execute(
-                "UPDATE group_messages SET root_message_id = 'invalid-topic'"
-            )
-            connection.execute(
-                "UPDATE group_agent_runs SET root_message_id = 'invalid-topic'"
-            )
-            connection.commit()
-            connection.close()
-
-            with self.assertRaises(STORE_MODULE.GroupStoreError):
-                GroupStore(path).initialize()
-            verification = sqlite3.connect(path)
-            version = verification.execute(
-                "SELECT value FROM group_meta WHERE key = 'schema_version'"
-            ).fetchone()[0]
-            tables = {
-                row[0]
-                for row in verification.execute(
-                    """SELECT name FROM sqlite_master
-                    WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
-                )
-            }
-            verification.close()
-            self.assertEqual(version, "3")
-            self.assertNotIn("group_topics", tables)
-            self.assertNotIn("group_agent_topic_state", tables)
-
-    @staticmethod
-    def _downgrade_to_early_v4(connection: sqlite3.Connection) -> None:
-        connection.execute(
-            """CREATE TABLE group_messages_early_fixture (
-                seq INTEGER PRIMARY KEY AUTOINCREMENT,
-                id TEXT NOT NULL UNIQUE,
-                room_id TEXT NOT NULL REFERENCES group_rooms(id) ON DELETE CASCADE,
-                topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
-                sender_kind TEXT NOT NULL,
-                sender_id TEXT NOT NULL,
-                sender_name TEXT NOT NULL,
-                root_message_id TEXT NOT NULL,
-                reply_to_message_id TEXT,
-                client_message_id TEXT UNIQUE,
-                content TEXT NOT NULL DEFAULT '',
-                reasoning TEXT NOT NULL DEFAULT '',
-                tool_state_json TEXT NOT NULL DEFAULT '[]',
-                status TEXT NOT NULL,
-                error TEXT NOT NULL DEFAULT '',
-                visible INTEGER NOT NULL DEFAULT 1,
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_messages_early_fixture
-            SELECT * FROM group_messages ORDER BY seq"""
-        )
-        connection.execute(
-            """CREATE TABLE group_agent_runs_early_fixture (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL,
-                topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
-                agent_id TEXT NOT NULL,
-                trigger_message_id TEXT NOT NULL,
-                response_message_id TEXT NOT NULL,
-                root_message_id TEXT NOT NULL,
-                depth INTEGER NOT NULL,
-                reply_mode TEXT NOT NULL DEFAULT 'mentioned',
-                status TEXT NOT NULL,
-                runtime_session_id TEXT,
-                error TEXT NOT NULL DEFAULT '',
-                created_at REAL NOT NULL,
-                updated_at REAL NOT NULL
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_agent_runs_early_fixture
-            SELECT id, room_id, topic_id, agent_id, trigger_message_id,
-                   response_message_id, root_message_id, depth, reply_mode,
-                   status, runtime_session_id, error, created_at, updated_at
-            FROM group_agent_runs"""
-        )
-        connection.execute(
-            """CREATE TABLE group_interactions_early_fixture (
-                id TEXT PRIMARY KEY,
-                room_id TEXT NOT NULL,
-                topic_id TEXT NOT NULL REFERENCES group_topics(id) ON DELETE CASCADE,
-                agent_id TEXT NOT NULL,
-                run_id TEXT NOT NULL,
-                kind TEXT NOT NULL,
-                payload_json TEXT NOT NULL,
-                status TEXT NOT NULL,
-                created_at REAL NOT NULL,
-                resolved_at REAL
-            )"""
-        )
-        connection.execute(
-            """INSERT INTO group_interactions_early_fixture
-            SELECT * FROM group_interactions"""
-        )
-        connection.execute("DROP TABLE group_interactions")
-        connection.execute("DROP TABLE group_agent_runs")
-        connection.execute("DROP TABLE group_messages")
-        connection.execute(
-            "ALTER TABLE group_messages_early_fixture RENAME TO group_messages"
-        )
-        connection.execute(
-            "ALTER TABLE group_agent_runs_early_fixture RENAME TO group_agent_runs"
-        )
-        connection.execute(
-            "ALTER TABLE group_interactions_early_fixture RENAME TO group_interactions"
-        )
-        connection.execute("DROP INDEX IF EXISTS idx_group_agents_room_host")
-        connection.execute("ALTER TABLE group_agents DROP COLUMN is_host")
-        connection.execute(
-            "UPDATE group_meta SET value = '4' WHERE key = 'schema_version'"
-        )
-
-    @staticmethod
-    def _repair_snapshot(connection: sqlite3.Connection) -> dict[str, object]:
-        ordering = {
-            "group_meta": "key",
-            "group_rooms": "id",
-            "group_topics": "id",
-            "group_agents": "id",
-            "group_agent_topic_state": "agent_id, topic_id",
-            "group_messages": "seq",
-            "group_agent_runs": "id",
-            "group_interactions": "id",
-            "group_events": "cursor",
-            "group_idempotency": "request_id",
-        }
-        return {
-            table: [
-                tuple(row)
-                for row in connection.execute(
-                    f"SELECT * FROM {table} ORDER BY {order_by}"
-                )
-            ]
-            for table, order_by in ordering.items()
-        }
-
-    @staticmethod
-    def _create_legacy_database(
-        path: Path, *, version: int, stored_session_id: str | None
-    ) -> tuple[str, str, str]:
-        if version not in {2, 3}:
-            raise ValueError("legacy test version must be 2 or 3")
-        SETTINGS_TESTS.GroupSettingsContractTests._create_v1_database(path)
-        connection = sqlite3.connect(path)
-        connection.row_factory = sqlite3.Row
-        GroupStore._migrate_v1_to_v2(connection)
-        room_id = connection.execute("SELECT id FROM group_rooms").fetchone()[0]
-        agent_id = connection.execute("SELECT id FROM group_agents").fetchone()[0]
-        topic_id = connection.execute(
-            "SELECT root_message_id FROM group_messages ORDER BY seq LIMIT 1"
-        ).fetchone()[0]
-        connection.execute(
-            """UPDATE group_agents
-            SET stored_session_id = ?, last_context_message_seq = 1
-            WHERE id = ?""",
-            (stored_session_id, agent_id),
-        )
-        if version == 3:
-            GroupStore._migrate_v2_to_v3(connection)
-            connection.execute(
-                "UPDATE group_agents SET session_config_json = NULL WHERE id = ?",
-                (agent_id,),
-            )
-        connection.commit()
-        connection.close()
-        return room_id, agent_id, topic_id
-
-    @staticmethod
-    def _default_session_configuration() -> dict[str, object]:
-        return {
-            "model": None,
-            "provider": None,
-            "reasoning_effort": None,
-            "fast": None,
-        }
-
-    @staticmethod
-    def _claim_legacy_topic_continuation(
-        store: GroupStore, room_id: str, agent_id: str, topic_id: str
-    ) -> dict[str, object]:
-        [run] = store.create_human_message(
-            room_id,
-            request_id=new_id(),
-            client_message_id=new_id(),
-            topic_id=topic_id,
-            content="继续旧话题",
-            mention_agent_ids=[agent_id],
-        )["runs"]
-        claimed = store.claim_next_runnable_run()
-        if claimed is None or claimed["id"] != run["id"]:
-            raise AssertionError("legacy continuation was not claimed")
-        return claimed
-
-    @staticmethod
-    def _assert_legacy_schema_rolled_back(path: Path) -> None:
-        connection = sqlite3.connect(path)
-        version = connection.execute(
-            "SELECT value FROM group_meta WHERE key = 'schema_version'"
-        ).fetchone()[0]
-        tables = {
-            row[0]
-            for row in connection.execute(
-                """SELECT name FROM sqlite_master
-                WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"""
-            )
-        }
-        connection.close()
-        if version != "3" or "group_topics" in tables:
-            raise AssertionError("failed migration was not rolled back")
-
-    def _submit_and_settle(
-        self,
-        store: GroupStore,
-        projection: dict[str, object],
-        *,
-        runtime: str,
-        stored: str,
-    ) -> None:
-        run = projection["run"]
-        agent = projection["agent"]
-        store.bind_run_runtime(run["id"], runtime)
-        store.commit_prompt_submission(
-            run["id"],
-            expected_stored_session_id=agent["storedSessionId"],
-            stored_session_id=stored,
-            runtime_session_id=runtime,
-            expected_context_seq=agent["lastContextMessageSeq"],
-            through_seq=projection["throughSeq"],
-        )
-        store.upsert_agent_message(
-            run["id"],
-            content="完成",
-            reasoning="",
-            tool_state=[],
-            status="completed",
-        )
-        store.settle_run(
-            run["id"],
-            runtime_session_id=runtime,
-            expected_stored_session_id=stored,
-            stored_session_id=stored,
-            outcome="completed",
-        )
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 104
hermes-plugins/yaoyao/dashboard/tests/test_poller_contract.py

@@ -1,104 +0,0 @@
-from __future__ import annotations
-
-import json
-import sqlite3
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-from unittest import mock
-
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-if str(DASHBOARD_DIR) not in sys.path:
-    sys.path.insert(0, str(DASHBOARD_DIR))
-
-import poller  # noqa: E402
-import store  # noqa: E402
-
-
-class PollerContractTests(unittest.TestCase):
-    def test_scans_file_references_from_every_session(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            root = Path(directory)
-            profile_home = root / "profile"
-            profile_home.mkdir()
-            files = root / "files"
-            files.mkdir()
-            first = files / "first.docx"
-            second = files / "second.xlsx"
-            spaced = files / "third file.md"
-            generated = files / "generated.txt"
-            for index, path in enumerate((first, second, spaced, generated), 1):
-                path.write_text(f"file {index}", encoding="utf-8")
-
-            conn = sqlite3.connect(profile_home / "state.db")
-            conn.execute(
-                "CREATE TABLE messages ("
-                "id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, role TEXT NOT NULL, "
-                "content TEXT, tool_name TEXT)"
-            )
-            conn.executemany(
-                "INSERT INTO messages(id, session_id, role, content, tool_name) "
-                "VALUES(?,?,?,?,?)",
-                (
-                    (1, "session-a", "assistant", f"MEDIA:{first}", None),
-                    (
-                        2,
-                        "session-b",
-                        "user",
-                        'GROUP_CONTEXT_JSON={"messages":[{"content":"'
-                        f"MEDIA:{second}"
-                        '","reasoning":"done"}]}',
-                        None,
-                    ),
-                    (3, "session-c", "user", f'MEDIA:"{spaced}"', None),
-                    (
-                        4,
-                        "session-d",
-                        "tool",
-                        json.dumps({"resolved_path": str(generated)}),
-                        "write_file",
-                    ),
-                ),
-            )
-            conn.commit()
-            conn.close()
-
-            watcher = poller._ProfileWatcher("contract-test", profile_home)
-            watcher.data_root = root / "library"
-            watcher.store = store.Store(watcher.data_root)
-
-            with mock.patch.object(poller, "BATCH_LIMIT", 2):
-                for _ in range(3):
-                    poller._poll_profile(watcher)
-
-            items, _, _ = watcher.store.query_attachments(limit=20)
-            self.assertEqual(
-                {item["sessionId"] for item in items},
-                {"session-a", "session-b", "session-c", "session-d"},
-            )
-            self.assertEqual(
-                {item["displayName"] for item in items},
-                {path.name for path in (first, second, spaced, generated)},
-            )
-            watcher.close()
-
-    def test_scanner_version_replays_history_only_once(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            archive = store.Store(Path(directory) / "library")
-            archive.mark_processed(42)
-
-            self.assertTrue(archive.prepare_scanner_version(7))
-            self.assertEqual(archive.processed_waterline(), 0)
-
-            archive.mark_processed(84)
-            self.assertFalse(archive.prepare_scanner_version(7))
-            self.assertEqual(archive.processed_waterline(), 84)
-
-            self.assertTrue(archive.prepare_scanner_version(8))
-            self.assertEqual(archive.processed_waterline(), 0)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 48
hermes-plugins/yaoyao/dashboard/tests/test_voice_settings_contract.py

@@ -1,48 +0,0 @@
-from __future__ import annotations
-
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-from unittest.mock import patch
-
-
-DASHBOARD_DIR = Path(__file__).resolve().parents[1]
-if str(DASHBOARD_DIR) not in sys.path:
-    sys.path.insert(0, str(DASHBOARD_DIR))
-
-import store  # noqa: E402
-
-
-class DuplexVoiceSettingsContractTests(unittest.TestCase):
-    def test_public_settings_mask_the_key_and_removed_current_voice_falls_back(self) -> None:
-        with tempfile.TemporaryDirectory() as directory:
-            root = Path(directory)
-            settings_path = root / "duplex_voice.json"
-            with (
-                patch.object(store, "DEFAULT_DATA_ROOT", root),
-                patch.object(store, "_DUPLEX_VOICE_FILE", settings_path),
-            ):
-                store.save_duplex_voice({
-                    "apiKey": "top-secret-key",
-                    "voices": [
-                        {"id": "voice-a", "name": "音色 A"},
-                        {"id": "voice-b", "name": "音色 B"},
-                    ],
-                    "currentVoiceId": "voice-b",
-                })
-                public = store.public_duplex_voice()
-                self.assertTrue(public["hasApiKey"])
-                self.assertNotIn("apiKey", public)
-                self.assertNotIn("top-secret-key", str(public))
-                self.assertEqual(store.runtime_duplex_voice()["apiKey"], "top-secret-key")
-
-                updated = store.save_duplex_voice({
-                    "voices": [{"id": "voice-a", "name": "音色 A"}],
-                })
-                self.assertEqual(updated["currentVoiceId"], "voice-a")
-                self.assertEqual(updated["apiKey"], "top-secret-key")
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 487
hermes-plugins/yaoyao/dashboard/voice_store.py

@@ -1,487 +0,0 @@
-"""TTS + STT provider settings store for the yaoyao plugin.
-
-Mirrors yaoyao-webui's tts-settings-store.ts and stt-settings-store.ts:
-- Multiple providers per profile, each with settings (baseUrl/model/voice/...)
-  + secrets (apiKey).
-- An "active provider" selection.
-- baseUrl presets (recently used base URLs per provider).
-- Secrets are masked as "[stored]" in public responses.
-
-Storage: a single JSON file at
-``<profile_home>/plugin-data/yaoyao/voice_providers.json`` (not SQLite - the
-data is small and write frequency is low). The structure matches
-yaoyao-webui's DB rows so the data is interchangeable.
-"""
-
-from __future__ import annotations
-
-import copy
-import json
-import logging
-import os
-import threading
-import time
-from typing import Any, Optional
-
-from store import DATA_ROOT, _ensure_dirs
-
-log = logging.getLogger("yaoyao.voice_store")
-
-_VOICE_PROVIDERS_FILE = DATA_ROOT / "voice_providers.json"
-_VOICE_LOCK = threading.Lock()
-
-STORED_MARKER = "[stored]"
-MAX_TEXT_LENGTH = 2000
-MAX_BASE_URL_PRESETS = 20
-MAX_PROMPT_LENGTH = 1000
-MAX_API_KEY_LENGTH = 4000
-
-# ---------------------------------------------------------------------------
-# Provider registries
-# ---------------------------------------------------------------------------
-
-TTS_PROVIDERS = ["edge", "openai", "custom", "mimo", "doubao"]
-TTS_PROVIDER_LABELS = {
-    "edge": "Edge TTS",
-    "openai": "OpenAI TTS",
-    "custom": "Custom TTS",
-    "mimo": "MiMo TTS",
-    "doubao": "Doubao TTS",
-}
-TTS_SETTINGS_KEYS = [
-    "baseUrl", "baseUrlPresets", "model", "voice", "rate", "pitch",
-    "authMode", "voiceMode", "voiceDesignDesc", "voiceCloneFormat", "stylePrompt",
-]
-TTS_SECRET_KEYS = ["apiKey"]
-
-STT_STORED_PROVIDERS = ["openai", "custom", "doubao"]
-STT_ACTIVE_PROVIDERS = ["browser"] + STT_STORED_PROVIDERS
-STT_PROVIDER_LABELS = {
-    "openai": "OpenAI STT",
-    "custom": "Custom STT",
-    "doubao": "Doubao STT",
-    "browser": "Browser STT",
-}
-STT_SETTINGS_KEYS = ["baseUrl", "baseUrlPresets", "model", "language", "prompt", "audioTranscode"]
-STT_SECRET_KEYS = ["apiKey"]
-
-# Default provider configurations (used when no saved config exists).
-_DEFAULT_TTS_PROVIDER_CONFIGS: dict[str, dict[str, Any]] = {
-    "edge": {"voice": "zh-CN-XiaoxiaoNeural", "rate": "+0%", "pitch": "+0Hz"},
-    "openai": {"baseUrl": "https://api.openai.com/v1", "model": "tts-1", "voice": "alloy"},
-    "custom": {"baseUrl": "", "model": "tts-1", "voice": "alloy"},
-    "mimo": {"baseUrl": "", "model": "mimo-v2.5-tts", "voice": "冰糖"},
-    "doubao": {"baseUrl": "https://openspeech.bytedance.com/api/v3/tts/unidirectional",
-               "model": "seed-tts-2.0", "voice": "zh_female_xiaohe_uranus_bigtts"},
-}
-
-_DEFAULT_STT_PROVIDER_CONFIGS: dict[str, dict[str, Any]] = {
-    "openai": {"baseUrl": "https://api.openai.com/v1", "model": "whisper-1", "language": ""},
-    "custom": {"baseUrl": "", "model": "whisper-1", "language": ""},
-    "doubao": {"baseUrl": "", "model": "", "language": ""},
-}
-
-# ---------------------------------------------------------------------------
-# File-level read / write
-# ---------------------------------------------------------------------------
-
-def _default_data() -> dict[str, Any]:
-    return {
-        "tts": {
-            "activeProvider": "edge",
-            "providers": {},
-        },
-        "stt": {
-            "activeProvider": "browser",
-            "providers": {},
-        },
-    }
-
-
-def _load_all() -> dict[str, Any]:
-    data = _default_data()
-    try:
-        if _VOICE_PROVIDERS_FILE.is_file():
-            saved = json.loads(_VOICE_PROVIDERS_FILE.read_text(encoding="utf-8"))
-            if isinstance(saved, dict):
-                _deep_merge(data, saved)
-    except Exception as e:
-        log.warning("voice providers load failed: %s", e)
-    return data
-
-
-def _save_all(data: dict[str, Any]) -> None:
-    _ensure_dirs()
-    with _VOICE_LOCK:
-        _VOICE_PROVIDERS_FILE.write_text(
-            json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8"
-        )
-
-
-def _deep_merge(base: dict, overlay: dict) -> None:
-    for k, v in overlay.items():
-        if k in base and isinstance(base[k], dict) and isinstance(v, dict):
-            _deep_merge(base[k], v)
-        else:
-            base[k] = v
-
-
-# ---------------------------------------------------------------------------
-# Settings / secrets sanitization
-# ---------------------------------------------------------------------------
-
-def _sanitize_settings(settings: Any, allowed_keys: list[str]) -> dict[str, Any]:
-    if not isinstance(settings, dict):
-        return {}
-    out: dict[str, Any] = {}
-    for k in allowed_keys:
-        if k not in settings:
-            continue
-        v = settings[k]
-        if k == "baseUrlPresets":
-            if isinstance(v, list):
-                presets: list[str] = []
-                seen: set[str] = set()
-                for url in v:
-                    if isinstance(url, str) and url not in seen:
-                        presets.append(url)
-                        seen.add(url)
-                    if len(presets) >= MAX_BASE_URL_PRESETS:
-                        break
-                out[k] = presets
-            continue
-        if not isinstance(v, str):
-            continue
-        max_len = MAX_PROMPT_LENGTH if k == "prompt" else MAX_TEXT_LENGTH
-        v = v.strip()
-        if v and len(v) <= max_len:
-            out[k] = v
-    return out
-
-
-def _sanitize_secrets(secrets: Any, allowed_keys: list[str]) -> dict[str, str]:
-    if not isinstance(secrets, dict):
-        return {}
-    out: dict[str, str] = {}
-    for k in allowed_keys:
-        v = secrets.get(k)
-        if isinstance(v, str):
-            v = v.strip()
-            if v and v != STORED_MARKER and len(v) <= MAX_API_KEY_LENGTH:
-                out[k] = v
-    return out
-
-
-def _mask_secrets(secrets: dict[str, str]) -> dict[str, str]:
-    return {k: (STORED_MARKER if v else "") for k, v in secrets.items()}
-
-
-def _merge_settings(existing: dict[str, Any], new: dict[str, Any]) -> dict[str, Any]:
-    merged = dict(existing)
-    for k, v in new.items():
-        if k == "baseUrlPresets":
-            presets = list(merged.get("baseUrlPresets", []))
-            if isinstance(v, list):
-                for url in v:
-                    if isinstance(url, str) and url not in presets:
-                        presets.insert(0, url)
-                    if len(presets) >= MAX_BASE_URL_PRESETS:
-                        break
-            merged["baseUrlPresets"] = presets[:MAX_BASE_URL_PRESETS]
-        else:
-            merged[k] = v
-    # If baseUrl is set and not in presets, add it.
-    base_url = merged.get("baseUrl", "")
-    if base_url and base_url not in merged.get("baseUrlPresets", []):
-        presets = merged.get("baseUrlPresets", [])
-        presets.insert(0, base_url)
-        merged["baseUrlPresets"] = presets[:MAX_BASE_URL_PRESETS]
-    return merged
-
-
-def _merge_secrets(existing: dict[str, str], new: dict[str, str]) -> dict[str, str]:
-    merged = dict(existing)
-    for k, v in new.items():
-        merged[k] = v
-    return merged
-
-
-# ---------------------------------------------------------------------------
-# Provider row helpers
-# ---------------------------------------------------------------------------
-
-def _provider_row(kind: str, provider: str, data: dict, include_secrets: bool) -> dict[str, Any]:
-    """Build a provider row for the API response."""
-    section = data[kind]
-    providers = section.get("providers", {})
-    stored = providers.get(provider, {})
-    defaults = _DEFAULT_TTS_PROVIDER_CONFIGS if kind == "tts" else _DEFAULT_STT_PROVIDER_CONFIGS
-    default_cfg = defaults.get(provider, {})
-
-    settings = dict(default_cfg)
-    settings.update(stored.get("settings", {}))
-
-    raw_secrets = stored.get("secrets", {})
-    secrets = _mask_secrets(raw_secrets) if not include_secrets else dict(raw_secrets)
-
-    now = int(time.time() * 1000)
-    return {
-        "profile": "default",
-        "provider": provider,
-        "settings": settings,
-        "secrets": secrets,
-        "createdAt": stored.get("createdAt", 0),
-        "updatedAt": stored.get("updatedAt", now),
-    }
-
-
-def _list_provider_rows(kind: str, data: dict, include_secrets: bool) -> list[dict[str, Any]]:
-    providers = data[kind].get("providers", {})
-    provider_list = TTS_PROVIDERS if kind == "tts" else STT_STORED_PROVIDERS
-    rows: list[dict[str, Any]] = []
-    for p in provider_list:
-        if p in providers:
-            rows.append(_provider_row(kind, p, data, include_secrets))
-    return rows
-
-
-# ---------------------------------------------------------------------------
-# TTS settings API
-# ---------------------------------------------------------------------------
-
-def tts_list_settings() -> dict[str, Any]:
-    data = _load_all()
-    active = data["tts"].get("activeProvider", "edge")
-    # If only one non-edge provider is configured, prefer it.
-    configured = list(data["tts"].get("providers", {}).keys())
-    if active == "edge" and len(configured) == 1 and configured[0] != "edge":
-        active = configured[0]
-    return {
-        "settings": _list_provider_rows("tts", data, include_secrets=False),
-        "activeProvider": active,
-    }
-
-
-def tts_get_active() -> str:
-    return _load_all()["tts"].get("activeProvider", "edge")
-
-
-def tts_set_active(provider: str) -> str:
-    if provider not in TTS_PROVIDERS:
-        raise ValueError(f"unknown TTS provider: {provider}")
-    data = _load_all()
-    data["tts"]["activeProvider"] = provider
-    _save_all(data)
-    return provider
-
-
-def tts_get_provider(provider: str, *, include_secrets: bool = False) -> Optional[dict[str, Any]]:
-    if provider not in TTS_PROVIDERS:
-        return None
-    data = _load_all()
-    return _provider_row("tts", provider, data, include_secrets)
-
-
-def tts_save_provider(provider: str, settings: Any, secrets: Any) -> dict[str, Any]:
-    if provider not in TTS_PROVIDERS:
-        raise ValueError(f"unknown TTS provider: {provider}")
-    data = _load_all()
-    providers = data["tts"].setdefault("providers", {})
-    existing = providers.get(provider, {})
-    existing_settings = dict(existing.get("settings", {}))
-    existing_settings.update(_DEFAULT_TTS_PROVIDER_CONFIGS.get(provider, {}))
-    clean_settings = _sanitize_settings(settings, TTS_SETTINGS_KEYS)
-    merged_settings = _merge_settings(existing_settings, clean_settings)
-    clean_secrets = _sanitize_secrets(secrets, TTS_SECRET_KEYS)
-    merged_secrets = _merge_secrets(existing.get("secrets", {}), clean_secrets)
-
-    now = int(time.time() * 1000)
-    providers[provider] = {
-        "settings": merged_settings,
-        "secrets": merged_secrets,
-        "createdAt": existing.get("createdAt", now),
-        "updatedAt": now,
-    }
-    _save_all(data)
-    return _provider_row("tts", provider, data, include_secrets=False)
-
-
-def tts_delete_provider(provider: str) -> bool:
-    if provider == "edge":
-        raise ValueError("edge provider cannot be deleted")
-    data = _load_all()
-    providers = data["tts"].get("providers", {})
-    if provider not in providers:
-        return False
-    del providers[provider]
-    if data["tts"].get("activeProvider") == provider:
-        data["tts"]["activeProvider"] = "edge"
-    _save_all(data)
-    return True
-
-
-def tts_delete_base_url_preset(provider: str, url: str) -> Optional[dict[str, Any]]:
-    data = _load_all()
-    providers = data["tts"].get("providers", {})
-    stored = providers.get(provider, {})
-    settings = stored.get("settings", {})
-    presets = settings.get("baseUrlPresets", [])
-    settings["baseUrlPresets"] = [u for u in presets if u != url]
-    if settings.get("baseUrl") == url:
-        settings["baseUrl"] = ""
-    stored["settings"] = settings
-    providers[provider] = stored
-    _save_all(data)
-    return _provider_row("tts", provider, data, include_secrets=False)
-
-
-def tts_clear_secret(provider: str, secret_name: str) -> Optional[dict[str, Any]]:
-    if secret_name != "apiKey":
-        raise ValueError(f"unknown secret: {secret_name}")
-    data = _load_all()
-    providers = data["tts"].get("providers", {})
-    stored = providers.get(provider, {})
-    secrets = stored.get("secrets", {})
-    secrets.pop(secret_name, None)
-    stored["secrets"] = secrets
-    providers[provider] = stored
-    _save_all(data)
-    return _provider_row("tts", provider, data, include_secrets=False)
-
-
-# ---------------------------------------------------------------------------
-# STT settings API
-# ---------------------------------------------------------------------------
-
-def stt_list_settings() -> dict[str, Any]:
-    data = _load_all()
-    active = data["stt"].get("activeProvider", "browser")
-    return {
-        "settings": _list_provider_rows("stt", data, include_secrets=False),
-        "activeProvider": active,
-    }
-
-
-def stt_get_active() -> str:
-    return _load_all()["stt"].get("activeProvider", "browser")
-
-
-def stt_set_active(provider: str) -> str:
-    if provider not in STT_ACTIVE_PROVIDERS:
-        raise ValueError(f"unknown STT provider: {provider}")
-    data = _load_all()
-    data["stt"]["activeProvider"] = provider
-    _save_all(data)
-    return provider
-
-
-def stt_get_provider(provider: str, *, include_secrets: bool = False) -> Optional[dict[str, Any]]:
-    if provider not in STT_STORED_PROVIDERS:
-        return None
-    data = _load_all()
-    return _provider_row("stt", provider, data, include_secrets)
-
-
-def stt_save_provider(provider: str, settings: Any, secrets: Any) -> dict[str, Any]:
-    if provider not in STT_STORED_PROVIDERS:
-        raise ValueError(f"unknown STT provider: {provider}")
-    data = _load_all()
-    providers = data["stt"].setdefault("providers", {})
-    existing = providers.get(provider, {})
-    existing_settings = dict(existing.get("settings", {}))
-    existing_settings.update(_DEFAULT_STT_PROVIDER_CONFIGS.get(provider, {}))
-    clean_settings = _sanitize_settings(settings, STT_SETTINGS_KEYS)
-    # audioTranscode only accepts 'ffmpeg' or 'none'
-    if "audioTranscode" in clean_settings:
-        if clean_settings["audioTranscode"] not in ("ffmpeg", "none"):
-            del clean_settings["audioTranscode"]
-    merged_settings = _merge_settings(existing_settings, clean_settings)
-    clean_secrets = _sanitize_secrets(secrets, STT_SECRET_KEYS)
-    merged_secrets = _merge_secrets(existing.get("secrets", {}), clean_secrets)
-
-    now = int(time.time() * 1000)
-    providers[provider] = {
-        "settings": merged_settings,
-        "secrets": merged_secrets,
-        "createdAt": existing.get("createdAt", now),
-        "updatedAt": now,
-    }
-    _save_all(data)
-    return _provider_row("stt", provider, data, include_secrets=False)
-
-
-def stt_delete_provider(provider: str) -> bool:
-    data = _load_all()
-    providers = data["stt"].get("providers", {})
-    if provider not in providers:
-        return False
-    del providers[provider]
-    if data["stt"].get("activeProvider") == provider:
-        data["stt"]["activeProvider"] = "browser"
-    _save_all(data)
-    return True
-
-
-def stt_delete_base_url_preset(provider: str, url: str) -> Optional[dict[str, Any]]:
-    data = _load_all()
-    providers = data["stt"].get("providers", {})
-    stored = providers.get(provider, {})
-    settings = stored.get("settings", {})
-    presets = settings.get("baseUrlPresets", [])
-    settings["baseUrlPresets"] = [u for u in presets if u != url]
-    if settings.get("baseUrl") == url:
-        settings["baseUrl"] = ""
-    stored["settings"] = settings
-    providers[provider] = stored
-    _save_all(data)
-    return _provider_row("stt", provider, data, include_secrets=False)
-
-
-def stt_clear_secret(provider: str, secret_name: str) -> Optional[dict[str, Any]]:
-    if secret_name != "apiKey":
-        raise ValueError(f"unknown secret: {secret_name}")
-    data = _load_all()
-    providers = data["stt"].get("providers", {})
-    stored = providers.get(provider, {})
-    secrets = stored.get("secrets", {})
-    secrets.pop(secret_name, None)
-    stored["secrets"] = secrets
-    providers[provider] = stored
-    _save_all(data)
-    return _provider_row("stt", provider, data, include_secrets=False)
-
-
-# ---------------------------------------------------------------------------
-# Provider info (for the frontend provider picker)
-# ---------------------------------------------------------------------------
-
-def provider_info() -> dict[str, Any]:
-    """Static info about all providers: labels, settings keys, needs-key flags."""
-    return {
-        "tts": {
-            "providers": [
-                {
-                    "id": p,
-                    "label": TTS_PROVIDER_LABELS[p],
-                    "settingsKeys": TTS_SETTINGS_KEYS,
-                    "secretKeys": TTS_SECRET_KEYS,
-                    "needsKey": p != "edge",
-                    "defaults": _DEFAULT_TTS_PROVIDER_CONFIGS.get(p, {}),
-                }
-                for p in TTS_PROVIDERS
-            ],
-        },
-        "stt": {
-            "providers": [
-                {
-                    "id": p,
-                    "label": STT_PROVIDER_LABELS[p],
-                    "settingsKeys": STT_SETTINGS_KEYS,
-                    "secretKeys": STT_SECRET_KEYS,
-                    "needsKey": p != "browser",
-                    "defaults": _DEFAULT_STT_PROVIDER_CONFIGS.get(p, {}),
-                }
-                for p in STT_ACTIVE_PROVIDERS if p in STT_PROVIDER_LABELS
-            ],
-        },
-    }

+ 0 - 4
hermes-plugins/yaoyao/plugin.yaml

@@ -1,4 +0,0 @@
-name: yaoyao
-version: "1.7.3"
-description: "YaoYao Dashboard extension for files, Agent identity, voice, and multi-device teams"
-author: samien

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "hermes-yaoyao",
-  "version": "0.2.31",
+  "version": "0.3.0",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "hermes-yaoyao",
-      "version": "0.2.31",
+      "version": "0.3.0",
       "license": "BSL-1.1",
       "dependencies": {
         "@koa/bodyparser": "^5.0.0",

+ 3 - 2
package.json

@@ -1,6 +1,6 @@
 {
   "name": "hermes-yaoyao",
-  "version": "0.2.31",
+  "version": "0.3.0",
   "private": true,
   "license": "BSL-1.1",
   "description": "夭夭 Web:直连 Hermes 9119 的聊天、团队、文件库与产物工作台",
@@ -22,7 +22,8 @@
     "test:live": "cross-env HERMES_YAOYAO_LIVE_TEST=1 vitest run tests/live",
     "brand:verify": "node scripts/verify-brand.mjs",
     "release:verify": "node scripts/verify-release.mjs",
-    "verify:lifecycle": "node scripts/verify-lifecycle.mjs"
+    "verify:lifecycle": "node scripts/verify-lifecycle.mjs",
+    "test:e2e:workspace": "npm run build && playwright test -c playwright.workspace.config.ts"
   },
   "dependencies": {
     "@koa/bodyparser": "^5.0.0",

+ 1 - 0
playwright.config.ts

@@ -2,6 +2,7 @@ import { defineConfig, devices } from '@playwright/test'
 
 export default defineConfig({
   testDir: './tests/e2e',
+  testIgnore: '**/workspace-chat.spec.ts',
   timeout: 30_000,
   fullyParallel: false,
   workers: 1,

+ 22 - 0
playwright.workspace.config.ts

@@ -0,0 +1,22 @@
+import { defineConfig, devices } from '@playwright/test'
+export default defineConfig({
+  testDir: './tests/e2e',
+  testMatch: 'workspace-chat.spec.ts',
+  workers: 1,
+  timeout: 45_000,
+  reporter: 'list',
+  use: {
+    baseURL: 'http://127.0.0.1:18802',
+    viewport: { width: 1280, height: 800 },
+    trace: 'retain-on-failure',
+    screenshot: 'only-on-failure',
+  },
+  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+  webServer: {
+    command:
+      'WORKSPACE_FIXTURE_PORT=18802 WORKSPACE_FIXTURE_UPSTREAM_PORT=19120 node --import tsx tests/fixtures/workspace-server.ts',
+    url: 'http://127.0.0.1:18802/healthz',
+    reuseExistingServer: false,
+    timeout: 20_000,
+  },
+})

+ 3 - 4
release.json

@@ -1,7 +1,6 @@
 {
   "schemaVersion": 1,
-  "releaseVersion": "0.2.31",
-  "webVersion": "0.2.31",
-  "pluginVersion": "1.7.3",
-  "gitTag": "v0.2.31"
+  "releaseVersion": "0.3.0",
+  "webVersion": "0.3.0",
+  "gitTag": "v0.3.0"
 }

+ 1 - 6
scripts/verify-release.mjs

@@ -8,9 +8,6 @@ const json = async path => JSON.parse(await readFile(resolve(root, path), 'utf8'
 const release = await json('release.json')
 const pkg = await json('package.json')
 const lock = await json('package-lock.json')
-const pluginManifest = await json('hermes-plugins/yaoyao/dashboard/manifest.json')
-const pluginYaml = await readFile(resolve(root, 'hermes-plugins/yaoyao/plugin.yaml'), 'utf8')
-const pluginYamlVersion = pluginYaml.match(/^version:\s*["']?([^"'\s]+)["']?\s*$/m)?.[1]
 const updaterBuildPackages = [
   '@vitejs/plugin-vue',
   '@vue/tsconfig',
@@ -27,8 +24,6 @@ if (pkg.version !== release.webVersion) failures.push('package.json 版本与 re
 if (lock.version !== release.webVersion || lock.packages?.['']?.version !== release.webVersion) {
   failures.push('package-lock.json 版本与 release.json 不一致')
 }
-if (pluginManifest.version !== release.pluginVersion) failures.push('插件 manifest.json 版本与 release.json 不一致')
-if (pluginYamlVersion !== release.pluginVersion) failures.push('plugin.yaml 版本与 release.json 不一致')
 for (const dependency of updaterBuildPackages) {
   if (typeof pkg.dependencies?.[dependency] !== 'string') {
     failures.push(`升级构建依赖 ${dependency} 必须位于 dependencies,以兼容旧版后台升级器`)
@@ -39,5 +34,5 @@ if (failures.length) {
   for (const failure of failures) process.stderr.write(`- ${failure}\n`)
   process.exitCode = 1
 } else {
-  process.stdout.write(`发布版本校验通过:Web ${release.webVersion} + 插件 ${release.pluginVersion}\n`)
+  process.stdout.write(`发布版本校验通过:Web ${release.webVersion}\n`)
 }

+ 2 - 6
src/client/App.vue

@@ -6,15 +6,12 @@ import LoginView from '@/views/LoginView.vue'
 import PasswordChangeView from '@/views/PasswordChangeView.vue'
 import { useAuthStore } from '@/stores/auth'
 import { useChatStore } from '@/stores/chat'
-import { useGroupsStore } from '@/stores/groups'
 import { useKanbanStore } from '@/stores/kanban'
 import { useThemeStore } from '@/stores/theme'
-import { reconcileYaoyaoPlugin } from '@/api/systemUpdate'
 import AgentIdentityFixture from '@/components/app/AgentIdentityFixture.vue'
 
 const auth = useAuthStore()
 const chat = useChatStore()
-const groups = useGroupsStore()
 const kanban = useKanbanStore()
 const theme = useThemeStore()
 const route = useRoute()
@@ -22,8 +19,8 @@ const agentIdentityFixture = import.meta.env.DEV
   && new URLSearchParams(window.location.search).get('fixture') === 'agent-identity'
 
 const pageTitle = computed(() => {
-  const name = route.path.startsWith('/groups')
-    ? groups.selectedRoom?.name || '团队'
+  const name = route.path.startsWith('/conversations')
+    ? '聊天'
     : route.path.startsWith('/kanban')
       ? kanban.selectedBoard?.name || kanban.selectedBoardSlug || '看板'
     : route.path.startsWith('/files')
@@ -42,7 +39,6 @@ watch(pageTitle, value => { document.title = value }, { immediate: true })
 
 watch(() => auth.isAuthenticated, authenticated => {
   if (authenticated) {
-    void reconcileYaoyaoPlugin().catch(() => undefined)
     void chat.connect().catch(() => undefined)
   }
 })

+ 3 - 3
src/client/api/sessions.ts

@@ -2,7 +2,7 @@ import type { ChatMessage, JsonValue, SessionSummary } from '@shared/types'
 import { apiRequest, apiUrl, unwrapData } from './client'
 import { normalizeChatMessage, normalizeSession, number, record, values } from '@/utils/normalize'
 
-const EXCLUDED_SOURCES = 'cron,ios_group'
+const EXCLUDED_SOURCES = 'cron,ios_group,yaoyao_workspace'
 
 export interface SessionPage {
   items: SessionSummary[]
@@ -33,7 +33,7 @@ export async function getSessions(profile?: string, cursor?: string, limit = 100
   const source = record(payload)
   const rawItems = values(source.items ?? source.sessions ?? payload)
   const items = rawItems.map(item => normalizeSession(item, profile)).filter(session => session.id)
-    .filter(session => !['cron', 'ios_group'].includes(session.source))
+    .filter(session => !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source))
   const total = number(source.total)
   const nextOffset = offset + items.length
   return {
@@ -56,7 +56,7 @@ export async function searchSessions(query: string, profile?: string, limit = 10
   })))
   const source = record(payload)
   return values(source.items ?? source.sessions ?? source.results ?? payload).map(item => normalizeSession(item, profile))
-    .filter(session => session.id && !['cron', 'ios_group'].includes(session.source))
+    .filter(session => session.id && !['cron', 'ios_group', 'yaoyao_workspace'].includes(session.source))
 }
 
 export async function getSession(id: string, profile?: string): Promise<SessionSummary> {

+ 0 - 16
src/client/api/systemUpdate.ts

@@ -5,7 +5,6 @@ export interface ReleaseManifest {
   schemaVersion: 1
   releaseVersion: string
   webVersion: string
-  pluginVersion: string
   gitTag: string
 }
 
@@ -34,8 +33,6 @@ export interface UpdateJob {
 
 export interface SystemUpdateStatus {
   current: ReleaseManifest
-  installedPluginVersion?: string
-  versionsMatch: boolean
   installationMode: 'source' | 'release'
   latest?: ReleaseManifest
   updateAvailable: boolean
@@ -71,16 +68,3 @@ export function systemUpdateJob(jobID: string): Promise<UpdateJob> {
 export function rollbackSystemUpdate(): Promise<UpdateJob> {
   return apiRequest('/api/app/system/update/rollback', { method: 'POST', body: {} })
 }
-
-export function reconcileYaoyaoPlugin(): Promise<{
-  ok: boolean
-  updated: boolean
-  installedPluginVersion?: string
-  expectedPluginVersion: string
-}> {
-  return apiRequest('/api/app/plugins/yaoyao/reconcile', {
-    method: 'POST',
-    body: {},
-    timeoutMs: 90_000,
-  })
-}

+ 4 - 2
src/client/components/app/SettingsCenterDialog.vue

@@ -6,6 +6,8 @@ import AgentIdentityPanel from '@/components/app/AgentIdentityPanel.vue'
 import DuplexVoicePanel from '@/components/app/DuplexVoicePanel.vue'
 import ModelServicesPanel from '@/components/app/ModelServicesPanel.vue'
 import NodePairingPanel from '@/components/app/NodePairingPanel.vue'
+import WorkspaceNodesPanel from '@/components/workspace/WorkspaceNodesPanel.vue'
+import WorkspaceVoiceProviders from '@/components/workspace/WorkspaceVoiceProviders.vue'
 import SystemManagementPanel from '@/components/app/SystemManagementPanel.vue'
 import SystemOverviewPanel from '@/components/app/SystemOverviewPanel.vue'
 import SystemUpdatePanel from '@/components/app/SystemUpdatePanel.vue'
@@ -342,8 +344,8 @@ watch(() => [props.open, props.initialPage] as const, ([open, initialPage]) => {
                 <SystemManagementPanel v-else-if="activePage === 'system-users' && isAdmin" section="users" :active="true" @dirty-change="setDirty('system-users', $event)" />
                 <SystemManagementPanel v-else-if="activePage === 'system-connection' && isAdmin" section="connection" :active="true" :upstream-ready="upstreamReady" :upstream-error="upstreamError" @dirty-change="setDirty('system-connection', $event)" />
                 <SystemManagementPanel v-else-if="activePage === 'system-push' && isAdmin" section="push" :active="true" @dirty-change="setDirty('system-push', $event)" />
-                <NodePairingPanel v-else-if="activePage === 'system-nodes' && isAdmin" mode="nodes" :active="true" :is-admin="true" @dirty-change="setDirty('system-nodes', $event)" />
-                <DuplexVoicePanel v-else-if="activePage === 'system-voice' && isAdmin" @dirty-change="setDirty('system-voice', $event)" />
+                <WorkspaceNodesPanel v-else-if="activePage === 'system-nodes' && isAdmin" />
+                <section v-else-if="activePage === 'system-voice' && isAdmin"><DuplexVoicePanel @dirty-change="setDirty('system-voice', $event)" /><WorkspaceVoiceProviders /></section>
                 <SystemUpdatePanel v-else-if="activePage === 'system-update' && isAdmin" :active="true" @lock-change="updateLocked = $event" />
               </div>
               <footer v-if="showFixedFooter" class="settings-content__footer">

+ 0 - 4
src/client/components/app/SystemUpdateDialog.vue

@@ -22,7 +22,6 @@ let pollToken = 0
 
 const terminal = computed(() => job.value && ['succeeded', 'failed', 'rolled_back'].includes(job.value.state))
 const active = computed(() => job.value && !terminal.value)
-const currentPlugin = computed(() => status.value?.installedPluginVersion || '未检测(不影响 Web 升级)')
 const canApply = computed(() => Boolean(status.value?.supported && status.value.updateAvailable && status.value.latest && !active.value && !busy.value))
 
 function stopPolling() { pollToken += 1 }
@@ -116,12 +115,9 @@ onBeforeUnmount(stopPolling)
 
           <section v-if="status" class="version-grid">
             <article><small>当前 Web</small><strong>{{ status.current.webVersion }}</strong></article>
-            <article><small>当前插件</small><strong>{{ currentPlugin }}</strong></article>
             <article><small>最新 Web</small><strong>{{ status.latest?.webVersion || status.current.webVersion }}</strong></article>
-            <article><small>配套插件</small><strong>{{ status.latest?.pluginVersion || status.current.pluginVersion }}</strong></article>
           </section>
 
-          <p v-if="status?.installedPluginVersion && !status.versionsMatch" class="version-warning"><AppIcon name="alert" :size="14" />插件版本与 Web 清单不一致,可在 9119 恢复后单独更新;不影响 Web 升级。</p>
           <p v-if="status?.installationMode === 'source'" class="mode-note">首次升级会把运行服务迁移到可回滚的版本目录;Git 工作区不会被覆盖。</p>
           <p v-if="status && !status.supported" class="mode-note">{{ status.unsupportedReason }}</p>
 

+ 0 - 4
src/client/components/app/SystemUpdatePanel.vue

@@ -27,7 +27,6 @@ let lifecycleToken = 0
 const terminal = computed(() => job.value && ['succeeded', 'failed', 'rolled_back'].includes(job.value.state))
 const jobRunning = computed(() => Boolean(job.value && !terminal.value))
 const locked = computed(() => operationStarting.value || (jobRunning.value && !trackingTimedOut.value))
-const currentPlugin = computed(() => status.value?.installedPluginVersion || '未检测(不影响 Web 升级)')
 const canApply = computed(() => Boolean(status.value?.supported && status.value.updateAvailable && status.value.latest && !jobRunning.value && !busy.value))
 
 function stopPolling() { pollToken += 1 }
@@ -150,12 +149,9 @@ onBeforeUnmount(() => { lifecycleToken += 1; operationStarting.value = false; st
 
     <section v-if="status" class="version-grid" aria-label="版本信息">
       <article><small>当前 Web</small><strong>{{ status.current.webVersion }}</strong></article>
-      <article><small>当前插件</small><strong>{{ currentPlugin }}</strong></article>
       <article><small>最新 Web</small><strong>{{ status.latest?.webVersion || status.current.webVersion }}</strong></article>
-      <article><small>配套插件</small><strong>{{ status.latest?.pluginVersion || status.current.pluginVersion }}</strong></article>
     </section>
 
-    <p v-if="status?.installedPluginVersion && !status.versionsMatch" class="version-warning"><AppIcon name="alert" :size="15" />插件版本与 Web 清单不一致,可在 9119 恢复后单独更新;不影响 Web 升级。</p>
     <p v-if="status?.installationMode === 'source'" class="mode-note">首次升级会把运行服务迁移到可回滚的版本目录;Git 工作区不会被覆盖。</p>
     <p v-if="status && !status.supported" class="mode-note">{{ status.unsupportedReason }}</p>
 

+ 20 - 19
src/client/components/app/WorkspaceShell.vue

@@ -105,8 +105,8 @@ function profileTitle(profile?: Profile): string {
 }
 
 const navItems: NavItem[] = [
-  { key: 'chat', label: '对话', path: '/chat', icon: 'chat' },
-  { key: 'groups', label: '团队', path: '/groups', icon: 'groups' },
+  { key: 'chat', label: '原生对话', path: '/chat', icon: 'chat' },
+  { key: 'groups', label: '聊天', path: '/conversations', icon: 'groups' },
   { key: 'kanban', label: '看板', path: '/kanban', icon: 'board' },
   { key: 'files', label: '文件库', path: '/files', icon: 'files' },
 ]
@@ -114,8 +114,9 @@ const navItems: NavItem[] = [
 // The active workspace is already represented by its main canvas and sidebar
 // context. Keep this strip focused on destinations the user can switch to.
 const featureNavItems = computed(() => navItems.filter(item => item.key !== activeNav.value.key
-  && !(activeNav.value.key === 'groups' && item.key === 'files')))
+ ))
 
+const applicationWorkspace = computed(() => route.path.startsWith('/conversations'))
 const activeNav = computed(() => {
   const item = navItems.find(entry => route.path.startsWith(entry.path))
   return item ?? navItems[0]
@@ -123,7 +124,7 @@ const activeNav = computed(() => {
 
 const contextHeading = computed(() => ({
   chat: '历史记录',
-  groups: '话题列表',
+  groups: '聊天列表',
   kanban: '看板列表',
   files: '历史记录',
 })[activeNav.value.key])
@@ -276,7 +277,7 @@ onBeforeUnmount(() => {
       <button ref="mobileNavigationTrigger" class="icon-button" type="button" aria-label="打开导航" @click="openMobileDrawer">
         <AppIcon name="menu" :size="20" />
       </button>
-      <button class="mobile-brand" type="button" aria-label="返回对话" @click="navigate('/chat')">
+      <button class="mobile-brand" type="button" aria-label="返回聊天" @click="navigate('/conversations')">
         <BrandMark :size="28" compact />
       </button>
       <button class="icon-button" type="button" :aria-label="theme === 'dark' ? '切换浅色主题' : '切换深色主题'" @click="emit('toggleTheme')">
@@ -291,7 +292,7 @@ onBeforeUnmount(() => {
       :inert="mobileDrawerOpen"
     >
       <div class="sidebar-brand-row">
-        <button class="rail__brand sidebar-brand" type="button" aria-label="返回对话" title="夭夭 Web" @click="navigate('/chat')">
+        <button class="rail__brand sidebar-brand" type="button" aria-label="返回聊天" title="夭夭 Web" @click="navigate('/conversations')">
           <BrandMark :size="sidebarCollapsed ? 26 : 32" :label="false" compact bare />
         </button>
       </div>
@@ -361,15 +362,15 @@ onBeforeUnmount(() => {
 
       <div class="sidebar-footer">
         <div class="sidebar-account-switcher">
-          <button class="sidebar-account-switcher__main" type="button" :title="`切换 Agent:${profileTitle(activeProfile)}`" aria-haspopup="listbox" :aria-expanded="profileMenuOpen" @click="toggleProfileMenu">
-            <AgentAvatar :name="profileTitle(activeProfile)" :avatar="activeProfile?.agentAvatar || ''" :size="30" />
+          <button class="sidebar-account-switcher__main" type="button" :title="applicationWorkspace ? '当前账号' : `切换 Agent:${profileTitle(activeProfile)}`" :aria-haspopup="applicationWorkspace ? undefined : 'listbox'" :aria-expanded="applicationWorkspace ? undefined : profileMenuOpen" @click="applicationWorkspace ? openSettings('account-security', $event) : toggleProfileMenu($event)">
+            <AgentAvatar :name="applicationWorkspace ? userName : profileTitle(activeProfile)" :avatar="applicationWorkspace ? '' : activeProfile?.agentAvatar || ''" :size="30" />
             <span class="account-copy">
-              <strong>{{ profileTitle(activeProfile) }}</strong>
-              <span>{{ activeProfile?.name || userName || '未选择 Agent' }}</span>
+              <strong>{{ applicationWorkspace ? userName : profileTitle(activeProfile) }}</strong>
+              <span>{{ applicationWorkspace ? '当前账号' : activeProfile?.name || userName || '未选择 Agent' }}</span>
             </span>
-            <AppIcon class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
+            <AppIcon v-if="!applicationWorkspace" class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
           </button>
-          <button class="sidebar-settings-trigger" type="button" title="设置中心" aria-label="打开设置中心" @click="openSettings('agent-identity', $event)">
+          <button class="sidebar-settings-trigger" type="button" title="设置中心" aria-label="打开设置中心" @click="openSettings(applicationWorkspace ? 'account-security' : 'agent-identity', $event)">
             <AppIcon name="settings" :size="17" />
           </button>
           <Transition name="menu-fade">
@@ -405,7 +406,7 @@ onBeforeUnmount(() => {
       :inert="!mobileDrawerOpen"
     >
       <div class="mobile-drawer__header">
-        <button class="sidebar-brand" type="button" aria-label="返回对话" @click="navigate('/chat')">
+        <button class="sidebar-brand" type="button" aria-label="返回聊天" @click="navigate('/conversations')">
           <BrandMark :size="32" compact />
         </button>
         <button ref="mobileDrawerClose" class="icon-button" type="button" aria-label="关闭导航" @click="closeMobileDrawer">
@@ -467,15 +468,15 @@ onBeforeUnmount(() => {
 
       <div class="sidebar-footer mobile-drawer__footer">
         <div class="sidebar-account-switcher">
-          <button class="sidebar-account-switcher__main" type="button" :title="`切换 Agent:${profileTitle(activeProfile)}`" aria-haspopup="listbox" :aria-expanded="profileMenuOpen" @click="toggleProfileMenu">
-            <AgentAvatar :name="profileTitle(activeProfile)" :avatar="activeProfile?.agentAvatar || ''" :size="30" />
+          <button class="sidebar-account-switcher__main" type="button" :title="applicationWorkspace ? '当前账号' : `切换 Agent:${profileTitle(activeProfile)}`" :aria-haspopup="applicationWorkspace ? undefined : 'listbox'" :aria-expanded="applicationWorkspace ? undefined : profileMenuOpen" @click="applicationWorkspace ? openSettings('account-security', $event) : toggleProfileMenu($event)">
+            <AgentAvatar :name="applicationWorkspace ? userName : profileTitle(activeProfile)" :avatar="applicationWorkspace ? '' : activeProfile?.agentAvatar || ''" :size="30" />
             <span class="account-copy">
-              <strong>{{ profileTitle(activeProfile) }}</strong>
-              <span>{{ activeProfile?.name || userName || '未选择 Agent' }}</span>
+              <strong>{{ applicationWorkspace ? userName : profileTitle(activeProfile) }}</strong>
+              <span>{{ applicationWorkspace ? '当前账号' : activeProfile?.name || userName || '未选择 Agent' }}</span>
             </span>
-            <AppIcon class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
+            <AppIcon v-if="!applicationWorkspace" class="sidebar-account-switcher__chevron" name="chevron-down" :size="14" />
           </button>
-          <button class="sidebar-settings-trigger" type="button" title="设置中心" aria-label="打开设置中心" @click="openSettings('agent-identity', $event)">
+          <button class="sidebar-settings-trigger" type="button" title="设置中心" aria-label="打开设置中心" @click="openSettings(applicationWorkspace ? 'account-security' : 'agent-identity', $event)">
             <AppIcon name="settings" :size="17" />
           </button>
           <Transition name="menu-fade">

+ 1 - 0
src/client/components/library/types.ts

@@ -19,6 +19,7 @@ export type UiLibraryItem = {
   downloadUrl?: string
   sourceLabel?: string
   sourceSessionId?: string
+  sourceWorkspaceConversationId?: string
   sourceMessageId?: string
   sourceProfile?: string
   textContent?: string

+ 1 - 2
src/client/components/messages/MarkdownContent.vue

@@ -118,8 +118,7 @@ function decorateFileLinks() {
     let url: URL
     try { url = new URL(link.href, window.location.href) } catch { return }
     const isAgentFile = /^\/Users\/[^/]+\/Agents\/.+/.test(url.pathname)
-    const isRemoteNodeFile = /^\/api\/plugins\/yaoyao\/v1\/nodes\/[0-9a-f-]{36}\/files$/i.test(url.pathname)
-      && Boolean(url.searchParams.get('path'))
+    const isRemoteNodeFile = /^\/api\/app\/files\/(?:[0-9a-f-]{36}|[0-9]+)\/(?:download|preview)$/i.test(url.pathname)
     if (url.origin !== window.location.origin || (!isAgentFile && !isRemoteNodeFile)) return
     link.dataset.fileCard = 'true'
     link.classList.add('file-link-card')

+ 114 - 0
src/client/components/workspace/ConversationList.vue

@@ -0,0 +1,114 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue'
+import AgentAvatar from '@/components/common/AgentAvatar.vue'
+import type { WorkspaceConversation } from '@shared/workspace'
+const props = defineProps<{ conversations: WorkspaceConversation[]; selected?: string }>()
+defineEmits<{ select: [id: string] }>()
+const query = ref(''),
+  archived = ref(false)
+const rows = computed(() =>
+  props.conversations.filter(
+    (c) =>
+      c.archived === archived.value &&
+      (!query.value || `${c.name} ${c.preview}`.toLowerCase().includes(query.value.toLowerCase())),
+  ),
+)
+</script>
+<template>
+  <div class="conversation-list">
+    <input v-model="query" type="search" placeholder="搜索聊天" aria-label="搜索聊天" />
+    <label class="archive-filter"><input v-model="archived" type="checkbox" />显示已归档</label>
+    <button
+      v-for="c in rows"
+      :key="c.id"
+      class="conversation-row"
+      :class="{ selected: c.id === selected }"
+      @click="$emit('select', c.id)"
+    >
+      <AgentAvatar
+        :name="c.name"
+        :avatar="c.avatar"
+        :state="c.activeRunId ? 'working' : 'idle'"
+        :size="38"
+      />
+      <span class="row-text"
+        ><strong>{{ c.pinned ? '⌖ ' : '' }}{{ c.name }}</strong
+        ><small
+          >{{ c.kind === 'group' ? `${c.memberIds.length} 位成员 · ` : ''
+          }}{{ c.preview || '开始聊天' }}</small
+        ></span
+      >
+      <span v-if="c.lastSeq > c.readSeq" class="unread" aria-label="未读消息" />
+    </button>
+    <p v-if="!rows.length" class="empty">
+      {{ archived ? '没有已归档聊天' : '创建一个 Agent,开始你的第一段聊天。' }}
+    </p>
+  </div>
+</template>
+<style scoped>
+.conversation-list {
+  padding: 8px;
+}
+.conversation-list > input {
+  box-sizing: border-box;
+  width: 100%;
+  padding: 10px 12px;
+  border: 1px solid var(--line);
+  border-radius: 10px;
+  background: var(--surface);
+  color: var(--text-primary);
+}
+.archive-filter {
+  display: flex;
+  gap: 6px;
+  align-items: center;
+  font-size: 11px;
+  color: var(--text-muted);
+  padding: 10px 3px;
+}
+.conversation-row {
+  width: 100%;
+  display: flex;
+  align-items: center;
+  gap: 10px;
+  border: 0;
+  border-radius: 12px;
+  background: transparent;
+  color: var(--text-primary);
+  padding: 12px 10px;
+  text-align: left;
+  cursor: pointer;
+}
+.conversation-row:hover,
+.conversation-row.selected {
+  background: var(--surface-soft);
+}
+.row-text {
+  display: grid;
+  gap: 5px;
+  min-width: 0;
+  flex: 1;
+}
+.row-text strong {
+  font-size: 13px;
+}
+.row-text small {
+  font-size: 11px;
+  color: var(--text-muted);
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.unread {
+  width: 7px;
+  height: 7px;
+  border-radius: 50%;
+  background: var(--accent, #507f6c);
+}
+.empty {
+  padding: 24px 12px;
+  font-size: 13px;
+  line-height: 1.8;
+  color: var(--text-muted);
+}
+</style>

+ 127 - 0
src/client/components/workspace/WorkspaceNodesPanel.vue

@@ -0,0 +1,127 @@
+<script setup lang="ts">
+import { onMounted, ref } from 'vue'
+import { apiRequest } from '@/api/client'
+const nodes = ref<Array<{ id: string; name: string; url: string }>>([]),
+  name = ref(''),
+  url = ref(''),
+  username = ref(''),
+  password = ref(''),
+  error = ref(''),
+  busy = ref(false)
+async function load() {
+  try {
+    nodes.value = (await apiRequest<{ nodes: typeof nodes.value }>('/api/app/nodes')).nodes
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+async function add() {
+  busy.value = true
+  error.value = ''
+  try {
+    await apiRequest('/api/app/nodes', {
+      method: 'POST',
+      body: {
+        name: name.value,
+        url: url.value,
+        username: username.value,
+        password: password.value,
+      },
+    })
+    password.value = ''
+    name.value = ''
+    url.value = ''
+    await load()
+  } catch (e) {
+    error.value = e instanceof Error ? e.message : '连接失败'
+  } finally {
+    busy.value = false
+  }
+}
+async function revoke(id: string) {
+  try {
+    await apiRequest(`/api/app/nodes/${id}`, { method: 'DELETE' })
+    await load()
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+onMounted(load)
+</script>
+<template>
+  <section class="nodes-panel">
+    <p>连接其他 Hermes 节点后,可用它的基础 Agent 创建角色。连接只属于当前登录用户。</p>
+    <p v-if="error" role="alert">{{ error }}</p>
+    <article v-for="node in nodes" :key="node.id">
+      <div>
+        <strong>{{ node.name }}</strong
+        ><small>{{ node.url }}</small>
+      </div>
+      <button @click="revoke(node.id)">断开</button>
+    </article>
+    <form @submit.prevent="add">
+      <label>节点名称<input v-model="name" required maxlength="100" /></label
+      ><label
+        >Hermes 地址<input
+          v-model="url"
+          type="url"
+          required
+          placeholder="http://服务器:9119" /></label
+      ><label>用户名<input v-model="username" autocomplete="off" /></label
+      ><label>密码<input v-model="password" type="password" autocomplete="new-password" /></label
+      ><button :disabled="busy">{{ busy ? '正在连接…' : '添加节点' }}</button>
+    </form>
+  </section>
+</template>
+<style scoped>
+.nodes-panel {
+  padding: 18px;
+  display: grid;
+  gap: 18px;
+  color: var(--text-primary);
+}
+p {
+  font-size: 13px;
+  line-height: 1.7;
+  color: var(--text-muted);
+}
+article {
+  display: flex;
+  justify-content: space-between;
+  gap: 12px;
+  padding: 12px;
+  border: 1px solid var(--line);
+  border-radius: 10px;
+}
+article div {
+  display: grid;
+  gap: 5px;
+}
+small {
+  font-size: 11px;
+  color: var(--text-muted);
+}
+form {
+  display: grid;
+  gap: 15px;
+}
+label {
+  display: grid;
+  gap: 7px;
+  font-size: 13px;
+}
+input,
+button {
+  border: 1px solid var(--line);
+  border-radius: 9px;
+  background: var(--surface-soft);
+  color: inherit;
+  padding: 10px;
+}
+button {
+  cursor: pointer;
+}
+p[role='alert'] {
+  color: var(--danger, #b44);
+}
+</style>

+ 167 - 0
src/client/components/workspace/WorkspaceVoiceProviders.vue

@@ -0,0 +1,167 @@
+<script setup lang="ts">
+import { onMounted, ref, watch } from 'vue'
+import { apiRequest } from '@/api/client'
+const kind = ref<'tts' | 'stt'>('tts'),
+  provider = ref('openai'),
+  active = ref(''),
+  rows = ref<
+    Array<{ provider: string; settings: Record<string, unknown>; secrets: Record<string, string> }>
+  >([])
+const baseUrl = ref(''),
+  model = ref(''),
+  voice = ref(''),
+  apiKey = ref(''),
+  error = ref(''),
+  notice = ref(''),
+  busy = ref(false)
+async function load() {
+  const r = await apiRequest<{ activeProvider: string; settings: typeof rows.value }>(
+    `/api/app/${kind.value}/settings`,
+  )
+  rows.value = r.settings
+  active.value = r.activeProvider
+  fill()
+}
+function fill() {
+  const r = rows.value.find((r) => r.provider === provider.value)
+  baseUrl.value = String(r?.settings.baseUrl ?? '')
+  model.value = String(r?.settings.model ?? '')
+  voice.value = String(r?.settings.voice ?? '')
+  apiKey.value = ''
+}
+async function save() {
+  busy.value = true
+  error.value = ''
+  try {
+    await apiRequest(`/api/app/${kind.value}/settings/${encodeURIComponent(provider.value)}`, {
+      method: 'PUT',
+      body: {
+        settings: { baseUrl: baseUrl.value, model: model.value, voice: voice.value },
+        secrets: apiKey.value ? { apiKey: apiKey.value } : {},
+        activeProvider: provider.value,
+      },
+    })
+    await load()
+    notice.value = '配置已保存'
+  } catch (e) {
+    error.value = String(e)
+  } finally {
+    busy.value = false
+  }
+}
+async function probe() {
+  busy.value = true
+  try {
+    const r = await apiRequest<{ ok: boolean; models: string[]; errorSummary?: string }>(
+      '/api/app/voice/probe',
+      {
+        method: 'POST',
+        body: {
+          kind: kind.value,
+          provider: provider.value,
+          baseUrl: baseUrl.value,
+          ...(apiKey.value ? { apiKey: apiKey.value } : {}),
+          compatibility: 'openai-compatible',
+        },
+      },
+    )
+    notice.value = r.ok
+      ? `连接成功,可用模型:${r.models.slice(0, 8).join('、')}`
+      : (r.errorSummary ?? '连接失败')
+  } catch (e) {
+    error.value = String(e)
+  } finally {
+    busy.value = false
+  }
+}
+async function remove() {
+  try {
+    await apiRequest(`/api/app/${kind.value}/settings/${encodeURIComponent(provider.value)}`, {
+      method: 'DELETE',
+    })
+    await load()
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+watch(kind, () => void load().catch((e) => (error.value = String(e))))
+watch(provider, fill)
+onMounted(() => void load().catch((e) => (error.value = String(e))))
+</script>
+<template>
+  <section class="voice-providers">
+    <h3>语音服务商</h3>
+    <p>当前启用:{{ active || '未配置' }}</p>
+    <p v-if="error" role="alert">{{ error }}</p>
+    <p v-if="notice" role="status">{{ notice }}</p>
+    <form @submit.prevent="save">
+      <label
+        >用途<select v-model="kind">
+          <option value="tts">语音合成 TTS</option>
+          <option value="stt">语音识别 STT</option>
+        </select></label
+      ><label
+        >服务商<select v-model="provider">
+          <option
+            v-for="p in kind === 'tts'
+              ? ['edge', 'openai', 'custom', 'mimo', 'doubao']
+              : ['openai', 'custom', 'doubao']"
+            :key="p"
+          >
+            {{ p }}
+          </option>
+        </select></label
+      ><label>服务地址<input v-model="baseUrl" type="url" /></label
+      ><label>模型<input v-model="model" /></label
+      ><label v-if="kind === 'tts'">音色<input v-model="voice" /></label
+      ><label
+        >API Key<input
+          v-model="apiKey"
+          type="password"
+          placeholder="留空保留已保存密钥"
+          autocomplete="new-password"
+      /></label>
+      <div>
+        <button :disabled="busy">保存并启用</button
+        ><button type="button" :disabled="busy || !baseUrl" @click="probe">测试连接</button
+        ><button type="button" :disabled="busy" @click="remove">删除配置</button>
+      </div>
+    </form>
+  </section>
+</template>
+<style scoped>
+.voice-providers {
+  padding: 20px 0;
+  border-top: 1px solid var(--line);
+  margin-top: 22px;
+}
+form {
+  display: grid;
+  gap: 14px;
+}
+label {
+  display: grid;
+  gap: 7px;
+  font-size: 13px;
+}
+input,
+select,
+button {
+  padding: 10px;
+  border: 1px solid var(--line);
+  border-radius: 9px;
+  color: var(--text-primary);
+  background: var(--surface-soft);
+}
+button {
+  margin-right: 8px;
+  cursor: pointer;
+}
+p {
+  font-size: 12px;
+  color: var(--text-muted);
+}
+[role='alert'] {
+  color: var(--danger, #b44);
+}
+</style>

+ 2 - 1
src/client/components/workspace/viewModels.ts

@@ -271,7 +271,7 @@ export function rewriteRemoteNodeFiles(content: string, nodeId: string, streamin
   return normalizeAssistantMediaMarkdown(content, streaming).replace(
     /(!?\[[^\]]*\]\()<?(?:file:\/\/)?(\/(?:Users|private|var|tmp)\/[^)>\n]+)>?(\))/g,
     (_match, prefix: string, path: string, suffix: string) => (
-      `${prefix}/api/plugins/yaoyao/v1/nodes/${encodeURIComponent(nodeId)}/files?path=${encodeURIComponent(path)}${suffix}`
+      `${prefix}/api/app/groups/nodes/${encodeURIComponent(nodeId)}/files?path=${encodeURIComponent(path)}${suffix}`
     ),
   )
 }
@@ -336,6 +336,7 @@ export function fileToUi(item: FileLibraryItem): UiLibraryItem {
     downloadUrl: item.downloadUrl,
     sourceLabel: origin?.sessionTitle || origin?.authorName || origin?.profile,
     sourceSessionId: origin?.sessionId,
+    sourceWorkspaceConversationId: origin?.workspaceConversationId,
     sourceMessageId: origin?.messageId,
     sourceProfile: origin?.profile,
   }

+ 2 - 2
src/client/router/index.ts

@@ -3,9 +3,9 @@ import { createRouter, createWebHistory } from 'vue-router'
 const router = createRouter({
   history: createWebHistory(),
   routes: [
-    { path: '/', redirect: '/chat' },
+    { path: '/', redirect: '/conversations' },
     { path: '/chat/:sessionId?', name: 'chat', component: () => import('@/views/ChatView.vue') },
-    { path: '/groups/:roomId?/:topicId?', name: 'groups', component: () => import('@/views/GroupsView.vue') },
+    { path: '/conversations/:id?', name: 'conversations', component: () => import('@/views/ConversationsView.vue') },
     { path: '/kanban/:boardSlug?', name: 'kanban', component: () => import('@/views/KanbanView.vue') },
     { path: '/files', name: 'files', component: () => import('@/views/FilesView.vue') },
     { path: '/artifacts', redirect: '/chat' },

+ 11 - 2
src/client/stores/files.ts

@@ -1,4 +1,4 @@
-import { computed, ref, shallowRef } from 'vue'
+import { computed, ref, shallowRef, watch } from 'vue'
 import { defineStore } from 'pinia'
 import type { FileKind, FileLibraryItem } from '@shared/types'
 import { getFiles } from '@/api/files'
@@ -45,7 +45,7 @@ export const useFilesStore = defineStore('files', () => {
         const page = await getFiles({
           search: query.value.trim() || undefined,
           kind: kindFilter.value,
-          profile: profile.value ?? auth.activeProfile?.name,
+          profile: profile.value,
           cursor,
           limit: 50,
         })
@@ -67,6 +67,15 @@ export const useFilesStore = defineStore('files', () => {
   }
 
   const reset = () => load(true)
+  watch(() => auth.user?.id, () => {
+    loadGeneration += 1
+    items.value = []
+    profile.value = undefined
+    nextCursor.value = undefined
+    visitedCursors.clear()
+    isLoading.value = false
+    error.value = undefined
+  }, { flush: 'sync' })
   const loadMore = () => load(false)
   return { items, filteredItems, nextCursor, hasMore, isLoading, error, query, kindFilter, profile, load, reset, loadMore }
 })

+ 1 - 0
src/client/utils/normalize.ts

@@ -505,6 +505,7 @@ export function normalizeFile(value: unknown, fallbackProfile?: string): FileLib
       id: origin.id as number | string | undefined,
       profile: string(origin.profile) || fallbackProfile || undefined,
       sessionId: string(pick(origin, 'sessionId', 'session_id')) || undefined,
+      workspaceConversationId: string(origin.workspaceConversationId) || undefined,
       sessionTitle: string(pick(origin, 'sessionTitle', 'session_title')) || undefined,
       messageId: string(pick(origin, 'messageId', 'message_id')) || undefined,
       authorKind: string(pick(origin, 'authorKind', 'author_kind')) as FileLibraryItem['origins'][number]['authorKind'] || undefined,

+ 991 - 0
src/client/views/ConversationsView.vue

@@ -0,0 +1,991 @@
+<script setup lang="ts">
+import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import WorkspaceShell from '@/components/app/WorkspaceShell.vue'
+import ConversationList from '@/components/workspace/ConversationList.vue'
+import WorkspaceNodesPanel from '@/components/workspace/WorkspaceNodesPanel.vue'
+import AgentAvatar from '@/components/common/AgentAvatar.vue'
+import MarkdownContent from '@/components/messages/MarkdownContent.vue'
+import { useAuthStore } from '@/stores/auth'
+import { useThemeStore } from '@/stores/theme'
+import { apiRequest } from '@/api/client'
+import type { JsonValue } from '@shared/types'
+import type {
+  WorkspaceAgent as Agent,
+  WorkspaceConversation as Conversation,
+  WorkspaceMessage as Message,
+  WorkspaceRun as Run,
+  WorkspaceInteraction as Interaction,
+  WorkspaceSource as Source,
+  WorkspaceFile,
+  WorkspaceEvent,
+} from '@shared/workspace'
+const auth = useAuthStore(),
+  theme = useThemeStore(),
+  route = useRoute(),
+  router = useRouter()
+const agents = ref<Agent[]>([]),
+  conversations = ref<Conversation[]>([]),
+  messages = ref<Message[]>([]),
+  sources = ref<Source[]>([])
+const active = ref<Conversation>(),
+  run = ref<Run | null>(null),
+  interactions = ref<Interaction[]>([]),
+  context = ref<Record<string, unknown> | null>(null)
+const text = ref(''),
+  error = ref(''),
+  busy = ref(false),
+  loading = ref(false),
+  files = ref<WorkspaceFile[]>([]),
+  mentions = ref<string[]>([]),
+  older = ref(true)
+const showNodes = ref(false)
+const dialog = ref<'agent' | 'group' | 'editAgent' | 'editGroup' | null>(null),
+  editingId = ref(''),
+  scroller = ref<HTMLElement>(),
+  fileInput = ref<HTMLInputElement>(),
+  dialogElement = ref<HTMLDialogElement>()
+const form = reactive({
+  name: '',
+  avatar: '',
+  instructions: '',
+  source: '',
+  memberIds: [] as string[],
+  administratorId: '',
+  mode: 'host' as 'host' | 'free',
+  autoReplyIds: [] as string[],
+  maxReplyRounds: 3,
+})
+const answers = reactive<Record<string, string>>({})
+let cursor = 0,
+  disposed = false,
+  timer: ReturnType<typeof setTimeout> | undefined,
+  generation = 0,
+  pendingRequestId: string | undefined
+const selected = computed(() => (typeof route.params.id === 'string' ? route.params.id : undefined))
+const members = computed(() => agents.value.filter((a) => active.value?.memberIds.includes(a.id)))
+const isAgentDialog = computed(() => dialog.value === 'agent' || dialog.value === 'editAgent')
+const body = (v: unknown) => v as JsonValue
+async function refresh() {
+  const [a, c] = await Promise.all([
+    apiRequest<{ agents: Agent[] }>('/api/app/agents'),
+    apiRequest<{ conversations: Conversation[]; cursor: number }>('/api/app/conversations'),
+  ])
+  if (disposed) return
+  agents.value = a.agents
+  conversations.value = c.conversations
+  if (!cursor) cursor = c.cursor
+}
+async function load(id = selected.value, append = false) {
+  if (!id) {
+    active.value = undefined
+    messages.value = []
+    return
+  }
+  const own = ++generation
+  if (!append) loading.value = true
+  try {
+    const r = await apiRequest<{
+      conversation: Conversation
+      messages: Message[]
+      run: Run | null
+      interactions: Interaction[]
+      context: Record<string, unknown> | null
+    }>(`/api/app/conversations/${id}`)
+    if (disposed || own !== generation) return
+    const atBottom =
+      !scroller.value ||
+      scroller.value.scrollHeight - scroller.value.scrollTop - scroller.value.clientHeight < 100
+    active.value = r.conversation
+    messages.value = append
+      ? [...new Map([...messages.value, ...r.messages].map((m) => [m.id, m])).values()].sort(
+          (a, b) => a.seq - b.seq,
+        )
+      : r.messages
+    run.value = r.run
+    interactions.value = r.interactions
+    context.value = r.context
+    if (!append) older.value = r.messages.length === 100
+    if (!append || atBottom) {
+      await nextTick()
+      scroller.value?.scrollTo({ top: scroller.value.scrollHeight })
+      await markRead()
+    }
+  } catch (e) {
+    error.value = e instanceof Error ? e.message : '加载失败'
+  } finally {
+    if (own === generation) loading.value = false
+  }
+}
+async function markRead() {
+  const c = active.value
+  if (!c || c.readSeq >= c.lastSeq) return
+  await apiRequest(`/api/app/conversations/${c.id}/read`, {
+    method: 'PUT',
+    body: { seq: c.lastSeq },
+  })
+  c.readSeq = c.lastSeq
+}
+async function poll() {
+  try {
+    const r = await apiRequest<{ events: WorkspaceEvent[]; cursor: number }>(
+      `/api/app/events?after=${cursor}`,
+    )
+    if (disposed) return
+    cursor = r.cursor
+    if (r.events.length) {
+      await refresh()
+      if (r.events.some((e) => e.conversationId === selected.value || e.type === 'agent.changed'))
+        await load(selected.value, true)
+    }
+  } catch (e) {
+    if (!disposed) error.value = e instanceof Error ? e.message : '连接中断,正在重连'
+  } finally {
+    if (!disposed) timer = setTimeout(() => void poll(), 1200)
+  }
+}
+async function select(id: string) {
+  error.value = ''
+  files.value = []
+  mentions.value = []
+  text.value = ''
+  pendingRequestId = undefined
+  await router.push(`/conversations/${id}`)
+}
+async function openDialog(kind: NonNullable<typeof dialog.value>) {
+  error.value = ''
+  dialog.value = kind
+  Object.assign(form, {
+    name: '',
+    avatar: '',
+    instructions: '',
+    source: '',
+    memberIds: [],
+    administratorId: '',
+    mode: 'host',
+    autoReplyIds: [],
+    maxReplyRounds: 3,
+  })
+  try {
+    if (kind === 'agent') {
+      const s = await apiRequest<{ sources: Source[] }>('/api/app/agents/sources')
+      sources.value = s.sources
+      form.source = s.sources[0] ? JSON.stringify([s.sources[0].nodeId, s.sources[0].profile]) : ''
+    }
+    if (kind === 'editAgent') {
+      const a = members.value[0]
+      if (!a) return
+      editingId.value = a.id
+      Object.assign(form, a)
+    }
+    if (kind === 'editGroup' && active.value) {
+      editingId.value = active.value.id
+      Object.assign(form, active.value, {
+        memberIds: [...active.value.memberIds],
+        autoReplyIds: [...active.value.autoReplyIds],
+      })
+    }
+    await nextTick()
+    dialogElement.value?.showModal()
+  } catch (e) {
+    error.value = String(e)
+    dialog.value = null
+  }
+}
+function closeDialog() {
+  dialogElement.value?.close()
+  dialog.value = null
+}
+watch(
+  () => form.memberIds.slice(),
+  (ids) => {
+    if (!ids.includes(form.administratorId)) form.administratorId = ids[0] ?? ''
+    form.autoReplyIds = form.autoReplyIds.filter((id) => ids.includes(id))
+  },
+)
+async function avatarChanged(event: Event) {
+  const file = (event.target as HTMLInputElement).files?.[0]
+  if (!file) return
+  if (file.size > 2 * 1024 * 1024) {
+    error.value = '头像请小于 2 MB'
+    return
+  }
+  form.avatar = await new Promise<string>((resolve, reject) => {
+    const r = new FileReader()
+    r.onload = () => resolve(String(r.result))
+    r.onerror = reject
+    r.readAsDataURL(file)
+  })
+}
+async function save() {
+  busy.value = true
+  error.value = ''
+  try {
+    const fields = { name: form.name, avatar: form.avatar, instructions: form.instructions }
+    if (dialog.value === 'agent') {
+      const [nodeId, profile] = JSON.parse(form.source)
+      const result = await apiRequest<{ agent: Agent }>('/api/app/agents', {
+        method: 'POST',
+        body: { ...fields, nodeId, profile },
+      })
+      await refresh()
+      const c = conversations.value.find(
+        (c) => c.kind === 'direct' && c.memberIds[0] === result.agent.id,
+      )
+      if (c) await select(c.id)
+    } else if (dialog.value === 'editAgent')
+      await apiRequest(`/api/app/agents/${editingId.value}`, { method: 'PATCH', body: fields })
+    else {
+      const payload = {
+        ...fields,
+        administratorId: form.administratorId,
+        mode: form.mode,
+        autoReplyIds: form.autoReplyIds,
+        maxReplyRounds: form.maxReplyRounds,
+        ...(dialog.value === 'group' ? { memberIds: form.memberIds } : {}),
+      }
+      const result = await apiRequest<{ conversation: Conversation }>(
+        dialog.value === 'group'
+          ? '/api/app/conversations'
+          : `/api/app/conversations/${editingId.value}`,
+        { method: dialog.value === 'group' ? 'POST' : 'PATCH', body: body(payload) },
+      )
+      await select(result.conversation.id)
+    }
+    closeDialog()
+    await refresh()
+    await load()
+  } catch (e) {
+    error.value = e instanceof Error ? e.message : '保存失败'
+  } finally {
+    busy.value = false
+  }
+}
+async function upload(event: Event) {
+  const picked = (event.target as HTMLInputElement).files
+  if (!picked?.length) return
+  busy.value = true
+  error.value = ''
+  try {
+    const data = new FormData()
+    for (const file of picked) data.append('files', file)
+    const r = await apiRequest<{ files: WorkspaceFile[] }>('/api/app/uploads', {
+      method: 'POST',
+      body: data,
+    })
+    files.value = [...files.value, ...r.files].slice(0, 8)
+  } catch (e) {
+    error.value = String(e)
+  } finally {
+    busy.value = false
+    ;(event.target as HTMLInputElement).value = ''
+  }
+}
+async function send() {
+  const c = active.value
+  if (!c || busy.value || c.activeRunId || (!text.value.trim() && !files.value.length)) return
+  busy.value = true
+  error.value = ''
+  pendingRequestId ??= crypto.randomUUID()
+  try {
+    await apiRequest(`/api/app/conversations/${c.id}/messages`, {
+      method: 'POST',
+      body: {
+        requestId: pendingRequestId,
+        content: text.value,
+        mentionIds: mentions.value,
+        fileIds: files.value.map((f) => f.id),
+      },
+    })
+    text.value = ''
+    files.value = []
+    mentions.value = []
+    pendingRequestId = undefined
+    await load(c.id, true)
+    await refresh()
+  } catch (e) {
+    error.value = e instanceof Error ? e.message : '发送失败'
+  } finally {
+    busy.value = false
+  }
+}
+watch([text, () => files.value.map((f) => f.id).join(), () => mentions.value.join()], () => {
+  if (!busy.value) pendingRequestId = undefined
+})
+async function action(operation: 'pin' | 'archive') {
+  const c = active.value
+  if (!c) return
+  try {
+    if (operation === 'pin')
+      await apiRequest(`/api/app/conversations/${c.id}`, {
+        method: 'PATCH',
+        body: { pinned: !c.pinned },
+      })
+    else
+      await apiRequest(
+        c.kind === 'direct'
+          ? `/api/app/agents/${c.memberIds[0]}`
+          : `/api/app/conversations/${c.id}`,
+        { method: 'PATCH', body: { archived: !c.archived } },
+      )
+    await refresh()
+    await load()
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+async function control(action: 'stop' | 'reconcile') {
+  if (!run.value) return
+  try {
+    await apiRequest(`/api/app/runs/${run.value.id}/${action}`, { method: 'POST', body: {} })
+    await load(undefined, true)
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+async function respond(i: Interaction, answer: string) {
+  try {
+    await apiRequest(`/api/app/interactions/${i.id}/respond`, { method: 'POST', body: { answer } })
+    await load(undefined, true)
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+async function loadOlder() {
+  const c = active.value
+  if (!c) return
+  try {
+    const r = await apiRequest<{ messages: Message[] }>(
+      `/api/app/conversations/${c.id}/messages?before=${messages.value[0]?.seq ?? 0}`,
+    )
+    messages.value = [...r.messages, ...messages.value]
+    older.value = r.messages.length === 100
+  } catch (e) {
+    error.value = String(e)
+  }
+}
+function rendered(m: Message) {
+  return m.content.replace(
+    /(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g,
+    (whole, label: string, path: string) => {
+      const file =
+        m.attachments.find((f) => f.sourcePath === path) ||
+        m.attachments.find((f) => path.split('/').at(-1) === f.name)
+      return file
+        ? `${label}(/api/app/files/${file.id}/${label.startsWith('!') ? 'preview' : 'download'})`
+        : whole
+    },
+  )
+}
+
+watch(selected, () => void load())
+onMounted(async () => {
+  try {
+    await apiRequest('/api/app/capabilities')
+    await refresh()
+    await load()
+    if (!disposed) void poll()
+  } catch (e) {
+    error.value = String(e)
+  }
+})
+onBeforeUnmount(() => {
+  disposed = true
+  generation++
+  if (timer) clearTimeout(timer)
+})
+</script>
+<template>
+  <WorkspaceShell
+    :user-name="auth.user?.username"
+    :profiles="auth.profiles"
+    :active-profile="auth.activeProfile"
+    :is-admin="auth.user?.role === 'admin'"
+    :upstream-ready="auth.upstreamReady"
+    :upstream-error="auth.upstreamError"
+    :theme="theme.resolvedTheme"
+    :theme-preference="theme.theme"
+    sidebar-title="聊天"
+    sidebar-context-title="聊天列表"
+    @logout="auth.logout"
+    @select-profile="auth.selectProfile"
+    @toggle-theme="theme.toggle"
+    @set-theme="theme.setTheme"
+  >
+    <template #sidebar-action
+      ><div class="new-actions">
+        <button @click="openDialog('agent')">+ 创建 Agent</button
+        ><button @click="openDialog('group')">+ 创建群聊</button
+        ><button @click="showNodes = true">节点</button>
+      </div></template
+    >
+    <template #sidebar
+      ><ConversationList :conversations="conversations" :selected="selected" @select="select"
+    /></template>
+    <template #mobile-sidebar
+      ><ConversationList :conversations="conversations" :selected="selected" @select="select"
+    /></template>
+    <section class="workspace-chat" aria-label="聊天">
+      <header v-if="active" class="chat-header">
+        <AgentAvatar :name="active.name" :avatar="active.avatar" :size="38" />
+        <div>
+          <h1>{{ active.name }}</h1>
+          <small>{{
+            active.kind === 'group' ? `${members.length} 位成员 · 成员已固定` : 'Agent 单聊'
+          }}</small>
+        </div>
+        <span class="spacer" /><button @click="action('pin')">
+          {{ active.pinned ? '取消置顶' : '置顶' }}</button
+        ><button @click="openDialog(active.kind === 'direct' ? 'editAgent' : 'editGroup')">
+          设置</button
+        ><button @click="action('archive')">{{ active.archived ? '恢复' : '归档' }}</button>
+      </header>
+      <p v-if="error" class="error" role="alert">
+        {{ error }} <button @click="error = ''" aria-label="关闭错误">×</button>
+      </p>
+      <div
+        v-if="active"
+        ref="scroller"
+        class="messages"
+        @scroll="
+          scroller &&
+          scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 40 &&
+          markRead()
+        "
+      >
+        <button v-if="older" class="older" @click="loadOlder">加载更早消息</button>
+        <p v-if="loading && !messages.length">正在加载…</p>
+        <article v-for="m in messages" :key="m.id" class="message" :class="m.role">
+          <small
+            >{{ m.role === 'user' ? '我' : m.agentName || '系统' }}
+            <time>{{
+              new Date(m.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
+            }}</time></small
+          >
+          <details v-if="m.reasoning">
+            <summary>思考过程</summary>
+            <p>{{ m.reasoning }}</p>
+          </details>
+          <MarkdownContent :content="rendered(m)" :streaming="m.status === 'streaming'" />
+          <details v-for="(tool, i) in m.tools" :key="i">
+            <summary>{{ tool.name || tool.tool_name || '工具' }} · {{ tool.status }}</summary>
+            <pre>{{ JSON.stringify(tool, null, 2) }}</pre>
+          </details>
+          <a
+            v-for="file in m.attachments"
+            :key="file.id"
+            class="file"
+            :href="`/api/app/files/${file.id}/download`"
+            target="_blank"
+            rel="noreferrer"
+            ><img
+              v-if="file.mimeType.startsWith('image/')"
+              :src="`/api/app/files/${file.id}/preview`"
+              :alt="file.name"
+            />{{ file.name }}</a
+          ><small v-if="m.status !== 'complete'" class="status">{{
+            {
+              queued: '等待中',
+              streaming: '正在回复…',
+              failed: '执行失败',
+              interrupted: '已停止',
+              uncertain: '执行状态待确认',
+            }[m.status]
+          }}</small>
+        </article>
+        <p v-if="!loading && !messages.length" class="chat-empty">
+          {{ active.kind === 'group' ? '向团队描述你希望完成的事。' : '发一条消息,开始协作。' }}
+        </p>
+      </div>
+      <div v-else class="welcome">
+        <AgentAvatar name="夭夭" :size="72" />
+        <h1>从一个角色开始</h1>
+        <p>创建专属 Agent,为它设置职责和规则。<br />让不同角色在同一个群聊中协作。</p>
+        <button @click="openDialog('agent')">创建 Agent</button>
+      </div>
+      <div v-if="active" class="composer-area">
+        <div v-for="i in interactions" :key="i.id" class="interaction">
+          <strong>{{ i.kind === 'approval' ? '需要审批' : '需要补充信息' }}</strong>
+          <p>{{ i.message }}</p>
+          <template v-if="i.kind === 'approval'"
+            ><button @click="respond(i, 'once')">允许本次</button
+            ><button @click="respond(i, 'deny')">拒绝</button></template
+          ><template v-else
+            ><input v-model="answers[i.id]" aria-label="补充信息" /><button
+              @click="respond(i, answers[i.id] || '')"
+            >
+              提交
+            </button></template
+          >
+        </div>
+        <div v-if="run" class="run-status">
+          {{
+            run.status === 'uncertain'
+              ? '执行状态待确认'
+              : run.status === 'waiting'
+                ? '等待你的确认'
+                : '正在协作'
+          }}<span>{{ run.error }}</span
+          ><button v-if="run.status === 'uncertain'" @click="control('reconcile')">核对状态</button
+          ><button @click="control('stop')">停止</button>
+        </div>
+        <div v-if="active.kind === 'group'" class="mentions">
+          <label v-for="a in members" :key="a.id"
+            ><input v-model="mentions" type="checkbox" :value="a.id" />@{{ a.name }}</label
+          >
+        </div>
+        <div v-if="files.length" class="uploads">
+          <button
+            v-for="f in files"
+            :key="f.id"
+            @click="files = files.filter((x) => x.id !== f.id)"
+          >
+            {{ f.name }} ×
+          </button>
+        </div>
+        <form class="composer" @submit.prevent="send">
+          <textarea
+            v-model="text"
+            :disabled="active.archived"
+            aria-label="消息"
+            :placeholder="active.archived ? '聊天已归档' : '输入消息…'"
+            @keydown.enter.exact.prevent="send"
+          />
+          <div>
+            <input ref="fileInput" hidden type="file" multiple @change="upload" /><button
+              type="button"
+              :disabled="busy || active.archived"
+              @click="fileInput?.click()"
+            >
+              附件</button
+            ><span class="spacer" /><small v-if="context"
+              >上下文 {{ context.context_percent ?? context.percent ?? '—' }}%</small
+            ><button
+              type="submit"
+              :disabled="
+                busy || !!active.activeRunId || active.archived || (!text.trim() && !files.length)
+              "
+            >
+              {{ busy ? '处理中…' : '发送' }}
+            </button>
+          </div>
+        </form>
+      </div>
+    </section>
+    <div
+      v-if="showNodes"
+      class="nodes-overlay"
+      role="dialog"
+      aria-modal="true"
+      aria-label="节点管理"
+    >
+      <div><button @click="showNodes = false">关闭</button><WorkspaceNodesPanel /></div>
+    </div>
+    <dialog v-if="dialog" ref="dialogElement" class="editor" @cancel.prevent="closeDialog">
+      <form @submit.prevent="save">
+        <header>
+          <h2>
+            {{ dialog === 'agent' ? '创建 Agent' : dialog === 'group' ? '创建群聊' : '编辑资料' }}
+          </h2>
+          <button type="button" aria-label="关闭" @click="closeDialog">×</button>
+        </header>
+        <p v-if="error" class="error" role="alert">{{ error }}</p>
+        <label>名称<input v-model="form.name" required maxlength="100" /></label
+        ><label
+          >头像<input
+            type="file"
+            accept="image/png,image/jpeg,image/webp"
+            @change="avatarChanged" /></label
+        ><AgentAvatar v-if="form.avatar" :name="form.name" :avatar="form.avatar" :size="48" /><label
+          v-if="dialog === 'agent'"
+          >基础 Agent<select v-model="form.source" required>
+            <option
+              v-for="s in sources"
+              :key="`${s.nodeId}:${s.profile}`"
+              :value="JSON.stringify([s.nodeId, s.profile])"
+            >
+              {{ s.name }} · {{ s.nodeId === 'local' ? '当前服务' : s.nodeId }}
+            </option></select
+          ><small v-if="!sources.length"
+            >没有可用的基础 Agent,请检查 Web 的 Hermes 连接。</small
+          ></label
+        ><label
+          >{{ isAgentDialog ? '角色提示词与规则' : '群规则'
+          }}<textarea
+            v-model="form.instructions"
+            rows="6"
+            maxlength="24000"
+            :placeholder="
+              isAgentDialog
+                ? '例如:你是代码审查员。重点检查正确性、边界情况和测试证据。'
+                : '所有成员共同遵守的协作规则'
+            "
+          />
+        </label>
+        <fieldset v-if="!isAgentDialog">
+          <legend>{{ dialog === 'group' ? '选择成员(创建后不可变更)' : '固定成员' }}</legend>
+          <label
+            v-for="a in agents.filter((a) =>
+              dialog === 'group' ? !a.archived : form.memberIds.includes(a.id),
+            )"
+            :key="a.id"
+            ><input
+              v-model="form.memberIds"
+              type="checkbox"
+              :value="a.id"
+              :disabled="dialog === 'editGroup'"
+            />{{ a.name }}</label
+          ><small v-if="agents.filter((a) => !a.archived).length < 2"
+            >至少需要两个 Agent 才能创建群聊。</small
+          >
+        </fieldset>
+        <template v-if="!isAgentDialog"
+          ><label
+            >管理员<select v-model="form.administratorId" required>
+              <option
+                v-for="a in agents.filter((a) => form.memberIds.includes(a.id))"
+                :key="a.id"
+                :value="a.id"
+              >
+                {{ a.name }}
+              </option>
+            </select></label
+          ><label
+            >协作方式<select v-model="form.mode">
+              <option value="host">管理员协调</option>
+              <option value="free">自由协作</option>
+            </select></label
+          >
+          <fieldset v-if="form.mode === 'free'">
+            <legend>未 @ 时自动回复</legend>
+            <label v-for="a in agents.filter((a) => form.memberIds.includes(a.id))" :key="a.id"
+              ><input v-model="form.autoReplyIds" type="checkbox" :value="a.id" />{{
+                a.name
+              }}</label
+            >
+          </fieldset>
+          <label
+            >自动协作轮数<input
+              v-model.number="form.maxReplyRounds"
+              type="number"
+              min="1"
+              max="100"
+              required /></label
+        ></template>
+        <footer>
+          <button type="button" @click="closeDialog">取消</button
+          ><button :disabled="busy || (!isAgentDialog && form.memberIds.length < 2)">
+            {{ busy ? '保存中…' : '保存' }}
+          </button>
+        </footer>
+      </form>
+    </dialog>
+  </WorkspaceShell>
+</template>
+<style scoped>
+.nodes-overlay {
+  position: fixed;
+  inset: 0;
+  z-index: 1000;
+  background: #0006;
+  display: grid;
+  place-items: center;
+}
+.nodes-overlay > div {
+  padding: 20px;
+  border-radius: 18px;
+  max-height: 85vh;
+  overflow: auto;
+  width: min(520px, 90vw);
+  background: var(--surface);
+}
+.new-actions {
+  display: flex;
+  gap: 4px;
+  flex-wrap: wrap;
+}
+.workspace-chat {
+  height: 100%;
+  min-height: 0;
+  display: flex;
+  flex-direction: column;
+  color: var(--text-primary);
+  background: var(--surface);
+}
+button {
+  cursor: pointer;
+  color: inherit;
+}
+.chat-header {
+  display: flex;
+  align-items: center;
+  gap: 12px;
+  padding: 17px 24px;
+  border-bottom: 1px solid var(--line);
+}
+h1 {
+  font-size: 18px;
+  margin: 0 0 4px;
+}
+small {
+  color: var(--text-muted);
+}
+.spacer {
+  flex: 1;
+}
+.chat-header button,
+.composer button,
+.run-status button,
+.interaction button,
+.editor button,
+.welcome button {
+  padding: 8px 13px;
+  border: 1px solid var(--line);
+  border-radius: 9px;
+  background: var(--surface-soft);
+}
+button:disabled {
+  opacity: 0.45;
+  cursor: default;
+}
+.messages {
+  flex: 1;
+  min-height: 0;
+  overflow: auto;
+  padding: 24px max(24px, calc((100% - 780px) / 2));
+  scrollbar-gutter: stable;
+}
+.message {
+  margin: 0 0 28px;
+  overflow-wrap: anywhere;
+}
+.message > small {
+  display: block;
+  margin-bottom: 9px;
+  font-size: 11px;
+}
+.message.user {
+  margin-left: 15%;
+  padding: 14px 18px;
+  background: var(--surface-soft);
+  border-radius: 17px;
+}
+.message time {
+  margin-left: 8px;
+  opacity: 0.7;
+}
+.message pre {
+  white-space: pre-wrap;
+  font-size: 11px;
+  max-height: 300px;
+  overflow: auto;
+}
+.message details {
+  margin: 8px 0;
+  font-size: 12px;
+  color: var(--text-secondary);
+}
+.message .file {
+  display: inline-flex;
+  vertical-align: top;
+  flex-direction: column;
+  max-width: 280px;
+  margin: 8px;
+  padding: 10px;
+  border: 1px solid var(--line);
+  border-radius: 12px;
+  color: inherit;
+  font-size: 12px;
+}
+.file img {
+  max-height: 240px;
+  max-width: 100%;
+  object-fit: contain;
+}
+.composer-area {
+  width: min(820px, 100%);
+  box-sizing: border-box;
+  align-self: center;
+  padding: 12px 24px 24px;
+}
+.composer {
+  border: 1px solid var(--line);
+  border-radius: 16px;
+  padding: 12px;
+  background: var(--surface);
+}
+.composer textarea {
+  resize: vertical;
+  width: 100%;
+  box-sizing: border-box;
+  min-height: 75px;
+  max-height: 220px;
+  border: 0;
+  background: transparent;
+  color: inherit;
+  font: inherit;
+  line-height: 1.6;
+  outline: none;
+}
+.composer > div {
+  display: flex;
+  align-items: center;
+  gap: 10px;
+}
+.mentions,
+.uploads {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 10px;
+  margin-bottom: 10px;
+  font-size: 12px;
+}
+.mentions label {
+  display: flex;
+  align-items: center;
+  gap: 3px;
+}
+.uploads button {
+  border: 1px solid var(--line);
+  border-radius: 8px;
+  padding: 7px;
+  background: var(--surface-soft);
+}
+.run-status {
+  display: flex;
+  gap: 10px;
+  align-items: center;
+  flex-wrap: wrap;
+  font-size: 12px;
+  margin-bottom: 10px;
+}
+.run-status span {
+  color: var(--text-muted);
+}
+.error {
+  padding: 12px 20px;
+  margin: 0;
+  background: color-mix(in srgb, var(--danger, #c64c4c) 10%, transparent);
+  color: var(--danger, #c64c4c);
+  font-size: 13px;
+}
+.error button {
+  float: right;
+  border: 0;
+  background: none;
+}
+.welcome {
+  flex: 1;
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  align-items: center;
+  text-align: center;
+  padding: 30px;
+  gap: 18px;
+}
+.welcome h1 {
+  font-size: 26px;
+}
+.welcome p {
+  line-height: 1.9;
+  color: var(--text-muted);
+}
+.chat-empty {
+  padding: 60px 20px;
+  text-align: center;
+  color: var(--text-muted);
+}
+.interaction {
+  border: 1px solid var(--line);
+  padding: 16px;
+  border-radius: 12px;
+  margin-bottom: 12px;
+  font-size: 13px;
+}
+.interaction button {
+  margin-right: 8px;
+}
+.older {
+  display: block;
+  margin: 0 auto 25px;
+  border: 0;
+  background: transparent;
+  color: var(--text-muted);
+}
+.editor {
+  border: 1px solid var(--line);
+  border-radius: 18px;
+  width: min(520px, calc(100vw - 48px));
+  max-height: 85vh;
+  overflow: auto;
+  background: var(--surface);
+  color: var(--text-primary);
+  padding: 25px;
+}
+.editor::backdrop {
+  background: #0006;
+}
+.editor header,
+.editor footer {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 12px;
+}
+.editor h2 {
+  font-size: 20px;
+}
+.editor label {
+  display: flex;
+  flex-direction: column;
+  gap: 7px;
+  margin: 15px 0;
+  font-size: 13px;
+}
+.editor input:not([type='checkbox']),
+.editor textarea,
+.editor select,
+.interaction input {
+  padding: 10px;
+  border: 1px solid var(--line);
+  border-radius: 8px;
+  background: var(--surface-soft);
+  color: inherit;
+  font: inherit;
+}
+.editor fieldset {
+  border: 1px solid var(--line);
+  border-radius: 10px;
+}
+.editor fieldset label {
+  flex-direction: row;
+  align-items: center;
+}
+.editor footer {
+  justify-content: flex-end;
+  margin-top: 25px;
+}
+.status {
+  margin-top: 8px;
+}
+@media (max-width: 700px) {
+  .chat-header {
+    padding: 12px;
+    gap: 8px;
+  }
+  .chat-header button {
+    padding: 6px;
+    font-size: 11px;
+  }
+  .messages {
+    padding: 18px 15px;
+  }
+  .composer-area {
+    padding: 10px 12px 16px;
+  }
+  .message.user {
+    margin-left: 8%;
+  }
+}
+</style>

+ 5 - 0
src/client/views/FilesView.vue

@@ -67,6 +67,10 @@ async function addMediaToComposer(media: PreviewMedia) {
 }
 
 async function openSource(item: UiLibraryItem) {
+  if (item.sourceWorkspaceConversationId) {
+    await router.push(`/conversations/${encodeURIComponent(item.sourceWorkspaceConversationId)}`)
+    return
+  }
   if (!item.sourceSessionId) return
   if (item.sourceProfile && auth.profiles.some(profile => profile.name === item.sourceProfile)) {
     auth.selectProfile(item.sourceProfile)
@@ -104,6 +108,7 @@ async function createChat() {
 }
 
 onMounted(() => {
+  files.profile = undefined
   void files.load(true)
   void chat.loadSessions(auth.activeProfile?.name)
   void chat.loadUnread(auth.activeProfile?.name)

+ 61 - 16
src/server/app.ts

@@ -1,4 +1,4 @@
-import { randomBytes } from 'node:crypto'
+import { randomBytes, createHash } from 'node:crypto'
 import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
 import { createServer as createHttpServer, type Server as HttpServer } from 'node:http'
 import { createServer as createHttpsServer } from 'node:https'
@@ -22,6 +22,11 @@ import {
 } from './security.js'
 import { UpstreamHttpError, UpstreamClient } from './upstream.js'
 import { UploadStore } from './uploads.js'
+import { WorkspaceStore } from './workspaceStore.js'
+import { WorkspaceNodes } from './workspaceGateway.js'
+import { WorkspaceRuntime } from './workspaceRuntime.js'
+import { WorkspaceAssets } from './workspaceAssets.js'
+import { workspaceRouter } from './workspaceRoutes.js'
 import { SystemUpdateManager } from './updateManager.js'
 import { PushCoordinator } from './pushCoordinator.js'
 import {
@@ -39,9 +44,7 @@ import {
 } from './allowedHostsConfiguration.js'
 import {
   ChatPushJobManager,
-  GroupPushEventWatcher,
   HermesChatNotificationResolver,
-  HermesGroupEventSource,
 } from './pushEvents.js'
 
 export interface ApplicationOptions {
@@ -62,6 +65,8 @@ export interface ApplicationOptions {
 }
 
 export interface ApplicationRuntime {
+  workspace: WorkspaceStore
+  workspaceRuntime: WorkspaceRuntime
   realtime: RealtimeAPI
   app: Koa
   config: ServerConfig
@@ -80,7 +85,6 @@ export interface ApplicationRuntime {
   allowedHostsConfiguration: AllowedHostsConfigurationManager
   pushEventCoordinator: PushCoordinatorEventAdapter
   chatPushJobs: ChatPushJobManager
-  groupPushEvents: GroupPushEventWatcher
   close(): void
 }
 
@@ -174,21 +178,34 @@ export function createApplication(options: ApplicationOptions = {}): Application
     isUserActive: userID => auth.isUserActive(userID),
     userAuthorizationVersion: userID => auth.pushAuthorizationVersion(userID),
   })
-  const pushEventCoordinator = new PushCoordinatorEventAdapter(push, upstreamSession)
+  const pushEventCoordinator = new PushCoordinatorEventAdapter(push)
   const chatPushJobs = new ChatPushJobManager(config, upstreamSession, pushEventCoordinator, {
     resolver: new HermesChatNotificationResolver(
       upstreamSession,
       (localUserID, prompt) => push.promptDigest(localUserID, prompt),
     ),
   })
-  const groupPushEvents = new GroupPushEventWatcher(
-    new HermesGroupEventSource(config, upstreamSession),
-    pushEventCoordinator,
-  )
+  // The application owns group events. No Dashboard plugin is queried.
+  const workspace = new WorkspaceStore(config.home)
+  const workspaceNodes = new WorkspaceNodes(workspace, config, { url: config.upstream, client: upstream, session: upstreamSession })
+  const workspaceRuntime = new WorkspaceRuntime(workspace, workspaceNodes, uploads, owner => auth.isUserActive(owner))
+  const workspaceAssets = new WorkspaceAssets(workspace, workspaceNodes, config.home)
+  workspaceRuntime.onMessage = (owner, message) => workspaceAssets.archive(owner, message)
+  workspaceRuntime.onNotify = (owner, c, run, message, interaction) => {
+    if (c.kind === 'group' && !push.isGroupSubscribed(owner,c.id)) return
+    push.enqueueNotification({ kind: interaction ? interaction.kind === 'approval' ? 'chat.approval.requested' : 'chat.clarification.requested' : run.status === 'failed' ? 'chat.failed' : 'chat.completed', eventID: `workspace:${interaction?.id ?? run.id}`, localUserID: owner, title: c.name, body: (interaction?.message || message?.content || run.error || '回复完成').slice(0,180), collapseID: `workspace:${c.id}`, data: { conversationId:c.id, workspace:'1' }, ...(c.kind === 'group' ? {roomID:c.id} : {}) })
+  }
   const realtime = new RealtimeAPI(config, auth, csrf, pairings, upstream, upstreamSession, {
     coordinator: pushEventCoordinator,
     resolver: new HermesChatNotificationResolver(upstreamSession, (user, prompt) => push.promptDigest(user, prompt)),
   })
+  realtime.broker.protectedSession = id => workspace.ownsUpstream(id)
+  realtime.broker.onNativeEvent = (owner, profile, storedId, frame) => {
+    if (!['message.complete', 'tool.complete', 'tool.completed', 'attachment.staged'].includes(frame.type)) return
+    const data = frame.payload ?? {}, text = JSON.stringify(data)
+    const messageId = String(data.row_id ?? data.message_id ?? data.id ?? createHash('sha256').update(text).digest('hex'))
+    void workspaceAssets.archiveText(owner, text, 'local', profile, storedId, messageId, frame.type === 'attachment.staged' ? 'user' : 'agent').catch(() => {})
+  }
   chatPushJobs.setTransportFactory(realtime.recoveryTransport, job => realtime.ownsPushJob(job.id))
   try {
     uploads.cleanupUncommitted()
@@ -242,15 +259,17 @@ export function createApplication(options: ApplicationOptions = {}): Application
     await next()
   })
   app.use(realtime.middleware())
-  app.use(bodyParser({
+  const parseBody = (limit: string) => bodyParser({
     encoding: 'utf-8',
     enableTypes: ['json'],
     parsedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
-    jsonLimit: '2mb',
+    jsonLimit: limit,
     onError: (error, ctx) => {
       throw new HttpError(ctx.status === 413 || (error as { status?: number }).status === 413 ? 413 : 400, 'Invalid JSON request body', 'invalid_json_body')
     },
-  }))
+  })
+  const ordinaryBody = parseBody('2mb'), workspaceBody = parseBody('4mb')
+  app.use((ctx,next) => (/^\/api\/app\/(agents|conversations)(\/|$)/.test(ctx.path) ? workspaceBody : ordinaryBody)(ctx,next))
   app.use(async (ctx, next) => {
     ctx.state.localAuth = auth
     ctx.state.upstreamSession = upstreamSession
@@ -295,7 +314,30 @@ export function createApplication(options: ApplicationOptions = {}): Application
     } else await next()
   })
 
+  const applicationRouter = workspaceRouter(workspace, workspaceRuntime, workspaceNodes, workspaceAssets, uploads, auth, push)
+  app.use(applicationRouter.routes())
+  app.use(async (ctx, next) => {
+    if (ctx.path.includes('/plugins/yaoyao') || ctx.path.startsWith('/api/app/groups')) throw new HttpError(410, '请使用新版聊天接口', 'retired_plugin_api')
+    const id = /\/sessions\/([^/]+)/.exec(ctx.path)?.[1]
+    if (id && workspace.ownsUpstream(decodeURIComponent(id))) throw new HttpError(404, '会话不存在', 'session_not_found')
+    await next()
+    // Native history is a separate surface, including search and profile projections.
+    if (ctx.path.includes('/sessions') || ctx.path.endsWith('/profiles')) {
+      let value: any = ctx.body
+      const buffered = Buffer.isBuffer(value)
+      try {
+        if (buffered) value = JSON.parse(value.toString())
+        const filter = (v: any): any => {
+          if (Array.isArray(v)) return v.filter(x => !x || typeof x !== 'object' || (x.source !== 'yaoyao_workspace' && !workspace.ownsUpstream(String(x.id ?? x.session_id ?? x.sessionId ?? '')))).map(filter)
+          if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k,x]) => [k, filter(x)]))
+          return v
+        }
+        ctx.body = buffered ? Buffer.from(JSON.stringify(filter(value))) : filter(value)
+      } catch { /* Preserve non-JSON error responses. */ }
+    }
+  })
   const router = createApiRouter({
+    workspace,
     config,
     csrf,
     upstream,
@@ -324,6 +366,8 @@ export function createApplication(options: ApplicationOptions = {}): Application
   })
 
   return {
+    workspace,
+    workspaceRuntime,
     realtime,
     app,
     config,
@@ -342,14 +386,16 @@ export function createApplication(options: ApplicationOptions = {}): Application
     allowedHostsConfiguration,
     pushEventCoordinator,
     chatPushJobs,
-    groupPushEvents,
     close: () => {
+      workspaceAssets.close()
+      workspaceRuntime.close()
+      workspaceNodes.close()
       upstream.close()
       realtime.close()
       chatPushJobs.stop()
-      groupPushEvents.stop()
       push.close()
       uploads.close()
+      workspace.close()
     },
   }
 }
@@ -370,12 +416,11 @@ export function createNodeServer(runtime: ApplicationRuntime): NodeServerRuntime
   const synchronizePushObservers = (enabled = runtime.push.isAnyProviderEnabled()) => {
     if (enabled) {
       runtime.chatPushJobs.start()
-      runtime.groupPushEvents.start()
     } else {
       runtime.chatPushJobs.stop()
-      runtime.groupPushEvents.stop()
     }
   }
+  runtime.workspaceRuntime.start()
   synchronizePushObservers()
   const removePushConfigurationListener = runtime.push.onEnabledChange(synchronizePushObservers)
   const removeWebSockets = runtime.realtime.rejectLegacyUpgrades(server)

+ 0 - 20
src/server/config.ts

@@ -41,7 +41,6 @@ export interface ServerConfig {
   insecureLan: boolean
   production: boolean
   superviseDashboard?: boolean
-  yaoyaoPluginSource?: string
   releaseSource?: string
   releaseRoot?: string
   allowRemoteUpdate?: boolean
@@ -56,7 +55,6 @@ export interface ServerConfig {
   allowedHostsSettings?: AllowedHostsConfigurationSnapshot
 }
 
-export const DEFAULT_YAOYAO_PLUGIN_SOURCE = 'https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao'
 export const DEFAULT_YAOYAO_RELEASE_SOURCE = 'https://git.samien.cn/samien/hermes-yaoyao.git'
 
 function flag(value: string | undefined): boolean {
@@ -83,22 +81,6 @@ function parseUpstream(value: string | undefined): URL {
   return upstream
 }
 
-function parsePluginSource(value: string | undefined): string {
-  const source = value?.trim() || DEFAULT_YAOYAO_PLUGIN_SOURCE
-  if (source.length > 2_048 || /[\u0000-\u001f\u007f]/.test(source)) {
-    throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE is invalid')
-  }
-  if (source.startsWith('https://') || source.startsWith('http://')) {
-    const url = new URL(source)
-    if (url.username || url.password) {
-      throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE must not contain credentials')
-    }
-  } else if (!source.startsWith('git@') && !source.startsWith('ssh://')) {
-    throw new Error('HERMES_YAOYAO_PLUGIN_SOURCE must be an HTTPS or SSH Git source')
-  }
-  return source
-}
-
 function parseReleaseSource(value: string | undefined): string {
   const source = value?.trim() || DEFAULT_YAOYAO_RELEASE_SOURCE
   if (source.length > 2_048 || /[\u0000-\u001f\u007f]/.test(source)) {
@@ -170,7 +152,6 @@ export function loadServerConfig(
   const allowInsecureLan = flag(env.HERMES_YAOYAO_ALLOW_INSECURE_LAN)
   const production = env.NODE_ENV === 'production'
   const superviseDashboard = flag(env.HERMES_YAOYAO_SUPERVISE_DASHBOARD)
-  const yaoyaoPluginSource = parsePluginSource(env.HERMES_YAOYAO_PLUGIN_SOURCE)
   const releaseSource = parseReleaseSource(env.HERMES_YAOYAO_RELEASE_SOURCE)
   const releaseRoot = resolve(env.HERMES_YAOYAO_RELEASE_ROOT?.trim() || `${homedir()}/.local/share/hermes-yaoyao`)
   const allowRemoteUpdate = flag(env.HERMES_YAOYAO_ALLOW_REMOTE_UPDATE)
@@ -208,7 +189,6 @@ export function loadServerConfig(
     insecureLan,
     production,
     superviseDashboard,
-    yaoyaoPluginSource,
     releaseSource,
     releaseRoot,
     allowRemoteUpdate,

+ 18 - 302
src/server/pushEventAdapter.ts

@@ -1,320 +1,36 @@
-import { createHash } from 'node:crypto'
-import type { UpstreamServiceSession } from './localAuth.js'
-import {
-  type ChatPushJob,
-  type ChatPushObservation,
-  type GroupWatchAnchor,
-  type GroupWatchReset,
-  type PushEventCoordinator,
-  type PushNotificationCandidate,
+import type {
+  ChatPushJob,
+  ChatPushObservation,
+  PushEventCoordinator,
+  PushNotificationCandidate,
 } from './pushEvents.js'
 import { PushCoordinator } from './pushCoordinator.js'
-import { notificationPlainText } from './notificationText.js'
 
-type JsonRecord = Record<string, unknown>
-
-function record(value: unknown): JsonRecord {
-  return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonRecord : {}
-}
-
-function values(value: unknown): unknown[] {
-  return Array.isArray(value) ? value : []
-}
-
-function text(value: unknown): string {
-  return typeof value === 'string' ? value.trim() : ''
-}
-
-function number(value: unknown): number | undefined {
-  const result = typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN
-  return Number.isFinite(result) ? result : undefined
-}
-
-function timestampMilliseconds(value: unknown): number | undefined {
-  const numeric = number(value)
-  if (numeric !== undefined) return numeric < 10_000_000_000 ? numeric * 1_000 : numeric
-  if (typeof value !== 'string') return undefined
-  const parsed = Date.parse(value)
-  return Number.isNaN(parsed) ? undefined : parsed
-}
-
-function summary(value: unknown, fallback: string): string {
-  return notificationPlainText(value, { fallback, maximum: 180 })
-}
-
-function collapseID(prefix: string, value: string): string {
-  return `${prefix}:${createHash('sha256').update(value, 'utf8').digest('base64url').slice(0, 32)}`
-}
-
-function parseResponse(body: Buffer): JsonRecord {
-  try { return record(JSON.parse(body.toString('utf8'))) } catch { throw new Error('Hermes returned invalid group reconciliation JSON') }
-}
-
-interface ReconciliationSubscription {
-  userId: string
-  roomId: string
-  startedAt: number
-  lastMessageSeq?: number
-}
-
-/**
- * Adapts the durable push store to the realtime observers. Cursor resets first
- * reconcile every active room from REST, then move to the server-provided
- * latest anchor. Existing processed event IDs make the replay idempotent.
- */
+/** Chat notifications and workspace events use Web-owned persistence. */
 export class PushCoordinatorEventAdapter implements PushEventCoordinator {
-  constructor(
-    readonly push: PushCoordinator,
-    readonly upstreamSession: UpstreamServiceSession,
-  ) {}
-
+  constructor(readonly push: PushCoordinator) {}
   observeChat(_observation: ChatPushObservation): void {}
   saveChatJob(job: ChatPushJob): void {
     if (this.push.isAnyProviderEnabled()) this.push.saveChatJob(job)
   }
-  completeChatJob(jobID: string): void { this.push.completeChatJob(jobID) }
+  completeChatJob(jobID: string): void {
+    this.push.completeChatJob(jobID)
+  }
   pendingChatJobs(): readonly ChatPushJob[] {
     return this.push.isAnyProviderEnabled() ? this.push.pendingChatJobs() : []
   }
   promptDigest(localUserID: string, prompt: string): string {
     return this.push.promptDigest(localUserID, prompt)
   }
-  canRecoverChatJob(job: ChatPushJob): boolean { return this.push.chatJobRecoveryAllowed(job) }
-  enqueueNotification(candidate: PushNotificationCandidate): 'enqueued' | 'duplicate' | 'ignored' {
-    if (!this.push.isAnyProviderEnabled()) return 'ignored'
-    if ('roomID' in candidate) {
-      if (candidate.messageSequence !== undefined) {
-        const lastSequence = this.push.groupSubscriptionLastMessageSeq(candidate.localUserID, candidate.roomID)
-        if (lastSequence !== undefined && candidate.messageSequence <= lastSequence) return 'ignored'
-        const result = this.push.enqueueNotification(candidate)
-        this.push.advanceGroupSubscriptionMessageSeq(
-          candidate.localUserID,
-          candidate.roomID,
-          candidate.messageSequence,
-        )
-        return result
-      } else {
-        const startedAt = this.push.groupSubscriptionStartedAt(candidate.localUserID, candidate.roomID)
-        if (startedAt === undefined || candidate.occurredAt === undefined || candidate.occurredAt + 2_000 < startedAt) {
-          return 'ignored'
-        }
-      }
-    }
-    return this.push.enqueueNotification(candidate)
-  }
-  groupWatchAnchor(): GroupWatchAnchor | undefined {
-    const anchor = this.push.groupWatchAnchor()
-    return anchor ? { epoch: anchor.epoch, cursor: anchor.cursor } : undefined
-  }
-  groupSubscribers(roomID: string): readonly string[] { return this.push.groupSubscribers(roomID) }
-  advanceGroupCursor(anchor: GroupWatchAnchor): void { this.push.advanceGroupCursor(anchor) }
-
-  async resetGroupCursor(reset: GroupWatchReset): Promise<GroupWatchAnchor> {
-    if (reset.reason !== 'initial') await this.reconcileGroups()
-    const anchor = this.push.resetGroupCursor(reset)
-    return { epoch: anchor.epoch, cursor: anchor.cursor }
-  }
-
-  async reconcileGroups(): Promise<void> {
-    const subscriptions = this.push.activeGroupSubscriptions().flatMap(item => {
-      const startedAt = Date.parse(item.updatedAt)
-      return Number.isNaN(startedAt) ? [] : [{
-        userId: item.userId,
-        roomId: item.roomId,
-        startedAt,
-        ...(item.lastMessageSeq !== undefined ? { lastMessageSeq: item.lastMessageSeq } : {}),
-      }]
-    })
-    const byRoom = new Map<string, ReconciliationSubscription[]>()
-    for (const subscription of subscriptions) {
-      byRoom.set(subscription.roomId, [...(byRoom.get(subscription.roomId) ?? []), subscription])
-    }
-    for (const [roomID, roomSubscriptions] of byRoom) {
-      await this.reconcileRoom(roomID, roomSubscriptions)
-    }
+  canRecoverChatJob(job: ChatPushJob): boolean {
+    return this.push.chatJobRecoveryAllowed(job)
   }
-
-  private async reconcileRoom(roomID: string, subscriptions: ReconciliationSubscription[]): Promise<void> {
-    const detailResponse = await this.upstreamSession.request(
-      `/api/plugins/yaoyao/v1/rooms/${encodeURIComponent(roomID)}`,
-    )
-    if (detailResponse.status < 200 || detailResponse.status >= 300) {
-      if (detailResponse.status === 404) {
-        for (const subscription of subscriptions) {
-          this.push.setGroupSubscription(subscription.userId, roomID, false)
-        }
-        return
-      }
-      throw new Error(`Unable to reconcile group ${roomID} (${detailResponse.status})`)
-    }
-    const detailPayload = parseResponse(detailResponse.body)
-    const detailData = record(detailPayload.data)
-    const room = record(detailPayload.room ?? detailData.room ?? detailPayload.data ?? detailPayload)
-    const roomName = text(room.name) || '团队'
-    await this.reconcileMessages(roomID, roomName, subscriptions)
-    await this.reconcileInteractions(roomID, roomName, subscriptions, room)
-  }
-
-  private async reconcileMessages(
-    roomID: string,
-    roomName: string,
-    subscriptions: ReconciliationSubscription[],
-  ): Promise<void> {
-    if (subscriptions.some(item => item.lastMessageSeq === undefined)) {
-      const baselineResponse = await this.upstreamSession.request(
-        `/api/plugins/yaoyao/v1/rooms/${encodeURIComponent(roomID)}/messages`,
-        { search: new URLSearchParams({ limit: '1' }) },
-      )
-      if (baselineResponse.status < 200 || baselineResponse.status >= 300) {
-        throw new Error(`Unable to establish group baseline for ${roomID} (${baselineResponse.status})`)
-      }
-      const baselinePayload = parseResponse(baselineResponse.body)
-      const baselineData = record(baselinePayload.data)
-      const baseline = values(
-        baselinePayload.items ?? baselinePayload.messages ?? baselineData.items ?? baselineData.messages,
-      ).map(record).reduce((maximum, message) => {
-        const sequence = number(message.seq ?? message.sequence)
-        return sequence !== undefined && Number.isSafeInteger(sequence) ? Math.max(maximum, sequence) : maximum
-      }, 0)
-      for (const subscription of subscriptions) {
-        if (subscription.lastMessageSeq !== undefined) continue
-        this.push.advanceGroupSubscriptionMessageSeq(subscription.userId, roomID, baseline)
-        subscription.lastMessageSeq = baseline
-      }
-    }
-    let afterSequence = Math.min(...subscriptions.map(item => item.lastMessageSeq ?? 0))
-    if (afterSequence === 0) {
-      const collected: JsonRecord[] = []
-      let beforeSequence: number | undefined
-      let complete = false
-      for (let page = 0; page < 200; page += 1) {
-        const search = new URLSearchParams({ limit: '100' })
-        if (beforeSequence !== undefined) search.set('beforeSeq', String(beforeSequence))
-        const messages = await this.fetchGroupMessages(roomID, search)
-        if (!messages.length) { complete = true; break }
-        collected.push(...messages)
-        const sequences = messages
-          .map(message => number(message.seq ?? message.sequence))
-          .filter((value): value is number => value !== undefined && Number.isSafeInteger(value))
-        if (messages.length < 100 || !sequences.length) { complete = true; break }
-        const nextBefore = Math.min(...sequences)
-        if (beforeSequence !== undefined && nextBefore >= beforeSequence) break
-        beforeSequence = nextBefore
-      }
-      if (!complete) throw new Error(`Group reconciliation exceeded the safe page limit for ${roomID}`)
-      const ordered = [...new Map(collected.map(message => [String(message.id ?? message.seq), message])).values()]
-        .sort((left, right) => Number(left.seq ?? left.sequence) - Number(right.seq ?? right.sequence))
-      this.processGroupMessages(roomID, roomName, subscriptions, ordered, 0)
-      return
-    }
-    for (let page = 0; page < 50; page += 1) {
-      const search = new URLSearchParams({ limit: '100' })
-      search.set('afterSeq', String(afterSequence))
-      const messages = await this.fetchGroupMessages(roomID, search)
-      if (!messages.length) return
-      const greatestSequence = this.processGroupMessages(
-        roomID, roomName, subscriptions, messages, afterSequence,
-      )
-      if (messages.length < 100 || greatestSequence <= afterSequence) return
-      afterSequence = greatestSequence
-    }
-    throw new Error(`Group reconciliation exceeded the safe page limit for ${roomID}`)
-  }
-
-  private async fetchGroupMessages(roomID: string, search: URLSearchParams): Promise<JsonRecord[]> {
-    const response = await this.upstreamSession.request(
-      `/api/plugins/yaoyao/v1/rooms/${encodeURIComponent(roomID)}/messages`,
-      { search },
+  enqueueNotification(candidate: PushNotificationCandidate): 'enqueued' | 'duplicate' | 'ignored' {
+    if (
+      'roomID' in candidate &&
+      !this.push.isGroupSubscribed(candidate.localUserID, candidate.roomID)
     )
-    if (response.status < 200 || response.status >= 300) {
-      throw new Error(`Unable to reconcile group messages for ${roomID} (${response.status})`)
-    }
-    const payload = parseResponse(response.body)
-    const data = record(payload.data)
-    return values(payload.items ?? payload.messages ?? data.items ?? data.messages).map(record)
-  }
-
-  private processGroupMessages(
-    roomID: string,
-    roomName: string,
-    subscriptions: ReconciliationSubscription[],
-    messages: JsonRecord[],
-    afterSequence: number,
-  ): number {
-    let greatestSequence = afterSequence
-    for (const message of messages) {
-      const sequence = number(message.seq ?? message.sequence)
-      const updatedAt = timestampMilliseconds(message.updatedAt ?? message.updated_at ?? message.createdAt ?? message.created_at)
-      if (sequence === undefined || !Number.isSafeInteger(sequence) || sequence <= afterSequence) continue
-      greatestSequence = Math.max(greatestSequence, sequence)
-      const senderKind = text(message.senderKind ?? message.sender_kind).toLowerCase()
-      const status = text(message.status).toLowerCase()
-      const messageID = text(message.id)
-      if (senderKind !== 'agent' || !messageID || (status !== 'completed' && status !== 'failed')) continue
-      for (const subscription of subscriptions) {
-        if (sequence <= (subscription.lastMessageSeq ?? 0)) continue
-        const kind = status === 'completed' ? 'group.message.completed' as const : 'group.message.failed' as const
-        const eventID = `group-message:${messageID}:${status}`
-        const sender = text(message.senderName ?? message.sender_name) || 'Agent'
-        const topicID = text(message.topicId ?? message.topic_id)
-        this.enqueueNotification({
-          eventID,
-          localUserID: subscription.userId,
-          kind,
-          title: `${roomName} · ${sender}`,
-          body: summary(message.error ?? message.content, status === 'completed' ? '打开夭夭查看团队消息' : '打开夭夭查看失败详情'),
-          collapseID: collapseID('group-message', messageID),
-          roomID,
-          messageSequence: sequence,
-          occurredAt: updatedAt,
-          ...(topicID ? { topicID } : {}),
-          data: {
-            version: '1', eventId: eventID, kind, roomId: roomID,
-            ...(topicID ? { topicId: topicID } : {}), messageId: messageID,
-          },
-        })
-      }
-    }
-    return greatestSequence
-  }
-
-  private async reconcileInteractions(
-    roomID: string,
-    roomName: string,
-    subscriptions: ReconciliationSubscription[],
-    room: JsonRecord,
-  ): Promise<void> {
-    const interactions = values(room.pendingInteractions ?? room.pending_interactions)
-      .map(record)
-    for (const interaction of interactions) {
-      const status = text(interaction.status).toLowerCase()
-      const interactionID = text(interaction.id)
-      const updatedAt = timestampMilliseconds(
-        interaction.updatedAt ?? interaction.updated_at ?? interaction.createdAt ?? interaction.created_at,
-      )
-      if (!interactionID || status && status !== 'pending' || updatedAt === undefined) continue
-      const interactionKind = text(interaction.kind).toLowerCase()
-      const clarification = interactionKind === 'clarification'
-      const payload = record(interaction.payload)
-      const topicID = text(interaction.topicId ?? interaction.topic_id)
-      const eventID = `group-interaction:${interactionID}`
-      for (const subscription of subscriptions) {
-        if (updatedAt + 2_000 < subscription.startedAt) continue
-        this.push.enqueueNotification({
-          eventID,
-          localUserID: subscription.userId,
-          kind: 'group.interaction.requested',
-          title: clarification ? `${roomName} · 需要补充信息` : `${roomName} · 请求审批`,
-          body: summary(payload.question ?? payload.message ?? payload.prompt, '请打开夭夭继续处理'),
-          collapseID: collapseID('group-interaction', interactionID),
-          roomID,
-          ...(topicID ? { topicID } : {}),
-          data: {
-            version: '1', eventId: eventID, kind: 'group.interaction.requested', roomId: roomID,
-            ...(topicID ? { topicId: topicID } : {}), interactionId: interactionID,
-          },
-        })
-      }
-    }
+      return 'ignored'
+    return this.push.isAnyProviderEnabled() ? this.push.enqueueNotification(candidate) : 'ignored'
   }
 }

+ 0 - 263
src/server/pushEvents.ts

@@ -146,10 +146,6 @@ export interface PushEventCoordinator {
   promptDigest?(localUserID: string, prompt: string): MaybePromise<string>
   canRecoverChatJob?(job: ChatPushJob): MaybePromise<boolean>
   enqueueNotification(candidate: PushNotificationCandidate): MaybePromise<'enqueued' | 'duplicate' | 'ignored' | void>
-  groupWatchAnchor(): MaybePromise<GroupWatchAnchor | undefined>
-  groupSubscribers(roomID: string): MaybePromise<readonly string[]>
-  advanceGroupCursor(anchor: GroupWatchAnchor): MaybePromise<void>
-  resetGroupCursor(reset: GroupWatchReset): MaybePromise<GroupWatchAnchor | void>
 }
 
 /** Keep the event pipeline decoupled from the concrete persistent coordinator. */
@@ -161,10 +157,6 @@ export function createPushEventCoordinator(push: PersistentPushCoordinator): Pus
     promptDigest: (localUserID, prompt) => push.promptDigest(localUserID, prompt),
     canRecoverChatJob: job => push.chatJobRecoveryAllowed(job),
     enqueueNotification: candidate => push.enqueueNotification(candidate),
-    groupWatchAnchor: () => push.groupWatchAnchor(),
-    groupSubscribers: roomID => push.subscribedUserIds(roomID),
-    advanceGroupCursor: anchor => { push.advanceGroupCursor(anchor) },
-    resetGroupCursor: reset => push.resetGroupCursor(reset),
   }
 }
 
@@ -739,91 +731,6 @@ function terminalGroupCandidate(
 
 export type GroupEnvelopeResult = 'ready' | 'heartbeat' | 'advanced' | 'ignored' | 'reset'
 
-/** Applies strict epoch/cursor continuity and extracts only push-worthy events. */
-export class GroupPushEventProcessor {
-  #anchor: GroupWatchAnchor
-  readonly #recent = new Map<string, true>()
-
-  constructor(
-    anchor: GroupWatchAnchor,
-    readonly coordinator: PushEventCoordinator,
-    readonly recentLimit = 4_096,
-  ) {
-    this.#anchor = canonicalAnchor(anchor)
-  }
-
-  get anchor(): GroupWatchAnchor { return { ...this.#anchor } }
-
-  async accept(envelope: GroupEventEnvelope): Promise<GroupEnvelopeResult> {
-    if (envelope.type === 'group.reset_required') {
-      const proposed = canonicalAnchor({
-        epoch: string(envelope.epoch) || this.#anchor.epoch,
-        cursor: envelope.cursor ?? this.#anchor.cursor,
-      })
-      const recovered = await this.coordinator.resetGroupCursor({
-        ...proposed,
-        reason: string(envelope.reason) || 'server_reset',
-      })
-      this.#anchor = canonicalAnchor(recovered ?? proposed)
-      this.#recent.clear()
-      return 'reset'
-    }
-    if (envelope.epoch && envelope.epoch !== this.#anchor.epoch) {
-      throw new Error('Yaoyao group event epoch changed without reset')
-    }
-    if (envelope.type === 'group.ready') {
-      if (envelope.cursor !== this.#anchor.cursor) throw new Error('Yaoyao group ready cursor mismatch')
-      return 'ready'
-    }
-    if (envelope.type === 'group.heartbeat') {
-      if (envelope.cursor != null && envelope.cursor !== this.#anchor.cursor) {
-        throw new Error('Yaoyao group heartbeat cursor mismatch')
-      }
-      return 'heartbeat'
-    }
-    if (envelope.type !== 'group.event' || !Number.isSafeInteger(envelope.cursor) || envelope.cursor! < 0) {
-      throw new Error('Invalid Yaoyao group event envelope')
-    }
-    if (envelope.cursor! <= this.#anchor.cursor) return 'ignored'
-    if (envelope.cursor !== this.#anchor.cursor + 1) throw new Error('Yaoyao group event cursor gap')
-
-    const candidate = terminalGroupCandidate(envelope, this.#anchor)
-    if (candidate) {
-      const subscribers = [...new Set((await this.coordinator.groupSubscribers(candidate.roomID))
-        .map(value => value.trim()).filter(Boolean))]
-      for (const localUserID of subscribers) {
-        const dedupeKey = `${localUserID}:${candidate.eventID}`
-        if (this.#recent.has(dedupeKey)) continue
-        await this.coordinator.enqueueNotification({
-          ...candidate,
-          localUserID,
-          data: notificationData(candidate.eventID, candidate.kind, localUserID, {
-            roomId: candidate.roomID,
-            topicId: candidate.topicID,
-            messageId: candidate.messageID,
-            interactionId: candidate.interactionID,
-          }),
-        })
-        this.#remember(dedupeKey)
-      }
-    }
-    const next = { epoch: this.#anchor.epoch, cursor: envelope.cursor }
-    await this.coordinator.advanceGroupCursor(next)
-    this.#anchor = next
-    return 'advanced'
-  }
-
-  #remember(key: string): void {
-    this.#recent.delete(key)
-    this.#recent.set(key, true)
-    while (this.#recent.size > this.recentLimit) {
-      const oldest = this.#recent.keys().next().value as string | undefined
-      if (!oldest) break
-      this.#recent.delete(oldest)
-    }
-  }
-}
-
 export interface GroupEventConnection {
   close(): void
 }
@@ -1507,173 +1414,3 @@ export class ChatPushJobManager {
     }
   }
 }
-
-export class HermesGroupEventSource implements GroupEventSource {
-  constructor(
-    readonly config: ServerConfig,
-    readonly upstreamSession: UpstreamServiceSession,
-  ) {}
-
-  async currentAnchor(): Promise<GroupWatchAnchor> {
-    const response = await this.upstreamSession.request('/api/plugins/yaoyao/v1/capabilities')
-    if (response.status < 200 || response.status >= 300) throw new Error(`Yaoyao capabilities failed (${response.status})`)
-    const payload = parseUpstreamJSON(response.body)
-    const protocolVersion = Number(payload.protocolVersion ?? payload.protocol_version)
-    if (!isSupportedGroupProtocolVersion(protocolVersion)) throw new Error('Unsupported Yaoyao group protocol')
-    return canonicalAnchor({
-      epoch: string(payload.journalEpoch ?? payload.journal_epoch),
-      cursor: Number(payload.latestCursor ?? payload.latest_cursor),
-    })
-  }
-
-  async connect(
-    anchor: GroupWatchAnchor,
-    handlers: { onEnvelope(envelope: GroupEventEnvelope): void; onClose(error?: Error): void },
-  ): Promise<GroupEventConnection> {
-    const credential = await this.upstreamSession.webSocketCredential()
-    const url = new URL(this.config.upstream)
-    url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
-    const prefix = this.config.upstream.pathname === '/' ? '' : this.config.upstream.pathname.replace(/\/$/, '')
-    url.pathname = `${prefix}/api/plugins/yaoyao/v1/events`
-    url.search = ''
-    url.searchParams.set(credential.name, credential.value)
-    url.searchParams.set('epoch', anchor.epoch)
-    url.searchParams.set('cursor', String(anchor.cursor))
-
-    return await new Promise<GroupEventConnection>((resolve, reject) => {
-      const socket = new WebSocket(url, {
-        agent: this.upstreamSession.client.directAgent,
-        headers: { Origin: this.config.upstream.origin },
-        maxPayload: 2 * 1_024 * 1_024,
-        handshakeTimeout: 15_000,
-      })
-      let opened = false
-      let closed = false
-      socket.once('open', () => {
-        opened = true
-        resolve({ close: () => socket.close(1000, 'group push watcher close') })
-      })
-      socket.on('message', (data, isBinary) => {
-        if (isBinary) {
-          socket.close(1008, 'binary group frame')
-          return
-        }
-        try {
-          const value = record(JSON.parse(Buffer.from(data as Uint8Array).toString('utf8')))
-          handlers.onEnvelope({
-            type: string(value.type) as GroupEventEnvelope['type'],
-            epoch: string(value.epoch) || undefined,
-            cursor: value.cursor == null ? undefined : Number(value.cursor),
-            heartbeatSeconds: value.heartbeatSeconds == null && value.heartbeat_seconds == null
-              ? undefined : Number(value.heartbeatSeconds ?? value.heartbeat_seconds),
-            roomId: string(value.roomId ?? value.room_id) || undefined,
-            event: string(value.event) || undefined,
-            payload: value.payload,
-            reason: string(value.reason) || undefined,
-          })
-        } catch {
-          socket.close(1008, 'malformed group frame')
-        }
-      })
-      socket.once('unexpected-response', (_request, response) => {
-        const error = new Error(`Hermes rejected group WebSocket (${response.statusCode ?? 0})`)
-        response.resume()
-        if (!opened) reject(error)
-      })
-      socket.once('error', (error) => {
-        if (!opened) reject(error)
-      })
-      socket.once('close', (code, reason) => {
-        if (closed) return
-        closed = true
-        const error = code === 1000 ? undefined : new Error(reason.toString() || `Group WebSocket closed (${code})`)
-        if (!opened) reject(error ?? new Error('Group WebSocket closed before opening'))
-        else handlers.onClose(error)
-      })
-    })
-  }
-}
-
-export class GroupPushEventWatcher {
-  #running = false
-  #generation = 0
-  #retryAttempt = 0
-  #retryTimer?: ReturnType<typeof setTimeout>
-  #connection?: GroupEventConnection
-  #processor?: GroupPushEventProcessor
-  #frames = Promise.resolve()
-
-  constructor(
-    readonly source: GroupEventSource,
-    readonly coordinator: PushEventCoordinator,
-  ) {}
-
-  start(): void {
-    if (this.#running) return
-    this.#running = true
-    this.#generation += 1
-    void this.#open(this.#generation)
-  }
-
-  stop(): void {
-    this.#running = false
-    this.#generation += 1
-    if (this.#retryTimer) clearTimeout(this.#retryTimer)
-    this.#retryTimer = undefined
-    this.#connection?.close()
-    this.#connection = undefined
-  }
-
-  async #open(generation: number): Promise<void> {
-    try {
-      let anchor = await this.coordinator.groupWatchAnchor()
-      if (!anchor) {
-        anchor = await this.source.currentAnchor()
-        const restored = await this.coordinator.resetGroupCursor({ ...anchor, reason: 'initial' })
-        anchor = restored ?? anchor
-      }
-      if (!this.#running || generation !== this.#generation) return
-      this.#processor = new GroupPushEventProcessor(anchor, this.coordinator)
-      const connection = await this.source.connect(anchor, {
-        onEnvelope: envelope => this.#queueEnvelope(generation, envelope),
-        onClose: () => this.#scheduleReconnect(generation),
-      })
-      if (!this.#running || generation !== this.#generation || this.#connection) {
-        connection.close()
-        return
-      }
-      this.#connection = connection
-      this.#retryAttempt = 0
-    } catch {
-      this.#scheduleReconnect(generation)
-    }
-  }
-
-  #queueEnvelope(generation: number, envelope: GroupEventEnvelope): void {
-    this.#frames = this.#frames.then(async () => {
-      if (!this.#running || generation !== this.#generation || !this.#processor) return
-      const result = await this.#processor.accept(envelope)
-      if (result === 'reset') {
-        this.#connection?.close()
-        this.#connection = undefined
-        this.#scheduleReconnect(generation, 0)
-      }
-    }).catch(() => {
-      if (!this.#running || generation !== this.#generation) return
-      this.#connection?.close()
-      this.#connection = undefined
-      this.#scheduleReconnect(generation)
-    })
-  }
-
-  #scheduleReconnect(generation: number, delay?: number): void {
-    if (!this.#running || generation !== this.#generation || this.#retryTimer) return
-    this.#connection = undefined
-    const wait = delay ?? Math.min(15_000, 500 * 2 ** Math.min(this.#retryAttempt++, 5))
-    this.#retryTimer = setTimeout(() => {
-      this.#retryTimer = undefined
-      if (this.#running && generation === this.#generation) void this.#open(generation)
-    }, wait)
-    this.#retryTimer.unref()
-  }
-}

+ 2 - 2
src/server/realtimeApi.ts

@@ -71,7 +71,7 @@ export class RealtimeAPI {
         } else credential = await this.session.webSocketCredential()
         const url = new URL(this.config.upstream)
         url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
-        url.pathname = `${url.pathname.replace(/\/$/, '')}/api/${kind === 'chat' ? 'ws' : 'plugins/yaoyao/v1/events'}`
+        url.pathname = `${url.pathname.replace(/\/$/, '')}/api/ws`
         url.search = ''; url.searchParams.set(credential.name, credential.value)
         if (anchor) { url.searchParams.set('epoch', anchor.epoch); url.searchParams.set('cursor', String(anchor.cursor)) }
         return url
@@ -146,7 +146,7 @@ export class RealtimeAPI {
       ctx.set('Cache-Control', 'no-store')
       const path = match![2]!
       if (ctx.method === 'GET' && path === '/capabilities') {
-        ctx.body = { protocolVersion: 1, channels: ['chat', 'groups'], brokerEpoch: this.broker.epoch,
+        ctx.body = { protocolVersion: 1, channels: ['chat'], brokerEpoch: this.broker.epoch,
           ...(device ? {} : { csrfToken: this.csrf.issue(ctx) }) }
         return
       }

+ 25 - 28
src/server/realtimeBroker.ts

@@ -39,6 +39,8 @@ interface Upstream {
 
 /** Server-owned WS transports. Downstream detach never tears down an active upstream. */
 export class RealtimeBroker {
+  protectedSession: (id: string) => boolean = () => false
+  onNativeEvent: (owner: string, profile: string, storedId: string, frame: Frame) => void = () => {}
   readonly epoch = randomUUID()
   readonly channels = new Map<string, RealtimeChannel>()
   private upstreams = new Map<string, Upstream>()
@@ -54,6 +56,7 @@ export class RealtimeBroker {
   }
 
   async create(principal: RealtimePrincipal, kind: 'chat' | 'groups', group?: { epoch: string; cursor: number }): Promise<RealtimeChannel> {
+    if (String(kind) === 'groups') throw new HttpError(410, '请使用新版聊天事件接口', 'retired_group_stream')
     if (this.closed) throw new HttpError(503, 'Realtime broker is stopping', 'broker_stopping')
     principal.authorize?.(kind)
     if (!principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
@@ -72,10 +75,7 @@ export class RealtimeBroker {
       entries: [], routes: new Set(), listeners: new Set(), touched: this.now(), bytes: 0, group }
     this.channels.set(c.id, c)
     try {
-      if (kind === 'groups') {
-        if (!group) throw new HttpError(400, 'Group anchor is required', 'invalid_anchor')
-        await this.connectGroup(c)
-      } else {
+      {
         const u = this.upstream(principal)
         await this.connect(u)
         this.emit(c, 'frame', u.ready!)
@@ -133,6 +133,9 @@ export class RealtimeBroker {
     if (c.kind !== 'chat') throw new HttpError(403, 'Group event channel is read-only', 'read_only')
     const normalized = checkedChatFrame(Buffer.from(JSON.stringify(input)), false, c.principal.paired)
     const frame = JSON.parse(normalized) as Frame
+    if (Object.values(frame.params?.preferred_session_ids ?? {}).some(id => typeof id === 'string' && this.protectedSession(id))) {
+      throw new HttpError(404, '会话不存在', 'session_not_found')
+    }
     c.principal.authorize?.('chat', String(frame.method))
     delete frame.id
     const fingerprint = JSON.stringify(frame)
@@ -168,6 +171,7 @@ export class RealtimeBroker {
   private async perform(c: RealtimeChannel, frame: Frame): Promise<Frame> {
     const u = this.upstream(c.principal)
     const p = frame.params as Frame
+    if (p.session_id && this.protectedSession(String(p.session_id))) throw new HttpError(404, '会话不存在', 'session_not_found')
     const method = String(frame.method)
     const opening = method === 'session.create' || method === 'session.resume'
     if (opening && (c.routes.size >= 128 || u.routes.size >= 512)) throw new HttpError(429, 'Route capacity reached', 'route_limit')
@@ -231,8 +235,11 @@ export class RealtimeBroker {
         u.byRuntime.delete(route.runtime); u.routes.delete(this.routeKey(route.profile, route.stored))
         this.routeOwners.delete(JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, route.profile, route.stored]))
       }
+      if (route && response.result && ['file.attach','image.attach_bytes','pdf.attach'].includes(method) && c.principal.key.startsWith('user:')) {
+        this.onNativeEvent(c.principal.key.split(':')[1]!, route.profile, route.stored, { type:'attachment.staged', payload:response.result })
+      }
       u.lastUsed = this.now()
-      return response
+      return this.withoutProtectedSessions(response) ?? { result: {} }
     }
     if (['session.interrupt', 'approval.respond', 'clarify.respond', 'session.steer'].includes(method)) return execute()
     const work = (u.tails.get(routeKey) ?? Promise.resolve()).catch(() => {}).then(execute)
@@ -344,7 +351,10 @@ export class RealtimeBroker {
       while (this.interactions.size > 10_000) this.interactions.delete(this.interactions.keys().next().value!)
     }
     if (r) for (const principal of r.observers.values()) {
-      if (principal.valid()) principal.observeEvent?.(JSON.stringify(f))
+      if (principal.valid()) {
+        principal.observeEvent?.(JSON.stringify(f))
+        if (principal.key.startsWith('user:')) this.onNativeEvent(principal.key.split(':')[1]!, r.profile, r.stored, p)
+      }
     }
     for (const c of this.channels.values()) {
       if (c.kind !== 'chat' || c.principal.upstreamKey !== u.principal.upstreamKey || !c.principal.valid()) continue
@@ -380,29 +390,10 @@ export class RealtimeBroker {
     this.onActivity({ kind: 'reset', name: reason })
     for (const c of this.channels.values()) if (c.kind === 'chat' && c.principal.upstreamKey === u.principal.upstreamKey) this.emit(c, 'reset', { reason })
   }
-  private async connectGroup(c: RealtimeChannel): Promise<void> {
-    const url = await c.principal.url('groups', c.group)
-    const validator = new GroupFrameValidator(c.group!.epoch, c.group!.cursor)
-    await new Promise<void>((resolve, reject) => {
-      const ws = new WebSocket(url, { agent: c.principal.agent, headers: { Origin: `${url.protocol === 'wss:' ? 'https:' : 'http:'}//${url.host}` }, maxPayload: 2 * 1024 * 1024, handshakeTimeout: 15_000 })
-      c.socket = ws
-      const timer = setTimeout(() => { ws.terminate(); reject(new Error('Group ready timeout')) }, 20_000)
-      ws.on('message', (data, binary) => {
-        try {
-          if (!validator.accept(data, binary)) return
-          const frame = JSON.parse(data.toString()) as Frame
-          this.onActivity({ kind: 'group', name: String(frame.event ?? frame.type), roomId: frame.roomId })
-          if (frame.type === 'group.ready') { clearTimeout(timer); resolve() }
-          if (frame.type === 'group.event') c.group!.cursor = frame.cursor
-          this.emit(c, 'frame', frame)
-        } catch { this.emit(c, 'reset', { reason: 'group_gap' }); ws.close() }
-      })
-      ws.on('error', () => { clearTimeout(timer); reject(new Error('Group connection failed')) })
-      ws.on('close', () => { clearTimeout(timer); reject(new Error('Group disconnected')); this.onActivity({ kind: 'group', name: 'group_disconnected' }); if (this.channels.has(c.id)) this.emit(c, 'reset', { reason: 'group_disconnected' }) })
-    })
-  }
   private emit(c: RealtimeChannel, event: StreamEntry['event'], value: Frame): void {
-    const data = JSON.stringify(value)
+    const publicValue = this.withoutProtectedSessions(value)
+    if (!publicValue) return
+    const data = JSON.stringify(publicValue)
     const entry: StreamEntry = { id: `${this.epoch}:${++c.seq}`, event, data, at: this.now(), bytes: Buffer.byteLength(data) }
     c.entries.push(entry); c.bytes += entry.bytes
     this.trim(c)
@@ -410,6 +401,12 @@ export class RealtimeBroker {
       try { listener(entry) } catch { c.listeners.delete(listener) }
     }
   }
+  private withoutProtectedSessions(value: any): any {
+    if (Array.isArray(value)) return value.map(v => this.withoutProtectedSessions(v)).filter(v => v !== undefined)
+    if (!value || typeof value !== 'object') return value
+    if (value.source === 'yaoyao_workspace' || ['id','session_id','sessionId','stored_session_id','session_key'].some(k => typeof value[k] === 'string' && this.protectedSession(value[k]))) return undefined
+    return Object.fromEntries(Object.entries(value).map(([k,v]) => [k,this.withoutProtectedSessions(v)]).filter(([,v]) => v !== undefined))
+  }
   private trim(c: RealtimeChannel): void {
     const own = [...this.channels.values()].filter(v => v.principal.key === c.principal.key)
     while (own.reduce((n, v) => n + v.bytes, 0) > 8 * 1024 * 1024 || own.reduce((n, v) => n + v.entries.length, 0) > 10_000) {

+ 1 - 3
src/server/releases.ts

@@ -4,7 +4,6 @@ export interface ReleaseManifest {
   schemaVersion: 1
   releaseVersion: string
   webVersion: string
-  pluginVersion: string
   gitTag: string
 }
 
@@ -25,11 +24,10 @@ export function parseReleaseManifest(value: unknown): ReleaseManifest {
   if (input.schemaVersion !== 1) throw new Error('release.json schemaVersion 必须为 1')
   const releaseVersion = version(input.releaseVersion, 'releaseVersion')
   const webVersion = version(input.webVersion, 'webVersion')
-  const pluginVersion = version(input.pluginVersion, 'pluginVersion')
   const gitTag = typeof input.gitTag === 'string' ? input.gitTag : ''
   if (releaseVersion !== webVersion) throw new Error('releaseVersion 与 webVersion 必须一致')
   if (gitTag !== `v${releaseVersion}`) throw new Error('gitTag 必须与 releaseVersion 一致')
-  return { schemaVersion: 1, releaseVersion, webVersion, pluginVersion, gitTag }
+  return { schemaVersion: 1, releaseVersion, webVersion, gitTag }
 }
 
 export function readReleaseManifest(path: string): ReleaseManifest {

+ 31 - 710
src/server/routes.ts

@@ -1,4 +1,6 @@
 import type Koa from 'koa'
+import type { WorkspaceStore } from './workspaceStore.js'
+import type { WorkspaceConversation } from '../shared/workspace.js'
 import Router from '@koa/router'
 import { parse } from 'cookie'
 import { createReadStream, realpathSync, statSync } from 'node:fs'
@@ -6,7 +8,7 @@ import { basename, resolve, sep } from 'node:path'
 import { lookup as mimeLookup } from 'mime-types'
 import { isSupportedGroupProtocolVersion, SUPPORTED_GROUP_PROTOCOL_VERSION_LABEL } from '../shared/types.js'
 import type { ServerConfig } from './config.js'
-import { DEFAULT_YAOYAO_PLUGIN_SOURCE, isLoopbackHost, isLoopbackUpstream, isPrivateHost } from './config.js'
+import { isLoopbackHost, isLoopbackUpstream, isPrivateHost } from './config.js'
 import { HttpError } from './errors.js'
 import { compareReleaseVersions } from './releases.js'
 import {
@@ -48,6 +50,7 @@ import {
 type JsonObject = Record<string, unknown>
 
 export interface RouteDependencies {
+  workspace: WorkspaceStore
   config: ServerConfig
   csrf: CsrfProtection
   upstream: UpstreamClient
@@ -79,20 +82,6 @@ function optionalBody(ctx: Koa.Context): JsonObject | undefined {
     : undefined
 }
 
-async function boundedRawBody(ctx: Koa.Context, maximum: number): Promise<Buffer> {
-  const chunks: Buffer[] = []
-  let size = 0
-  for await (const raw of ctx.req) {
-    const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as Uint8Array)
-    size += chunk.byteLength
-    if (size > maximum) {
-      throw new HttpError(413, 'Paired node attachment is too large', 'node_attachment_too_large')
-    }
-    chunks.push(chunk)
-  }
-  if (size === 0) throw new HttpError(400, 'Paired node attachment is empty', 'invalid_node_attachment')
-  return Buffer.concat(chunks, size)
-}
 
 function parseJson(response: UpstreamResponse): JsonObject {
   try {
@@ -157,27 +146,13 @@ function normalizedProfiles(value: JsonObject): unknown[] {
   })
 }
 
-function profilesWithHermesBotNames(profiles: unknown[], pluginProfiles: JsonObject | undefined): unknown[] {
-  const items = Array.isArray(pluginProfiles?.profiles) ? pluginProfiles.profiles : []
-  const identities = new Map<string, string>()
-  for (const entry of items) {
-    if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
-    const profile = entry as JsonObject
-    const name = typeof profile.name === 'string' ? profile.name : ''
-    const botName = typeof profile.botName === 'string' ? profile.botName.trim() : ''
-    if (name && botName) identities.set(name, botName)
-  }
+function profilesWithCoreNames(profiles: unknown[]): unknown[] {
   return profiles.map(entry => {
     if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return entry
     const profile = entry as JsonObject
-    const name = typeof profile.name === 'string' ? profile.name : typeof profile.profile === 'string' ? profile.profile : ''
-    const agentName = identities.get(name)
-    return agentName ? {
-      ...profile,
-      agentName,
-      description: agentName,
-      display_name: agentName,
-    } : profile
+    const meta = profile.ui_meta as Record<string, any> | undefined
+    const title = meta?.['hermes-bots']?.title ?? profile.display_name
+    return typeof title === 'string' && title.trim() ? { ...profile, agentName:title.trim(), display_name:title.trim(), description:title.trim() } : profile
   })
 }
 
@@ -196,125 +171,6 @@ function publicStatus(status: JsonObject): JsonObject {
   }
 }
 
-async function yaoyaoPluginVersion(
-  dependencies: RouteDependencies,
-  jar: CookieJar,
-): Promise<string | undefined> {
-  const response = await dependencies.upstream.request('/api/dashboard/plugins', jar)
-  if (response.status < 200 || response.status >= 300) return undefined
-  const manifests = parseJsonValue(response)
-  if (!Array.isArray(manifests)) return undefined
-  const manifest = manifests.find(entry => (
-    entry && typeof entry === 'object' && !Array.isArray(entry)
-    && (entry as JsonObject).name === 'yaoyao'
-  )) as JsonObject | undefined
-  return typeof manifest?.version === 'string' ? manifest.version : undefined
-}
-
-async function requireYaoyaoStorageReady(
-  dependencies: RouteDependencies,
-  jar: CookieJar,
-  installedVersion?: string,
-): Promise<void> {
-  if (!installedVersion) return
-  const response = await dependencies.upstream.request(
-    '/api/plugins/yaoyao/maintenance/storage',
-    jar,
-  )
-  if (response.status < 200 || response.status >= 300) {
-    throw new HttpError(
-      409,
-      '当前夭夭插件尚未具备安全升级能力,请先按文档完成一次兼容版本安装',
-      'yaoyao_storage_migration_required',
-    )
-  }
-  const storage = parseJson(response)
-  if (storage.ready !== true) {
-    throw new HttpError(
-      409,
-      '检测到旧数据目录冲突,已停止升级以避免覆盖夭夭数据',
-      'yaoyao_storage_conflict',
-    )
-  }
-}
-
-let yaoyaoReconcileInFlight: Promise<JsonObject> | undefined
-
-function pluginVersionAtLeast(installed: string | undefined, expected: string): boolean {
-  if (!installed) return false
-  try {
-    return compareReleaseVersions(installed, expected) >= 0
-  } catch {
-    return installed === expected
-  }
-}
-
-async function reconcileYaoyaoPlugin(
-  dependencies: RouteDependencies,
-  jar: CookieJar,
-  clientAddress: string | undefined,
-  expectedVersion: string,
-): Promise<JsonObject> {
-  if (yaoyaoReconcileInFlight) return yaoyaoReconcileInFlight
-  const task = (async () => {
-    const installedVersion = await yaoyaoPluginVersion(dependencies, jar)
-    if (pluginVersionAtLeast(installedVersion, expectedVersion)) {
-      return {
-        ok: true,
-        updated: false,
-        installedPluginVersion: installedVersion,
-        expectedPluginVersion: expectedVersion,
-      }
-    }
-
-    await requireYaoyaoStorageReady(dependencies, jar, installedVersion)
-    const pluginSource = dependencies.config.yaoyaoPluginSource
-      ?? DEFAULT_YAOYAO_PLUGIN_SOURCE
-    const installedResult = requireSuccess(await dependencies.upstream.request(
-      '/api/dashboard/agent-plugins/install',
-      jar,
-      {
-        method: 'POST',
-        body: {
-          identifier: pluginSource,
-          force: Boolean(installedVersion),
-          enable: true,
-        },
-        clientAddress,
-      },
-    ))
-
-    let actualVersion: string | undefined
-    for (let attempt = 0; attempt < 20; attempt += 1) {
-      actualVersion = await yaoyaoPluginVersion(dependencies, jar)
-      if (pluginVersionAtLeast(actualVersion, expectedVersion)) break
-      await new Promise(resolvePromise => setTimeout(resolvePromise, 250))
-    }
-    if (!pluginVersionAtLeast(actualVersion, expectedVersion)) {
-      throw new HttpError(
-        502,
-        `9119 插件更新后版本仍不匹配:期望 ${expectedVersion},实际 ${actualVersion || '未安装'}`,
-        'yaoyao_plugin_version_mismatch',
-      )
-    }
-    return {
-      ...installedResult,
-      source: pluginSource,
-      updated: true,
-      installedPluginVersion: actualVersion,
-      expectedPluginVersion: expectedVersion,
-      restarted: false,
-      restartRequired: false,
-    }
-  })()
-  yaoyaoReconcileInFlight = task
-  try {
-    return await task
-  } finally {
-    if (yaoyaoReconcileInFlight === task) yaoyaoReconcileInFlight = undefined
-  }
-}
-
 export function systemUpdateRequestAllowed(address: string, allowRemoteUpdate = false): boolean {
   if (allowRemoteUpdate) return true
   return isLoopbackHost(address.replace(/^::ffff:/, ''))
@@ -413,21 +269,6 @@ function pushRequest<T>(operation: () => T): T {
   }
 }
 
-function bestEffortAutoSubscribe(
-  ctx: Koa.Context,
-  dependencies: RouteDependencies,
-  userID: string,
-  roomID: string,
-  baselineMessageSeq?: number,
-): void {
-  try {
-    dependencies.push.setGroupSubscription(userID, roomID, true, baselineMessageSeq)
-  } catch (cause) {
-    const detail = cause instanceof Error ? cause.message : String(cause)
-    ctx.app.emit('error', new Error(`团队消息已发送,但自动订阅推送失败:${detail}`), ctx)
-  }
-}
-
 function bestEffortRemoveUserPush(
   ctx: Koa.Context,
   dependencies: RouteDependencies,
@@ -441,44 +282,10 @@ function bestEffortRemoveUserPush(
   }
 }
 
-function groupMessageSequence(response: UpstreamResponse): number | undefined {
-  try {
-    const payload = parseJson(response)
-    const data = payload.data && typeof payload.data === 'object' && !Array.isArray(payload.data)
-      ? payload.data as JsonObject : {}
-    const message = payload.message && typeof payload.message === 'object' && !Array.isArray(payload.message)
-      ? payload.message as JsonObject
-      : data.message && typeof data.message === 'object' && !Array.isArray(data.message)
-        ? data.message as JsonObject : {}
-    const value = Number(message.seq ?? message.sequence)
-    return Number.isSafeInteger(value) && value >= 0 ? value : undefined
-  } catch {
-    return undefined
-  }
-}
-
-async function latestGroupMessageSequence(
-  dependencies: RouteDependencies,
-  roomID: string,
-): Promise<number> {
-  const response = await dependencies.upstreamSession.request(
-    `/api/plugins/yaoyao/v1/rooms/${encodeURIComponent(roomID)}/messages`,
-    { search: new URLSearchParams({ limit: '1' }) },
-  )
-  if (response.status === 404) throw new HttpError(404, '团队不存在', 'group_not_found')
-  const payload = requireSuccess(response)
-  const data = payload.data && typeof payload.data === 'object' && !Array.isArray(payload.data)
-    ? payload.data as JsonObject : {}
-  const rows = Array.isArray(payload.items) ? payload.items
-    : Array.isArray(payload.messages) ? payload.messages
-      : Array.isArray(data.items) ? data.items
-        : Array.isArray(data.messages) ? data.messages : []
-  const latest = rows.reduce((maximum, raw) => {
-    if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return maximum
-    const value = Number((raw as JsonObject).seq ?? (raw as JsonObject).sequence)
-    return Number.isSafeInteger(value) && value >= 0 ? Math.max(maximum, value) : maximum
-  }, 0)
-  return latest
+async function latestGroupMessageSequence(dependencies: RouteDependencies, roomID: string, owner: string): Promise<number> {
+  const room = dependencies.workspace.require<WorkspaceConversation>(owner, 'conversation', roomID)
+  if (room.kind !== 'group') throw new HttpError(404,'群聊不存在','group_not_found')
+  return room.lastSeq
 }
 
 function requestOrigin(ctx: Koa.Context, config: ServerConfig): string {
@@ -494,123 +301,6 @@ function pairingScopes(value: unknown): string[] | undefined {
   return value
 }
 
-async function addPairedChildNode(
-  qrPayload: string,
-  nameValue: string | undefined,
-  dependencies: RouteDependencies,
-): Promise<JsonObject> {
-  let deepLink: URL
-  try { deepLink = new URL(qrPayload.trim()) } catch {
-    throw new HttpError(400, '配对码格式无效', 'invalid_pairing_code')
-  }
-  if (deepLink.protocol !== 'yaoyao:' || deepLink.hostname !== 'pair' || deepLink.searchParams.get('v') !== '1') {
-    throw new HttpError(400, '这不是 8800 节点配对码', 'invalid_pairing_code')
-  }
-  const serviceValue = deepLink.searchParams.get('url') ?? ''
-  let serviceURL: URL
-  try { serviceURL = new URL(serviceValue) } catch {
-    throw new HttpError(400, '配对码缺少有效的 8800 地址', 'invalid_pairing_code')
-  }
-  if (!['http:', 'https:'].includes(serviceURL.protocol)
-    || serviceURL.username || serviceURL.password || serviceURL.search || serviceURL.hash
-    || (serviceURL.protocol === 'http:' && !isPrivateHost(serviceURL.hostname))) {
-    throw new HttpError(400, '子节点必须使用可信局域网 HTTP 或 HTTPS', 'invalid_node_url')
-  }
-  const requestJSON = async (url: URL, init?: RequestInit): Promise<JsonObject> => {
-    let response: Response
-    let timeout: ReturnType<typeof setTimeout> | undefined
-    try {
-      response = await Promise.race([
-        fetch(url, { ...init, redirect: 'error' }),
-        new Promise<never>((_resolve, reject) => {
-          timeout = setTimeout(() => reject(new Error('request timed out')), 20_000)
-          timeout.unref()
-        }),
-      ])
-    } catch (error) {
-      const reason = error instanceof Error ? error.message : 'connection failed'
-      throw new HttpError(502, `无法连接子 8800 节点:${reason}`, 'child_node_unavailable')
-    } finally {
-      if (timeout) clearTimeout(timeout)
-    }
-    let value: unknown
-    try { value = await response.json() } catch { value = undefined }
-    if (!response.ok || !value || typeof value !== 'object' || Array.isArray(value)) {
-      throw new HttpError(response.status || 502, '子节点拒绝了配对请求', 'child_node_rejected')
-    }
-    return value as JsonObject
-  }
-  const capabilities = await requestJSON(new URL('/api/pair/v1/capabilities', serviceURL))
-  if (capabilities.serviceType !== 'yaoyao-web') {
-    throw new HttpError(409, '子节点必须是 8800 夭夭 Web 服务', 'child_node_must_be_8800')
-  }
-  const pairingId = deepLink.searchParams.get('id') ?? ''
-  const secret = deepLink.searchParams.get('secret') ?? ''
-  const expectedNode = deepLink.searchParams.get('node') ?? ''
-  const expectedFingerprint = deepLink.searchParams.get('fingerprint') ?? ''
-  const claimed = await requestJSON(new URL('/api/pair/v1/claim', serviceURL), {
-    method: 'POST',
-    headers: { accept: 'application/json', 'content-type': 'application/json' },
-    body: JSON.stringify({ pairingId, secret, deviceName: '夭夭 8800 父节点' }),
-  })
-  if (claimed.serviceType !== 'yaoyao-web'
-    || claimed.nodeId !== expectedNode
-    || claimed.fingerprint !== expectedFingerprint
-    || typeof claimed.serverUrl !== 'string'
-    || typeof claimed.token !== 'string') {
-    throw new HttpError(502, '子节点身份与二维码不一致', 'child_node_identity_mismatch')
-  }
-  const nodeURL = new URL(claimed.serverUrl)
-  const profiles = await requestJSON(new URL(`${nodeURL.pathname.replace(/\/$/, '')}/api/profiles`, nodeURL), {
-    headers: { accept: 'application/json', authorization: `Bearer ${claimed.token}` },
-  })
-  let profileIdentities = new Map<string, JsonObject>()
-  try {
-    const identityPayload = await requestJSON(
-      new URL(`${nodeURL.pathname.replace(/\/$/, '')}/api/profile-identities`, nodeURL),
-      { headers: { accept: 'application/json', authorization: `Bearer ${claimed.token}` } },
-    )
-    profileIdentities = new Map(
-      (Array.isArray(identityPayload.profiles) ? identityPayload.profiles : [])
-        .flatMap(value => {
-          if (!value || typeof value !== 'object' || Array.isArray(value)) return []
-          const identity = value as JsonObject
-          return typeof identity.name === 'string' ? [[identity.name, identity] as const] : []
-        }),
-    )
-  } catch {
-    // Older 8800 nodes remain pairable; they simply use their REST names.
-  }
-  const profileItems = normalizedProfiles(profiles).flatMap(entry => {
-    if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return []
-    const value = entry as JsonObject
-    const name = typeof value.name === 'string' ? value.name : ''
-    if (!name) return []
-    const identity = profileIdentities.get(name)
-    return [{
-      name,
-      displayName: typeof identity?.displayName === 'string' ? identity.displayName
-        : typeof value.agentName === 'string' ? value.agentName
-        : typeof value.display_name === 'string' ? value.display_name : name,
-      model: typeof value.model === 'string' ? value.model : '',
-      ...(typeof identity?.avatar === 'string' ? { avatar: identity.avatar } : {}),
-      ...(typeof identity?.color === 'string' ? { color: identity.color } : {}),
-    }]
-  })
-  const registration = {
-    nodeId: claimed.nodeId,
-    name: nameValue?.trim() || nodeURL.host,
-    serverUrl: claimed.serverUrl,
-    fingerprint: claimed.fingerprint,
-    accessToken: claimed.token,
-    profiles: profileItems,
-  }
-  const response = await dependencies.upstreamSession.request('/api/plugins/yaoyao/v1/nodes', {
-    method: 'POST', body: registration,
-  })
-  return requireSuccess(response)
-}
-
 function pairedProxyScope(path: string, method: string): NodeScope {
   if (path === '/profiles' || path.startsWith('/profiles/')) {
     return path.includes('/sessions') ? 'history.read' : 'agents.read'
@@ -618,9 +308,6 @@ function pairedProxyScope(path: string, method: string): NodeScope {
   if (path === '/sessions' || path.startsWith('/sessions/')) {
     return ['GET', 'HEAD'].includes(method) ? 'history.read' : 'sessions.execute'
   }
-  if (path.startsWith('/plugins/yaoyao/v1/')) {
-    return ['GET', 'HEAD'].includes(method) ? 'groups.read' : 'groups.execute'
-  }
   return 'sessions.execute'
 }
 
@@ -639,7 +326,7 @@ function pairedProxyPath(rawPath: string): string {
     || path.startsWith('/models/')
     || path.startsWith('/files/')
     || path.startsWith('/attachments/')
-    || path.startsWith('/plugins/yaoyao/')
+
   if (!allowed) throw new HttpError(404, 'Paired node route is not available', 'node_route_not_found')
   return `/api${path}`
 }
@@ -940,7 +627,7 @@ async function bootstrap(
       profiles: [],
       csrfToken,
       insecureLan: dependencies.config.insecureLan,
-      groupUploadsEnabled: isLoopbackUpstream(dependencies.config.upstream),
+      groupUploadsEnabled: true,
       upstreamReady: false,
       serverKind: 'yaoyao-web',
     })
@@ -960,14 +647,10 @@ async function bootstrap(
           const statusResponse = await dependencies.upstreamSession.request('/api/status')
           const rawStatus = requireSuccess(statusResponse)
           const profilesResponse = await dependencies.upstreamSession.request('/api/profiles')
-          const pluginProfilesResponse = await dependencies.upstreamSession.request('/api/plugins/yaoyao/profiles')
+
           return {
             status: publicStatus(rawStatus),
-            profiles: profilesWithHermesBotNames(
-              normalizedProfiles(requireSuccess(profilesResponse)),
-              pluginProfilesResponse.status >= 200 && pluginProfilesResponse.status < 300
-                ? parseJson(pluginProfilesResponse) : undefined,
-            ),
+            profiles: profilesWithCoreNames(normalizedProfiles(requireSuccess(profilesResponse))),
           }
         })(),
         new Promise<never>((_resolve, reject) => {
@@ -992,7 +675,7 @@ async function bootstrap(
     profiles,
     csrfToken,
     insecureLan: dependencies.config.insecureLan,
-    groupUploadsEnabled: isLoopbackUpstream(dependencies.config.upstream),
+    groupUploadsEnabled: true,
     upstreamReady,
     upstreamError,
     serverKind: 'yaoyao-web',
@@ -1086,7 +769,7 @@ async function searchSessions(ctx: Koa.Context, dependencies: RouteDependencies)
     if (!text) throw new HttpError(400, 'q is required', 'missing_query')
     const limit = Math.max(1, Math.min(100, Number(query.get('limit') ?? '50') || 50))
     query.set('limit', String(limit))
-    if (!query.get('source')) query.set('exclude_sources', 'cron,ios_group')
+    if (!query.get('source')) query.set('exclude_sources', 'cron,ios_group,yaoyao_workspace')
     if (query.get('profile')) {
       const response = await dependencies.upstream.request('/api/sessions/search', jar, { search: query })
       sendUpstreamResponse(ctx, response, jar)
@@ -1121,11 +804,6 @@ async function searchSessions(ctx: Koa.Context, dependencies: RouteDependencies)
   })
 }
 
-function groupPath(ctx: Koa.Context, suffix = ''): string {
-  const roomID = canonicalUUID(ctx.params.roomID, 'room ID')
-  return `/api/plugins/yaoyao/v1/rooms/${roomID}${suffix}`
-}
-
 function localMediaPath(root: string, relativePath: string): string {
   let resolvedRoot: string
   let resolvedFile: string
@@ -1288,13 +966,9 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
   router.get('/api/profiles', async (ctx) => {
     dependencies.auth.require(ctx, true)
     const profilesResponse = await dependencies.upstreamSession.request('/api/profiles')
-    const pluginProfilesResponse = await dependencies.upstreamSession.request('/api/plugins/yaoyao/profiles')
+
     json(ctx, profilesResponse.status, {
-      profiles: profilesWithHermesBotNames(
-        normalizedProfiles(requireSuccess(profilesResponse)),
-        pluginProfilesResponse.status >= 200 && pluginProfilesResponse.status < 300
-          ? parseJson(pluginProfilesResponse) : undefined,
-      ),
+      profiles: profilesWithCoreNames(normalizedProfiles(requireSuccess(profilesResponse))),
     })
   })
   router.get('/api/push/v1/capabilities', (ctx) => {
@@ -1359,7 +1033,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
   })
   router.get('/api/push/v1/group-subscriptions', (ctx) => {
     const user = dependencies.auth.require(ctx)
-    const subscriptions = dependencies.push.listGroupSubscriptions(user.id)
+    const subscriptions = dependencies.push.listGroupSubscriptions(user.id).filter(s => dependencies.workspace.get<WorkspaceConversation>(user.id,'conversation',s.roomId)?.kind === 'group')
     json(ctx, 200, {
       subscriptions,
       roomIds: subscriptions.filter(item => item.enabled).map(item => item.roomId),
@@ -1373,7 +1047,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
     }
     const enabled = request.enabled
     const roomID = canonicalUUID(ctx.params.roomID, 'room ID')
-    const baseline = enabled ? await latestGroupMessageSequence(dependencies, roomID) : undefined
+    const baseline = enabled ? await latestGroupMessageSequence(dependencies, roomID, user.id) : undefined
     const subscription = pushRequest(() => dependencies.push.setGroupSubscription(
       user.id,
       roomID,
@@ -1394,7 +1068,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
   })
   router.get('/api/app/push/v1/group-subscriptions', (ctx) => {
     const user = dependencies.auth.require(ctx)
-    const subscriptions = dependencies.push.listGroupSubscriptions(user.id)
+    const subscriptions = dependencies.push.listGroupSubscriptions(user.id).filter(s => dependencies.workspace.get<WorkspaceConversation>(user.id,'conversation',s.roomId)?.kind === 'group')
     json(ctx, 200, {
       subscriptions,
       roomIds: subscriptions.filter(item => item.enabled).map(item => item.roomId),
@@ -1408,7 +1082,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
     }
     const enabled = request.enabled
     const roomID = canonicalUUID(ctx.params.roomID, 'room ID')
-    const baseline = enabled ? await latestGroupMessageSequence(dependencies, roomID) : undefined
+    const baseline = enabled ? await latestGroupMessageSequence(dependencies, roomID, user.id) : undefined
     const subscription = pushRequest(() => dependencies.push.setGroupSubscription(
       user.id,
       roomID,
@@ -1568,7 +1242,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
       nodeId: dependencies.pairings.nodeID,
       fingerprint: dependencies.pairings.fingerprint,
       scopes: [...DEFAULT_NODE_SCOPES],
-      features: ['bots', 'bot-group', 'native-group-worker', 'history'],
+      features: ['bots', 'history'],
     })
   })
 
@@ -1627,39 +1301,12 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
       throw new HttpError(414, 'Paired node query is too long', 'node_query_too_long')
     }
     const jar = new CookieJar(cookieHeader)
-    const isWorkerAttachment = ctx.method === 'POST'
-      && /\/plugins\/yaoyao\/v1\/node-worker\/sessions\/[^/]+\/attachments$/.test(path)
-      && ctx.get('content-type').split(';', 1)[0]?.trim().toLowerCase() === 'application/octet-stream'
-    let rawBody: BodyInit | undefined
-    let requestHeaders: Record<string, string> = {
-      'x-yaoyao-node-client': ctx.params.deviceID,
-    }
-    if (isWorkerAttachment) {
-      const encodedName = ctx.get('x-file-name-b64')
-      const mimeType = ctx.get('x-mime-type') || 'application/octet-stream'
-      if (!/^[A-Za-z0-9_-]{2,512}$/.test(encodedName)
-        || !/^[\x20-\x7e]{1,200}$/.test(mimeType)) {
-        throw new HttpError(400, 'Paired node attachment headers are invalid', 'invalid_node_attachment')
-      }
-      const buffer = await boundedRawBody(ctx, 25 * 1_024 * 1_024)
-      rawBody = buffer.buffer.slice(
-        buffer.byteOffset,
-        buffer.byteOffset + buffer.byteLength,
-      ) as ArrayBuffer
-      requestHeaders = {
-        ...requestHeaders,
-        'content-type': 'application/octet-stream',
-        'x-file-name-b64': encodedName,
-        'x-mime-type': mimeType,
-      }
-    }
     const response = await dependencies.upstream.withReadScope(`device:${ctx.params.deviceID}`, ctx.get('x-yaoyao-cache') === 'bypass', () => dependencies.upstream.request(path, jar, {
       method: ctx.method,
       search: new URLSearchParams(ctx.querystring),
-      body: ['GET', 'HEAD'].includes(ctx.method) || isWorkerAttachment
+      body: ['GET', 'HEAD'].includes(ctx.method)
         ? undefined : optionalBody(ctx),
-      rawBody,
-      headers: requestHeaders,
+      headers: { 'x-yaoyao-node-client': ctx.params.deviceID },
       clientAddress: path === '/api/auth/ws-ticket'
         ? undefined : ctx.req.socket.remoteAddress,
     }))
@@ -1984,14 +1631,6 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
       json(ctx, 200, { ok: true })
     })
   })
-  router.get('/api/app/admin/duplex-voice', async (ctx) => {
-    await proxyAdminFeature(ctx, dependencies, '/api/plugins/yaoyao/voice/settings')
-  })
-  router.put('/api/app/admin/duplex-voice', async (ctx) => {
-    await proxyAdminFeature(ctx, dependencies, '/api/plugins/yaoyao/voice/settings', {
-      method: 'PUT', requestBody: body(ctx),
-    })
-  })
   router.get('/api/app/system/update/status', async (ctx) => {
     dependencies.auth.requireAdmin(ctx)
     // No upstream calls, including best-effort plugin probes: a stalled 9119
@@ -2085,85 +1724,6 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
       throw updateFailure(error)
     }
   })
-  router.post('/api/app/plugins/yaoyao/reconcile', async (ctx) => {
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      json(ctx, 200, await reconcileYaoyaoPlugin(
-        dependencies,
-        jar,
-        ctx.req.socket.remoteAddress,
-        dependencies.updates.currentManifest().pluginVersion,
-      ))
-    })
-  })
-  router.post('/api/app/plugins/yaoyao/install', async (ctx) => {
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      const pluginSource = dependencies.config.yaoyaoPluginSource
-        ?? DEFAULT_YAOYAO_PLUGIN_SOURCE
-      const request = body(ctx)
-      if (request.force !== undefined && typeof request.force !== 'boolean') {
-        throw new HttpError(400, 'force must be a boolean', 'invalid_request')
-      }
-
-      const manifestsResponse = await dependencies.upstream.request(
-        '/api/dashboard/plugins',
-        jar,
-      )
-      if (manifestsResponse.status < 200 || manifestsResponse.status >= 300) {
-        sendUpstreamResponse(ctx, manifestsResponse, jar)
-        return
-      }
-      const manifests = parseJsonValue(manifestsResponse)
-      if (!Array.isArray(manifests)) {
-        throw new HttpError(502, 'Hermes returned an invalid plugin list', 'invalid_upstream_json')
-      }
-      const installed = manifests.some((entry) => (
-        entry && typeof entry === 'object' && !Array.isArray(entry)
-        && (entry as JsonObject).name === 'yaoyao'
-      ))
-
-      await requireYaoyaoStorageReady(
-        dependencies,
-        jar,
-        installed ? 'installed' : undefined,
-      )
-
-      const force = request.force === true
-      if (installed && !force) {
-        throw new HttpError(
-          409,
-          '夭夭已经安装;升级时必须明确传入 force=true',
-          'yaoyao_force_required',
-        )
-      }
-      const installResponse = await dependencies.upstream.request(
-        '/api/dashboard/agent-plugins/install',
-        jar,
-        {
-          method: 'POST',
-          body: {
-            identifier: pluginSource,
-            force,
-            enable: true,
-          },
-          clientAddress: ctx.req.socket.remoteAddress,
-        },
-      )
-      if (installResponse.status < 200 || installResponse.status >= 300) {
-        sendUpstreamResponse(ctx, installResponse, jar)
-        return
-      }
-      const installedResult = parseJson(installResponse)
-      json(ctx, 200, {
-        ...installedResult,
-        source: pluginSource,
-        restarted: false,
-        restartRequired: false,
-      })
-    })
-  })
-
   router.get('/api/app/profiles', async (ctx) => {
     await withJar(ctx, async (jar) => {
       const profilesResponse = await dependencies.upstream.request('/api/profiles', jar)
@@ -2171,13 +1731,8 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
         sendUpstreamResponse(ctx, profilesResponse, jar)
         return
       }
-      const pluginProfilesResponse = await dependencies.upstream.request('/api/plugins/yaoyao/profiles', jar)
-      const profiles = profilesWithHermesBotNames(
-        normalizedProfiles(parseJson(profilesResponse)),
-        pluginProfilesResponse.status >= 200 && pluginProfilesResponse.status < 300
-          ? parseJson(pluginProfilesResponse)
-          : undefined,
-      )
+
+      const profiles = profilesWithCoreNames(normalizedProfiles(parseJson(profilesResponse)))
       json(ctx, 200, { profiles })
     })
   })
@@ -2215,7 +1770,7 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
   })
   router.get('/api/app/sessions', async (ctx) => {
     const search = searchFrom(ctx, ['limit', 'offset', 'order', 'archived', 'profile', 'source'])
-    search.set('exclude_sources', 'cron,ios_group')
+    search.set('exclude_sources', 'cron,ios_group,yaoyao_workspace')
     const path = search.get('profile') ? '/api/sessions' : '/api/profiles/sessions'
     await proxy(ctx, dependencies.upstream, path, { search })
   })
@@ -2258,226 +1813,6 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
     })
   })
 
-  router.get('/api/app/groups/capabilities', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/capabilities')
-  })
-  router.get('/api/app/groups/nodes', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/nodes')
-  })
-  router.post('/api/app/groups/nodes', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/nodes', {
-      method: 'POST', requestBody: body(ctx),
-    })
-  })
-  router.post('/api/app/groups/nodes/pair', async (ctx) => {
-    dependencies.auth.requireAdmin(ctx)
-    const request = body(ctx)
-    const qrPayload = typeof request.qrPayload === 'string' ? request.qrPayload : ''
-    if (!qrPayload || qrPayload.length > 4_096) {
-      throw new HttpError(400, '请粘贴有效的 8800 配对码', 'invalid_pairing_code')
-    }
-    json(ctx, 201, await addPairedChildNode(
-      qrPayload,
-      typeof request.name === 'string' ? request.name : undefined,
-      dependencies,
-    ))
-  })
-  router.post('/api/app/groups/nodes/refresh-identities', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/nodes/refresh-identities', {
-      method: 'POST', requestBody: {},
-    })
-  })
-  router.delete('/api/app/groups/nodes/:nodeID', async (ctx) => {
-    const nodeID = canonicalUUID(ctx.params.nodeID, 'node ID')
-    await proxy(
-      ctx,
-      dependencies.upstream,
-      `/api/plugins/yaoyao/v1/nodes/${nodeID}`,
-      { method: 'DELETE', requestBody: body(ctx) },
-    )
-  })
-  router.get('/api/app/groups/rooms', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/rooms', {
-      search: searchFrom(ctx, ['limit', 'cursor', 'archived']),
-    })
-  })
-  router.get('/api/app/groups/topics/pinned', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/topics/pinned', {
-      search: searchFrom(ctx, ['limit']),
-    })
-  })
-  router.get('/api/app/groups/topics', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/topics', {
-      search: searchFrom(ctx, ['limit', 'cursor']),
-    })
-  })
-  router.post('/api/app/groups/rooms', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/v1/rooms', {
-      method: 'POST', requestBody: body(ctx),
-    })
-  })
-  router.get('/api/app/groups/rooms/:roomID', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, groupPath(ctx))
-  })
-  for (const method of ['patch', 'delete'] as const) {
-    router[method]('/api/app/groups/rooms/:roomID', async (ctx) => {
-      await proxy(ctx, dependencies.upstream, groupPath(ctx), {
-        method: method.toUpperCase(), requestBody: body(ctx),
-      })
-    })
-  }
-  router.post('/api/app/groups/rooms/:roomID/restore', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, '/restore'), {
-      method: 'POST', requestBody: body(ctx),
-    })
-  })
-  router.post('/api/app/groups/rooms/:roomID/agents', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, '/agents'), {
-      method: 'POST', requestBody: body(ctx),
-    })
-  })
-  for (const method of ['patch', 'delete'] as const) {
-    router[method]('/api/app/groups/rooms/:roomID/agents/:agentID', async (ctx) => {
-      const agentID = canonicalUUID(ctx.params.agentID, 'agent ID')
-      await proxy(ctx, dependencies.upstream, groupPath(ctx, `/agents/${agentID}`), {
-        method: method.toUpperCase(), requestBody: body(ctx),
-      })
-    })
-  }
-  router.post('/api/app/groups/rooms/:roomID/agents/:agentID/interrupt', async (ctx) => {
-    const agentID = canonicalUUID(ctx.params.agentID, 'agent ID')
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, `/agents/${agentID}/interrupt`), {
-      method: 'POST', requestBody: body(ctx),
-    })
-  })
-  router.get('/api/app/groups/rooms/:roomID/topics', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, '/topics'), {
-      search: searchFrom(ctx, ['limit', 'cursor', 'archived']),
-    })
-  })
-  router.patch('/api/app/groups/rooms/:roomID/topics/:topicID', async (ctx) => {
-    const topicID = canonicalUUID(ctx.params.topicID, 'topic ID')
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, `/topics/${topicID}`), {
-      method: 'PATCH', requestBody: body(ctx),
-    })
-  })
-  router.delete('/api/app/groups/rooms/:roomID/topics/:topicID', async (ctx) => {
-    const topicID = canonicalUUID(ctx.params.topicID, 'topic ID')
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, `/topics/${topicID}`), {
-      method: 'DELETE', requestBody: body(ctx),
-    })
-  })
-  router.post('/api/app/groups/rooms/:roomID/topics/:topicID/restore', async (ctx) => {
-    const topicID = canonicalUUID(ctx.params.topicID, 'topic ID')
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, `/topics/${topicID}/restore`), {
-      method: 'POST', requestBody: body(ctx),
-    })
-  })
-  router.patch('/api/app/groups/rooms/:roomID/topics/:topicID/read', async (ctx) => {
-    const topicID = canonicalUUID(ctx.params.topicID, 'topic ID')
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, `/topics/${topicID}/read`), {
-      method: 'PATCH', requestBody: body(ctx),
-    })
-  })
-  router.get('/api/app/groups/rooms/:roomID/messages', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, groupPath(ctx, '/messages'), {
-      search: searchFrom(ctx, ['topicId', 'beforeSeq', 'afterSeq', 'limit']),
-    })
-  })
-  router.post('/api/app/groups/rooms/:roomID/messages', async (ctx) => {
-    const localUser = dependencies.auth.require(ctx)
-    const subscribedRoomID = canonicalUUID(ctx.params.roomID, 'room ID')
-    const request = body(ctx)
-    const uploadIds = Array.isArray(request.uploadIds)
-      ? request.uploadIds.map((value) => String(value))
-      : []
-    const upstreamBody = { ...request }
-    delete upstreamBody.uploadIds
-    if (uploadIds.length) {
-      if (!isLoopbackUpstream(dependencies.config.upstream)) {
-        throw new HttpError(409, 'Group attachments require a loopback Hermes upstream', 'remote_upload_disabled')
-      }
-      const accountKey = requestAccountKey(ctx.req)
-      const records = dependencies.uploads.records(uploadIds, accountKey)
-      const content = typeof upstreamBody.content === 'string' ? upstreamBody.content.trim() : ''
-      upstreamBody.content = [content, uploadMarkdown(records)].filter(Boolean).join('\n\n')
-      await withJar(ctx, async (jar) => {
-        const response = await dependencies.upstream.request(groupPath(ctx, '/messages'), jar, {
-          method: 'POST', body: upstreamBody,
-        })
-        sendUpstreamResponse(ctx, response, jar)
-        if (response.status >= 200 && response.status < 300) {
-          dependencies.uploads.markReferenced(uploadIds, accountKey)
-          bestEffortAutoSubscribe(
-            ctx,
-            dependencies,
-            localUser.id,
-            subscribedRoomID,
-            groupMessageSequence(response),
-          )
-        }
-      })
-      return
-    }
-    await withJar(ctx, async (jar) => {
-      const response = await dependencies.upstream.request(groupPath(ctx, '/messages'), jar, {
-        method: 'POST', body: upstreamBody,
-      })
-      sendUpstreamResponse(ctx, response, jar)
-      if (response.status >= 200 && response.status < 300) {
-        bestEffortAutoSubscribe(
-          ctx,
-          dependencies,
-          localUser.id,
-          subscribedRoomID,
-          groupMessageSequence(response),
-        )
-      }
-    })
-  })
-  for (const action of ['approval', 'clarification'] as const) {
-    router.post(`/api/app/groups/rooms/:roomID/interactions/:interactionID/${action}`, async (ctx) => {
-      const interactionID = safeIdentifier(ctx.params.interactionID, 'interaction ID')
-      await proxy(
-        ctx,
-        dependencies.upstream,
-        groupPath(ctx, `/interactions/${encodeURIComponent(interactionID)}/${action}`),
-        { method: 'POST', requestBody: body(ctx) },
-      )
-    })
-  }
-
-  router.post('/api/app/group-uploads', async (ctx) => {
-    if (!isLoopbackUpstream(dependencies.config.upstream)) {
-      throw new HttpError(409, 'Group attachments require a loopback Hermes upstream', 'remote_upload_disabled')
-    }
-    await withJar(ctx, async (jar) => {
-      await requireGatewayAuthentication(ctx, dependencies, jar)
-      const accountKey = requestAccountKey(ctx.req)
-      const files = await receiveGroupUploads(ctx.req, dependencies.uploads, accountKey)
-      json(ctx, 201, { files })
-    })
-  })
-
-  router.get('/api/app/files', async (ctx) => {
-    await proxy(ctx, dependencies.upstream, '/api/plugins/yaoyao/files', {
-      search: searchFrom(ctx, ['limit', 'cursor', 'search', 'profile', 'kind', 'sender', 'session_id']),
-    })
-  })
-  for (const action of ['download', 'preview'] as const) {
-    router.get(`/api/app/files/:fileID/${action}`, async (ctx) => {
-      const id = safeIdentifier(ctx.params.fileID, 'file ID')
-      await proxy(ctx, dependencies.upstream, `/api/plugins/yaoyao/${encodeURIComponent(id)}/download`, {
-        search: searchFrom(ctx, ['profile']),
-        requestHeaders: ctx.get('range') ? { range: ctx.get('range') } : undefined,
-        maxResponseBytes: 256 * 1_024 * 1_024,
-      })
-      if (action === 'preview') {
-        prepareFilePreview(ctx, `file-${id}`)
-      }
-    })
-  }
-
   router.all('/api/*gatewayPath', async (ctx) => {
     if (ctx.path.startsWith('/api/app/') || ctx.path.startsWith('/api/pair/')) {
       throw new HttpError(404, 'Route not found', 'not_found')
@@ -2496,22 +1831,8 @@ export function createApiRouter(dependencies: RouteDependencies): Router {
       // phone's address here would make 9119 reject the ticket during Upgrade.
       clientAddress: upstreamPath === '/api/auth/ws-ticket'
         ? undefined : ctx.req.socket.remoteAddress,
-      maxResponseBytes: /\/plugins\/yaoyao\/v1\/nodes\/[0-9a-f-]{36}\/files$/.test(upstreamPath)
-        ? 256 * 1_024 * 1_024 : undefined,
+
     })
-    const nativeGroupMessage = ctx.method === 'POST'
-      ? /^\/api\/plugins\/yaoyao\/v1\/rooms\/([0-9a-f-]{36})\/messages$/.exec(upstreamPath)
-      : null
-    if (nativeGroupMessage && response.status >= 200 && response.status < 300) {
-      const localUser = dependencies.auth.require(ctx)
-      bestEffortAutoSubscribe(
-        ctx,
-        dependencies,
-        localUser.id,
-        canonicalUUID(nativeGroupMessage[1]!, 'room ID'),
-        groupMessageSequence(response),
-      )
-    }
     sendUpstreamResponse(ctx, response, dependencies.upstreamSession.jar)
   })
 

+ 4 - 8
src/server/updateManager.ts

@@ -60,8 +60,6 @@ interface StoredUpdateJob extends UpdateJob {
 
 export interface SystemUpdateStatus {
   current: ReleaseManifest
-  installedPluginVersion?: string
-  versionsMatch: boolean
   installationMode: 'source' | 'release'
   latest?: ReleaseManifest
   updateAvailable: boolean
@@ -254,13 +252,11 @@ export class SystemUpdateManager {
     return id ? this.storedJob(id) : undefined
   }
 
-  status(installedPluginVersion?: string, latest?: ReleaseManifest): SystemUpdateStatus {
+  status(latest?: ReleaseManifest): SystemUpdateStatus {
     const current = this.currentManifest()
     const job = this.latestJob()
     return {
       current,
-      installedPluginVersion,
-      versionsMatch: installedPluginVersion === current.pluginVersion,
       installationMode: this.projectRoot.startsWith(`${this.releaseRoot}/`) ? 'release' : 'source',
       latest,
       updateAvailable: Boolean(latest && compareReleaseVersions(latest.releaseVersion, current.releaseVersion) > 0),
@@ -271,10 +267,10 @@ export class SystemUpdateManager {
     }
   }
 
-  async check(installedPluginVersion?: string): Promise<SystemUpdateStatus> {
+  async check(): Promise<SystemUpdateStatus> {
     const current = this.currentManifest()
     const latest = await this.inspectRemote(this.releaseSource, current)
-    return this.status(installedPluginVersion, latest?.manifest)
+    return this.status(latest?.manifest)
   }
 
   private acquire(jobID: string): void {
@@ -351,7 +347,7 @@ export class SystemUpdateManager {
     return job
   }
 
-  async startUpdate(targetVersion: string, installedPluginVersion?: string): Promise<UpdateJob> {
+  async startUpdate(targetVersion: string): Promise<UpdateJob> {
     if (this.platform !== 'darwin') throw new Error('当前环境不支持服务内升级')
     const current = this.currentManifest()
     const latest = await this.inspectRemote(this.releaseSource, current)

+ 0 - 1
src/server/upstream.ts

@@ -187,7 +187,6 @@ export class UpstreamClient {
       } else response = await load()
       // Snapshot-after-anchor ordering: no room snapshot fetched before this fresh
       // journal cursor may be reused to bootstrap a stream starting at that cursor.
-      if (path === '/api/plugins/yaoyao/v1/capabilities' && response.status === 200) this.invalidateReads(['groups'])
       return response
     } finally {
       if (tags) this.invalidateReads(tags)

+ 2 - 15
src/server/upstreamReadCache.ts

@@ -97,7 +97,7 @@ function cacheable(value: UpstreamResponse): boolean {
 }
 
 export function readPolicy(path: string, search?: URLSearchParams): ReadPolicy | undefined {
-  if (path === '/api/profiles' || path === '/api/plugins/yaoyao/profiles') {
+  if (path === '/api/profiles') {
     return { tags: ['profiles'], freshMs: 5_000, staleMs: 15_000 }
   }
   if (path === '/api/model/options') return { tags: ['models'], freshMs: 30_000, staleMs: 60_000 }
@@ -109,17 +109,7 @@ export function readPolicy(path: string, search?: URLSearchParams): ReadPolicy |
     const oldPage = Number(search?.get('offset') ?? 0) > 0
     return { tags: ['sessions', `session:${decodeURIComponent(session[1]!)}`], freshMs: oldPage ? 10_000 : 1_000, staleMs: 0 }
   }
-  const base = '/api/plugins/yaoyao/v1'
-  if ([`${base}/rooms`, `${base}/topics`, `${base}/topics/pinned`].includes(path)) {
-    return { tags: ['groups', 'group-list'], freshMs: 2_000, staleMs: 0 }
-  }
-  const room = /^\/api\/plugins\/yaoyao\/v1\/rooms\/([^/]+)(?:\/(messages|topics))?$/.exec(path)
-  if (room) {
-    // Incremental reconciliation reads must never stop at a cached old tail.
-    if (search?.has('afterSeq')) return undefined
-    return { tags: ['groups', `group:${room[1]}`], freshMs: search?.has('beforeSeq') ? 10_000 : 1_000, staleMs: 0 }
-  }
-  return undefined
+
 }
 
 export function mutationTags(path: string): string[] | undefined {
@@ -127,9 +117,6 @@ export function mutationTags(path: string): string[] | undefined {
   const session = /^\/api\/sessions\/([^/]+)/.exec(path)
   if (session) return ['session-list', `session:${decodeURIComponent(session[1]!)}`]
   if (path.startsWith('/api/sessions')) return ['sessions']
-  const room = /^\/api\/plugins\/yaoyao\/v1\/rooms\/([^/]+)/.exec(path)
-  if (room) return ['group-list', `group:${room[1]}`]
-  if (path.startsWith('/api/plugins/yaoyao/v1/')) return ['groups']
   if (/^\/api\/(profiles|model|config|env|providers|dashboard\/agent-plugins)/.test(path)) return ['profiles', 'models', 'sessions', 'groups']
   return undefined
 }

+ 173 - 0
src/server/workspaceAssets.ts

@@ -0,0 +1,173 @@
+import { randomUUID, createHash } from 'node:crypto'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join, basename } from 'node:path'
+import { lookup } from 'mime-types'
+import { WorkspaceStore } from './workspaceStore.js'
+import { WorkspaceNodes } from './workspaceGateway.js'
+import type { WorkspaceAgent, WorkspaceFile, WorkspaceMessage } from '../shared/workspace.js'
+export interface StoredWorkspaceFile extends WorkspaceFile {
+  path: string
+  digest?: string
+}
+export function publicFile(f: StoredWorkspaceFile): WorkspaceFile {
+  const { path: _path, digest: _digest, ...result } = f
+  return result
+}
+export function libraryFile(
+  f: WorkspaceFile,
+  id: number,
+  conversation?: { id: string; name: string },
+) {
+  const path = `/api/app/files/${f.id}/download`
+  const origin = {
+    id,
+    sourceKind: f.sender === 'user' ? 'upload' : 'agent_generated',
+    eventKind: f.sender === 'user' ? 'uploaded' : 'generated',
+    username: '',
+    profile: f.profile ?? '',
+    agent: f.profile ?? '',
+    contextType: 'session',
+    sessionId: f.conversationId ?? '',
+    sessionTitle: conversation?.name ?? '',
+    workspaceConversationId: conversation?.id,
+    messageId: f.messageId ?? '',
+    runId: '',
+    workspace: '',
+    originalPath: path,
+    referencePath: path,
+    observedAt: f.createdAt,
+    messageTimestamp: f.createdAt,
+    authorKind: f.sender,
+  }
+  return {
+    ...f,
+    id,
+    itemId: id,
+    path,
+    extension: f.name.split('.').at(-1) ?? '',
+    modifiedAt: f.createdAt,
+    exists: true,
+    firstSeenAt: f.createdAt,
+    lastSeenAt: f.createdAt,
+    messageTimestamp: f.createdAt,
+    origins: [origin],
+    archiveStatus: 'ready',
+    availability: 'archived',
+    archivedAt: f.createdAt,
+    messageId: f.messageId ?? null,
+    sessionId: f.conversationId ?? null,
+    displayName: f.name,
+    contentType: f.mimeType,
+    byteCount: f.size,
+    sizeBytes: f.size,
+    kind: f.mimeType.startsWith('image/')
+      ? 'image'
+      : f.mimeType.startsWith('video/')
+        ? 'video'
+        : f.mimeType.startsWith('text/')
+          ? 'text'
+          : 'file',
+    createdAt: new Date(f.createdAt).toISOString(),
+    downloadUrl: path,
+    previewUrl: `/api/app/files/${f.id}/preview`,
+  }
+}
+export class WorkspaceAssets {
+  private stopped = false
+  private pending = new Set<string>()
+  constructor(
+    readonly store: WorkspaceStore,
+    readonly nodes: WorkspaceNodes,
+    readonly home: string,
+  ) {}
+  async archive(owner: string, message: WorkspaceMessage): Promise<void> {
+    if (!message.agentId) return
+    const agent = this.store.require<WorkspaceAgent>(owner, 'agent', message.agentId)
+    await this.archiveText(
+      owner,
+      message.content + '\n' + JSON.stringify(message.tools),
+      agent.nodeId,
+      agent.profile,
+      message.conversationId,
+      message.id,
+    )
+    if (this.stopped) return
+    const attachments = this.store
+      .list<StoredWorkspaceFile>(owner, 'file')
+      .filter((f) => f.messageId === message.id)
+      .map(publicFile)
+    if (attachments.length) {
+      message.attachments = attachments
+      this.store.saveMessage(owner, message)
+    }
+  }
+  async archiveText(
+    owner: string,
+    text: string,
+    nodeId: string,
+    profile: string,
+    conversationId: string,
+    messageId: string,
+    sender: 'user' | 'agent' = 'agent',
+  ): Promise<void> {
+    if (this.stopped) return
+    const paths = new Set<string>()
+    for (const m of text.matchAll(
+      /(?:MEDIA:\s*|\]\(<?|"(?:path|file_path|output_path)"\s*:\s*")((?:\/|~\/)[^\n"<>)]{1,4096})/g,
+    ))
+      paths.add(m[1]!.replace(/\\n.*$/, '').trim())
+    for (const path of [...paths].slice(0, 8)) {
+      const key = createHash('sha256')
+        .update(JSON.stringify([nodeId, profile, messageId, path]))
+        .digest('hex')
+      if (this.store.get(owner, 'archived-path', key) || this.pending.has(`${owner}:${key}`))
+        continue
+      this.pending.add(`${owner}:${key}`)
+      try {
+        const response = await this.nodes
+          .target(owner, nodeId)
+          .session.request('/api/files/download', {
+            search: new URLSearchParams({ profile, path }),
+            maxResponseBytes: 25 * 1024 * 1024,
+          })
+        if (response.status !== 200 || this.stopped) continue
+        const dir = join(this.home, 'workspace-files', owner)
+        mkdirSync(dir, { recursive: true, mode: 0o700 })
+        const digest = createHash('sha256').update(response.body).digest('hex')
+        const id = randomUUID(),
+          saved = join(dir, digest),
+          name = basename(path)
+        try { writeFileSync(saved, response.body, { mode: 0o600, flag: 'wx' }) }
+        catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
+        const file: StoredWorkspaceFile = {
+          id,
+          sourcePath: path,
+          path: saved,
+          digest,
+          name,
+          mimeType: String(
+            response.headers.get('content-type') || lookup(name) || 'application/octet-stream',
+          ).split(';')[0]!,
+          size: response.body.length,
+          sender,
+          profile,
+          conversationId,
+          messageId,
+          createdAt: Date.now(),
+        }
+        this.store.atomic(() => {
+          this.store.put(owner, 'file', id, file)
+          this.store.put(owner, 'archived-path', key, true)
+          this.store.event(owner, 'files.changed', publicFile(file), conversationId)
+        })
+      } catch {
+        /* A missing upstream file does not fail an otherwise completed reply. */
+      } finally {
+        this.pending.delete(`${owner}:${key}`)
+      }
+    }
+  }
+  close(): void {
+    this.stopped = true
+  }
+}

+ 254 - 0
src/server/workspaceGateway.ts

@@ -0,0 +1,254 @@
+import WebSocket from 'ws'
+import { randomUUID, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto'
+import { readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { UpstreamClient } from './upstream.js'
+import { UpstreamServiceSession } from './localAuth.js'
+import { WorkspaceStore } from './workspaceStore.js'
+import { HttpError } from './errors.js'
+import type { ServerConfig } from './config.js'
+import type { WorkspaceSource } from '../shared/workspace.js'
+
+export interface WorkspaceNode {
+  id: string
+  name: string
+  url: string
+  secret: string
+}
+export interface GatewayTarget {
+  url: URL
+  client: UpstreamClient
+  session: UpstreamServiceSession
+}
+export interface GatewayFrame {
+  type: string
+  session_id?: string
+  payload?: Record<string, any>
+}
+export class WorkspaceNodes {
+  private readonly key: Buffer
+  private targets = new Map<string, GatewayTarget>()
+  constructor(
+    readonly store: WorkspaceStore,
+    readonly config: ServerConfig,
+    readonly local: GatewayTarget,
+  ) {
+    const path = join(config.home, 'workspace-key.bin')
+    try {
+      this.key = readFileSync(path)
+    } catch (e) {
+      if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e
+      this.key = randomBytes(32)
+      writeFileSync(path, this.key, { mode: 0o600, flag: 'wx' })
+    }
+    if (this.key.length !== 32) throw new Error('Invalid workspace encryption key')
+  }
+  seal(value: unknown): string {
+    const nonce = randomBytes(12),
+      cipher = createCipheriv('aes-256-gcm', this.key, nonce)
+    const data = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()])
+    return Buffer.concat([nonce, cipher.getAuthTag(), data]).toString('base64')
+  }
+  open<T>(value: string): T {
+    const b = Buffer.from(value, 'base64'),
+      cipher = createDecipheriv('aes-256-gcm', this.key, b.subarray(0, 12))
+    cipher.setAuthTag(b.subarray(12, 28))
+    return JSON.parse(
+      Buffer.concat([cipher.update(b.subarray(28)), cipher.final()]).toString(),
+    ) as T
+  }
+  target(owner: string, id: string): GatewayTarget {
+    if (id === 'local') return this.local
+    const node = this.store.require<WorkspaceNode>(owner, 'node', id),
+      key = `${owner}:${id}`
+    let target = this.targets.get(key)
+    if (!target) {
+      const credentials = this.open<{ username: string; password: string }>(node.secret)
+      const url = new URL(node.url),
+        client = new UpstreamClient(url)
+      target = { url, client, session: new UpstreamServiceSession(client, () => credentials) }
+      this.targets.set(key, target)
+    }
+    return target
+  }
+  async add(
+    owner: string,
+    input: { name: string; url: string; username: string; password: string },
+  ): Promise<void> {
+    const url = new URL(input.url)
+    if (
+      !['http:', 'https:'].includes(url.protocol) ||
+      url.username ||
+      url.password ||
+      url.search ||
+      url.hash
+    )
+      throw new HttpError(400, '节点地址无效', 'invalid_node')
+    const client = new UpstreamClient(url),
+      session = new UpstreamServiceSession(client, () => ({
+        username: input.username,
+        password: input.password,
+      }))
+    try {
+      const status = await session.request('/api/status')
+      if (
+        status.status === 200 &&
+        JSON.parse(status.body.toString()).server_kind === 'yaoyao-web'
+      ) {
+        throw new HttpError(
+          400,
+          '请填写远端 Hermes 的 9119 地址,手机仍连接当前 Web 服务',
+          'native_gateway_required',
+        )
+      }
+      const response = await session.request('/api/profiles')
+      if (response.status !== 200)
+        throw new HttpError(400, '无法读取节点 Agent,请检查地址和凭据', 'node_unavailable')
+      const id = randomUUID()
+      this.store.put(owner, 'node', id, {
+        id,
+        name: input.name,
+        url: url.href,
+        secret: this.seal({ username: input.username, password: input.password }),
+      })
+      this.store.event(owner, 'nodes.changed', {})
+    } finally {
+      client.close()
+    }
+  }
+  remove(owner: string, id: string): void {
+    this.store.require(owner, 'node', id)
+    this.store.remove(owner, 'node', id)
+    this.targets.get(`${owner}:${id}`)?.client.close()
+    this.targets.delete(`${owner}:${id}`)
+    this.store.event(owner, 'nodes.changed', {})
+  }
+  async sources(owner: string): Promise<{ sources: WorkspaceSource[]; errors: string[] }> {
+    const sources: WorkspaceSource[] = [],
+      errors: string[] = []
+    await Promise.all(
+      ['local', ...this.store.list<WorkspaceNode>(owner, 'node').map((n) => n.id)].map(
+        async (nodeId) => {
+          try {
+            const response = await this.target(owner, nodeId).session.request('/api/profiles')
+            if (response.status !== 200) throw new Error('节点不可用')
+            const payload = JSON.parse(response.body.toString())
+            for (const p of Array.isArray(payload.profiles) ? payload.profiles : []) {
+              const profile = typeof p === 'string' ? p : p.name
+              if (typeof profile === 'string' && profile)
+                sources.push({
+                  nodeId,
+                  profile,
+                  name: p.ui_meta?.['hermes-bots']?.title || p.display_name || p.label || profile,
+                })
+            }
+          } catch {
+            errors.push(nodeId)
+          }
+        },
+      ),
+    )
+    return { sources, errors }
+  }
+  close(): void {
+    for (const t of this.targets.values()) t.client.close()
+    this.targets.clear()
+  }
+}
+
+/** One server-owned transport per execution binding, never tied to a browser. */
+export class WorkspaceGateway {
+  private socket?: WebSocket
+  private pending = new Map<
+    string,
+    { resolve(value: any): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }
+  >()
+  onEvent: (frame: GatewayFrame) => void = () => {}
+  onDisconnect: () => void = () => {}
+  constructor(readonly target: GatewayTarget) {}
+  async connect(): Promise<void> {
+    const credential = await this.target.session.webSocketCredential(),
+      url = new URL(this.target.url)
+    url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
+    url.pathname = `${url.pathname.replace(/\/$/, '')}/api/ws`
+    url.search = ''
+    url.searchParams.set(credential.name, credential.value)
+    const socket = new WebSocket(url, {
+      agent: this.target.client.directAgent,
+      headers: { Origin: this.target.url.origin },
+      maxPayload: 36 * 1024 * 1024,
+    })
+    this.socket = socket
+    let ready!: () => void
+    let failed!: (e: Error) => void
+    const handshake = new Promise<void>((resolve, reject) => {
+      ready = resolve
+      failed = reject
+    })
+    const handshakeTimer = setTimeout(() => {
+      socket.terminate()
+      failed(new Error('Hermes gateway readiness timed out'))
+    }, 20_000)
+    socket.on('message', (raw) => {
+      try {
+        const frame = JSON.parse(raw.toString()),
+          waiter = this.pending.get(String(frame.id))
+        if (waiter) {
+          clearTimeout(waiter.timer)
+          this.pending.delete(String(frame.id))
+          if (frame.error)
+            waiter.reject(
+              new HttpError(502, frame.error.message || 'Hermes 请求失败', 'gateway_rejected'),
+            )
+          else waiter.resolve(frame.result)
+        } else if (frame.method === 'event' && frame.params) {
+          if (frame.params.type === 'gateway.ready') {
+            clearTimeout(handshakeTimer)
+            ready()
+          }
+          this.onEvent(frame.params)
+        }
+      } catch {
+        /* Malformed frames cannot mutate an execution. */
+      }
+    })
+    socket.on('error', (error) => {
+      clearTimeout(handshakeTimer)
+      failed(error)
+    })
+    socket.on('close', () => {
+      for (const waiter of this.pending.values()) {
+        clearTimeout(waiter.timer)
+        waiter.reject(new Error('Hermes connection closed'))
+      }
+      this.pending.clear()
+      this.onDisconnect()
+      clearTimeout(handshakeTimer)
+      failed(new Error('Hermes connection closed'))
+    })
+    await handshake
+  }
+  rpc(method: string, params: Record<string, unknown>): Promise<any> {
+    if (this.socket?.readyState !== WebSocket.OPEN)
+      return Promise.reject(new Error('Hermes connection unavailable'))
+    const id = randomUUID()
+    return new Promise((resolve, reject) => {
+      const timer = setTimeout(() => {
+        this.pending.delete(id)
+        reject(new Error('Hermes response timed out'))
+      }, 30_000)
+      this.pending.set(id, { resolve, reject, timer })
+      this.socket!.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }), (error) => {
+        if (error) {
+          clearTimeout(timer)
+          this.pending.delete(id)
+          reject(error)
+        }
+      })
+    })
+  }
+  close(): void {
+    this.onDisconnect = () => {}
+    this.socket?.close()
+  }
+}

+ 549 - 0
src/server/workspaceRoutes.ts

@@ -0,0 +1,549 @@
+import Router from '@koa/router'
+import type Koa from 'koa'
+import { createReadStream, statSync } from 'node:fs'
+import { z } from 'zod'
+import { WorkspaceStore, agentInput, parse } from './workspaceStore.js'
+import { WorkspaceRuntime } from './workspaceRuntime.js'
+import { WorkspaceNodes, type WorkspaceNode } from './workspaceGateway.js'
+import {
+  WorkspaceAssets,
+  libraryFile,
+  publicFile,
+  type StoredWorkspaceFile,
+} from './workspaceAssets.js'
+import { receiveGroupUploads, type UploadStore } from './uploads.js'
+import { HttpError } from './errors.js'
+import type { PushCoordinator } from './pushCoordinator.js'
+import type { LocalAuthStore } from './localAuth.js'
+import type {
+  WorkspaceAgent,
+  WorkspaceConversation,
+  WorkspaceRun,
+  WorkspaceInteraction,
+} from '../shared/workspace.js'
+
+const body = (ctx: Koa.Context): any => (ctx.request as Koa.Request & { body?: unknown }).body ?? {}
+const number = (v: unknown, fallback: number) =>
+  typeof v === 'string' && /^\d+$/.test(v) ? Math.min(Number(v), Number.MAX_SAFE_INTEGER) : fallback
+export function workspaceRouter(
+  store: WorkspaceStore,
+  runtime: WorkspaceRuntime,
+  nodes: WorkspaceNodes,
+  assets: WorkspaceAssets,
+  uploads: UploadStore,
+  auth: LocalAuthStore,
+  push: PushCoordinator,
+): Router {
+  const router = new Router(),
+    owner = (ctx: Koa.Context) => auth.require(ctx).id
+  const libraryId = (user: string, id: string) =>
+    Number(
+      store.db
+        .prepare("SELECT rowid AS n FROM workspace_entities WHERE owner=? AND kind='file' AND id=?")
+        .get(user, id)?.n ?? 0,
+    )
+  const fileRecord = (user: string, id: string): StoredWorkspaceFile => {
+    if (/^\d+$/.test(id)) {
+      const row = store.db
+        .prepare("SELECT data FROM workspace_entities WHERE owner=? AND kind='file' AND rowid=?")
+        .get(user, Number(id))
+      if (row) return JSON.parse(String(row.data))
+    }
+    return store.require(user, 'file', id)
+  }
+  router.get('/api/app/capabilities', (ctx) => {
+    owner(ctx)
+    ctx.body = {
+      protocolVersion: 1,
+      serverKind: 'yaoyao-web',
+      features: [
+        'agents',
+        'conversations',
+        'immutableGroups',
+        'files',
+        'voice',
+        'context',
+        'nodes',
+        'events',
+      ],
+    }
+  })
+  router.get('/api/app/agents/sources', async (ctx) => {
+    ctx.body = await nodes.sources(owner(ctx))
+  })
+  router.get('/api/app/agents', (ctx) => {
+    ctx.body = { agents: store.list<WorkspaceAgent>(owner(ctx), 'agent') }
+  })
+  router.post('/api/app/agents', async (ctx) => {
+    const user = owner(ctx),
+      input = parse(agentInput, body(ctx)),
+      sources = await nodes.sources(user)
+    if (!sources.sources.some((s) => s.nodeId === input.nodeId && s.profile === input.profile))
+      throw new HttpError(409, '基础 Agent 当前不可用', 'source_unavailable')
+    ctx.body = { agent: store.createAgent(user, input) }
+    ctx.status = 201
+  })
+  router.patch('/api/app/agents/:id', (ctx) => {
+    ctx.body = { agent: store.updateAgent(owner(ctx), ctx.params.id, body(ctx)) }
+  })
+  router.get('/api/app/conversations', (ctx) => {
+    const user = owner(ctx)
+    ctx.body = {
+      conversations: store
+        .list<WorkspaceConversation>(user, 'conversation')
+        .sort(
+          (a, b) =>
+            Number(b.pinned) - Number(a.pinned) ||
+            b.updatedAt - a.updatedAt ||
+            a.id.localeCompare(b.id),
+        ),
+      cursor: store.cursor(user),
+    }
+  })
+  router.post('/api/app/conversations', (ctx) => {
+    const user = owner(ctx),
+      conversation = store.createGroup(user, body(ctx))
+    try {
+      push.setGroupSubscription(user, conversation.id, true, conversation.lastSeq)
+    } catch {
+      /* Optional delivery cannot undo a created chat. */
+    }
+    ctx.body = { conversation }
+    ctx.status = 201
+  })
+  router.get('/api/app/conversations/:id', (ctx) => {
+    const user = owner(ctx),
+      conversation = store.require<WorkspaceConversation>(user, 'conversation', ctx.params.id)
+    ctx.body = {
+      conversation,
+      messages: store.messages(user, conversation.id),
+      run: conversation.activeRunId
+        ? store.require<WorkspaceRun>(user, 'run', conversation.activeRunId)
+        : null,
+      interactions: store
+        .list<WorkspaceInteraction>(user, 'interaction')
+        .filter((i) => i.conversationId === conversation.id && !i.resolved),
+      context: store.get(user, 'context', conversation.id) ?? null,
+    }
+  })
+  router.patch('/api/app/conversations/:id', (ctx) => {
+    ctx.body = { conversation: store.updateConversation(owner(ctx), ctx.params.id, body(ctx)) }
+  })
+  router.get('/api/app/conversations/:id/messages', (ctx) => {
+    ctx.body = {
+      messages: store.messages(
+        owner(ctx),
+        ctx.params.id,
+        number(ctx.query.before, Number.MAX_SAFE_INTEGER),
+        Math.min(200, number(ctx.query.limit, 100)),
+      ),
+    }
+  })
+  router.post('/api/app/conversations/:id/messages', (ctx) => {
+    const user = owner(ctx)
+    ctx.body = { run: runtime.send(user, ctx.params.id, body(ctx)) }
+    ctx.status = 202
+  })
+  router.put('/api/app/conversations/:id/read', (ctx) => {
+    const user = owner(ctx),
+      c = store.require<WorkspaceConversation>(user, 'conversation', ctx.params.id)
+    const seq = parse(z.object({ seq: z.number().int().nonnegative() }).strict(), body(ctx)).seq
+    c.readSeq = Math.max(c.readSeq, Math.min(seq, c.lastSeq))
+    store.atomic(() => {
+      store.put(user, 'conversation', c.id, c)
+      store.event(user, 'conversation.changed', c, c.id)
+    })
+    ctx.body = { conversation: c }
+  })
+  router.post('/api/app/runs/:id/stop', async (ctx) => {
+    await runtime.stop(owner(ctx), ctx.params.id)
+    ctx.body = { ok: true }
+  })
+  router.post('/api/app/runs/:id/reconcile', (ctx) => {
+    const user = owner(ctx)
+    store.require(user, 'run', ctx.params.id)
+    void runtime.reconcile(user, ctx.params.id).catch(() => {})
+    ctx.status = 202
+    ctx.body = { ok: true }
+  })
+  router.post('/api/app/interactions/:id/respond', async (ctx) => {
+    const b = parse(z.object({ answer: z.string().min(1).max(16_000) }).strict(), body(ctx))
+    await runtime.respond(owner(ctx), ctx.params.id, b.answer)
+    ctx.body = { ok: true }
+  })
+  router.get('/api/app/events', (ctx) => {
+    const user = owner(ctx),
+      after = number(ctx.query.after, 0),
+      events = store.events(user, after)
+    ctx.set('Cache-Control', 'no-store')
+    ctx.body = { events, cursor: events.at(-1)?.seq ?? after }
+  })
+  router.get('/api/app/nodes', (ctx) => {
+    ctx.body = {
+      nodes: store
+        .list<WorkspaceNode>(owner(ctx), 'node')
+        .map(({ secret: _secret, ...node }) => node),
+    }
+  })
+  router.post('/api/app/nodes', async (ctx) => {
+    const b = parse(
+      z
+        .object({
+          name: z.string().min(1).max(100),
+          url: z.string().url().max(2048),
+          username: z.string().max(256),
+          password: z.string().max(4096),
+        })
+        .strict(),
+      body(ctx),
+    )
+    await nodes.add(owner(ctx), b)
+    ctx.status = 201
+    ctx.body = { ok: true }
+  })
+  router.delete('/api/app/nodes/:id', (ctx) => {
+    nodes.remove(owner(ctx), ctx.params.id)
+    ctx.body = { ok: true }
+  })
+  router.post('/api/app/uploads', async (ctx) => {
+    const user = owner(ctx),
+      refs = await receiveGroupUploads(ctx.req, uploads, user)
+    const files = uploads
+      .records(
+        refs.map((r) => r.id),
+        user,
+      )
+      .map((r) => ({
+        id: r.id,
+        name: r.name,
+        mimeType: r.mimeType,
+        size: r.size,
+        path: r.path,
+        sender: 'user' as const,
+        createdAt: Date.now(),
+      }))
+    // A library entry owns its bytes even when the user cancels the draft.
+    uploads.markReferenced(files.map(file => file.id), user)
+    for (const f of files) store.put(user, 'file', f.id, f)
+    ctx.status = 201
+    ctx.body = { files: files.map(publicFile) }
+  })
+  router.get('/api/app/files', (ctx) => {
+    const files = store
+      .list<StoredWorkspaceFile>(owner(ctx), 'file')
+      .filter(
+        (f) =>
+          (!ctx.query.search ||
+            f.name.toLowerCase().includes(String(ctx.query.search).toLowerCase())) &&
+          (!ctx.query.profile || f.profile === ctx.query.profile) &&
+          (!ctx.query.session_id || f.conversationId === ctx.query.session_id) &&
+          (!ctx.query.sender || f.sender === ctx.query.sender),
+      )
+      .sort((a, b) => b.createdAt - a.createdAt || a.id.localeCompare(b.id))
+      .map((f) => libraryFile(publicFile(f), libraryId(owner(ctx), f.id), store.get<WorkspaceConversation>(owner(ctx),'conversation',f.conversationId ?? '')))
+      .filter((f) => !ctx.query.kind || f.kind === ctx.query.kind)
+    const start = number(ctx.query.cursor, 0),
+      limit = Math.min(200, number(ctx.query.limit, 50))
+    ctx.body = {
+      items: files.slice(start, start + limit),
+      total: files.length,
+      nextCursor: start + limit < files.length ? String(start + limit) : null,
+    }
+  })
+  router.get('/api/app/files/stats', (ctx) => {
+    const files = store.list<StoredWorkspaceFile>(owner(ctx), 'file')
+    ctx.body = { count: files.length, totalBytes: files.reduce((sum, f) => sum + f.size, 0) }
+  })
+  router.post('/api/app/message-files/query', (ctx) => {
+    const ids = parse(
+      z.object({ messageIds: z.array(z.union([z.string(), z.number()])).max(500) }),
+      body(ctx),
+    ).messageIds.map(String)
+    const files = store.list<StoredWorkspaceFile>(owner(ctx), 'file')
+    ctx.body = {
+      messages: Object.fromEntries(
+        ids.map((id) => [
+          id,
+          files
+            .filter((f) => f.messageId === id)
+            .map((f, ordinal) => ({
+              itemId: libraryId(owner(ctx), f.id),
+              messageId: id,
+              ordinal,
+              originalPath: `/api/app/files/${f.id}/download`,
+              referencePath: `/api/app/files/${f.id}/download`,
+              name: f.name,
+              size: f.size,
+              mimeType: f.mimeType,
+              archiveStatus: 'ready',
+              archivedAt: f.createdAt,
+              availability: 'archived',
+            })),
+        ]),
+      ),
+    }
+  })
+  for (const action of ['download', 'preview'])
+    router.get(`/api/app/files/:id/${action}`, (ctx) => {
+      const file = fileRecord(owner(ctx), ctx.params.id),
+        size = statSync(file.path).size
+      const activeContent =
+        /(?:html|svg|javascript|ecmascript|xml)/i.test(file.mimeType) ||
+        /\.(?:html?|svg|js|mjs|xml|xhtml)$/i.test(file.name)
+      ctx.type = activeContent ? 'application/octet-stream' : file.mimeType
+      ctx.set(
+        'Content-Disposition',
+        `${action === 'preview' && !activeContent ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(file.name)}`,
+      )
+      ctx.set('Accept-Ranges', 'bytes')
+      ctx.set('Cache-Control', 'private, no-store')
+      const range = ctx.get('range'),
+        match = /^bytes=(\d*)-(\d*)$/.exec(range)
+      let start = 0,
+        end = size - 1
+      if (range) {
+        if (!match || (!match[1] && !match[2]))
+          throw new HttpError(416, 'Range invalid', 'invalid_range')
+        if (!match[1]) start = Math.max(0, size - Number(match[2]))
+        else {
+          start = Number(match[1])
+          end = match[2] ? Math.min(size - 1, Number(match[2])) : size - 1
+        }
+        if (start > end || start >= size) {
+          ctx.set('Content-Range', `bytes */${size}`)
+          throw new HttpError(416, 'Range invalid', 'invalid_range')
+        }
+        ctx.status = 206
+        ctx.set('Content-Range', `bytes ${start}-${end}/${size}`)
+      }
+      ctx.length = Math.max(0, end - start + 1)
+      ctx.body = size ? createReadStream(file.path, { start, end }) : Buffer.alloc(0)
+    })
+  const contextKey = (ctx: Koa.Context) =>
+    JSON.stringify([ctx.query.profile ?? ctx.get('x-hermes-profile') ?? 'default', ctx.params.id])
+  router.get('/api/app/session-context/:id', (ctx) => {
+    ctx.body = { snapshot: store.get(owner(ctx), 'native-context', contextKey(ctx)) ?? null }
+  })
+  router.put('/api/app/session-context/:id', (ctx) => {
+    const user = owner(ctx),
+      key = contextKey(ctx)
+    const value = parse(
+      z
+        .object({
+          usedTokens: z.number().int().nonnegative(),
+          limitTokens: z.number().int().positive().nullable().optional(),
+          percent: z.number().nonnegative().nullable().optional(),
+          compressions: z.number().int().nonnegative().nullable().optional(),
+          model: z.string().max(512).nullable().optional(),
+          provider: z.string().max(256).nullable().optional(),
+          observedAt: z.number().nonnegative(),
+        })
+        .strict(),
+      body(ctx),
+    )
+    const previous = store.get<{ observedAt: number }>(user, 'native-context', key)
+    const snapshot =
+      previous && previous.observedAt > value.observedAt
+        ? previous
+        : { ...value, sessionId: ctx.params.id, updatedAt: Date.now() / 1000 }
+    store.put(user, 'native-context', key, snapshot)
+    ctx.body = { snapshot }
+  })
+  registerVoice(router, store, nodes, owner, auth)
+  return router
+}
+
+function registerVoice(
+  router: Router,
+  store: WorkspaceStore,
+  vault: WorkspaceNodes,
+  owner: (ctx: Koa.Context) => string,
+  auth: LocalAuthStore,
+): void {
+  const read = (key: string): any => {
+    const saved = store.get<string>('_system', 'voice', key)
+    return saved ? vault.open(saved) : {}
+  }
+  const save = (key: string, value: unknown) =>
+    store.put('_system', 'voice', key, vault.seal(value))
+  const settings = () => ({
+    voices: [],
+    currentVoiceId: '',
+    apiKey: '',
+    updatedAt: 0,
+    ...read('duplex'),
+  })
+  const publicSettings = () => {
+    const { apiKey, ...value } = settings()
+    return { ...value, hasApiKey: Boolean(apiKey) }
+  }
+  router.get('/api/app/admin/duplex-voice', (ctx) => {
+    auth.requireAdmin(ctx)
+    ctx.body = publicSettings()
+  })
+  router.put('/api/app/admin/duplex-voice', (ctx) => {
+    auth.requireAdmin(ctx)
+    const b = parse(
+      z
+        .object({
+          apiKey: z.string().max(4096).optional(),
+          voices: z
+            .array(z.object({ id: z.string().min(1).max(200), name: z.string().min(1).max(200) }))
+            .max(100),
+          currentVoiceId: z.string().max(200),
+        })
+        .strict(),
+      body(ctx),
+    )
+    if (
+      new Set(b.voices.map((v) => v.id)).size !== b.voices.length ||
+      (b.currentVoiceId && !b.voices.some((v) => v.id === b.currentVoiceId))
+    )
+      throw new HttpError(400, '音色设置无效')
+    save('duplex', { ...settings(), ...b, updatedAt: Date.now() })
+    ctx.body = publicSettings()
+  })
+  router.get('/api/app/voice/runtime', (ctx) => {
+    const user = owner(ctx),
+      value = settings()
+    ctx.body = {
+      ...value,
+      currentVoiceId: store.get(user, 'voice-selection', 'current') ?? value.currentVoiceId,
+    }
+  })
+  router.put('/api/app/voice/current-voice', (ctx) => {
+    const user = owner(ctx),
+      value = settings(),
+      id = parse(z.object({ currentVoiceId: z.string() }).strict(), body(ctx)).currentVoiceId
+    if (!value.voices.some((v: any) => v.id === id)) throw new HttpError(400, '音色不存在')
+    store.put(user, 'voice-selection', 'current', id)
+    ctx.body = { voices: value.voices, currentVoiceId: id, updatedAt: Date.now() }
+  })
+  for (const kind of ['tts', 'stt']) {
+    const list = () => {
+      const data = read(kind)
+      return {
+        activeProvider: data.activeProvider ?? (kind === 'tts' ? 'edge' : 'browser'),
+        settings: Object.entries(data.providers ?? {}).map(([provider, v]: [string, any]) => ({
+          provider,
+          settings: v.settings,
+          secrets: Object.fromEntries(Object.keys(v.secrets ?? {}).map((k) => [k, '[stored]'])),
+        })),
+      }
+    }
+    router.get(`/api/app/${kind}/settings`, (ctx) => {
+      owner(ctx)
+      ctx.body = list()
+    })
+    router.put(`/api/app/${kind}/settings/active`, (ctx) => {
+      auth.requireAdmin(ctx)
+      const data = read(kind),
+        provider = parse(
+          z.object({ provider: z.string().min(1).max(100) }).strict(),
+          body(ctx),
+        ).provider
+      if (!data.providers?.[provider] && !['edge', 'browser'].includes(provider))
+        throw new HttpError(400, '请先配置服务商')
+      data.activeProvider = provider
+      save(kind, data)
+      ctx.body = list()
+    })
+    router.put(`/api/app/${kind}/settings/:provider`, (ctx) => {
+      auth.requireAdmin(ctx)
+      const input = parse(
+        z
+          .object({
+            settings: z.record(z.string(), z.unknown()).default({}),
+            secrets: z.record(z.string(), z.string().max(4096)).default({}),
+            activeProvider: z.string().optional(),
+          })
+          .strict(),
+        body(ctx),
+      )
+      if (JSON.stringify(input.settings).length > 32_000) throw new HttpError(413, '设置过大')
+      const data = read(kind)
+      data.providers ??= {}
+      const old = data.providers[ctx.params.provider] ?? { settings: {}, secrets: {} }
+      data.providers[ctx.params.provider] = {
+        settings: { ...old.settings, ...input.settings },
+        secrets: {
+          ...old.secrets,
+          ...Object.fromEntries(Object.entries(input.secrets).filter(([, v]) => v !== '[stored]')),
+        },
+      }
+      if (input.activeProvider) data.activeProvider = input.activeProvider
+      save(kind, data)
+      ctx.body = list()
+    })
+    router.delete(`/api/app/${kind}/settings/:provider`, (ctx) => {
+      auth.requireAdmin(ctx)
+      const data = read(kind)
+      if (data.providers) delete data.providers[ctx.params.provider]
+      if (data.activeProvider === ctx.params.provider)
+        data.activeProvider = kind === 'tts' ? 'edge' : 'browser'
+      save(kind, data)
+      ctx.body = list()
+    })
+    router.delete(`/api/app/${kind}/settings/:provider/secret/:secret`, (ctx) => {
+      auth.requireAdmin(ctx)
+      const data = read(kind)
+      if (data.providers?.[ctx.params.provider]?.secrets)
+        delete data.providers[ctx.params.provider].secrets[ctx.params.secret]
+      save(kind, data)
+      ctx.body = list()
+    })
+    router.delete(`/api/app/${kind}/settings/:provider/base-url-preset`, (ctx) => {
+      auth.requireAdmin(ctx)
+      const data = read(kind),
+        s = data.providers?.[ctx.params.provider]?.settings
+      if (s) s.baseUrlPresets = (s.baseUrlPresets ?? []).filter((v: string) => v !== ctx.query.url)
+      save(kind, data)
+      ctx.body = list()
+    })
+  }
+  router.get('/api/app/voice/providers-info', (ctx) => {
+    owner(ctx)
+    ctx.body = {
+      tts: ['edge', 'openai', 'custom', 'mimo', 'doubao'],
+      stt: ['browser', 'openai', 'custom', 'doubao'],
+    }
+  })
+  router.post('/api/app/voice/probe', async (ctx) => {
+    auth.requireAdmin(ctx)
+    const b = parse(
+        z
+          .object({
+            kind: z.enum(['tts', 'stt']),
+            provider: z.string().optional(),
+            compatibility: z.enum(['manual', 'openai-compatible']).default('openai-compatible'),
+            baseUrl: z.string().url(),
+            apiKey: z.string().max(4096).optional(),
+          })
+          .strict(),
+        body(ctx),
+      ),
+      url = new URL(b.baseUrl)
+    if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
+      throw new HttpError(400, '服务地址无效')
+    if (b.compatibility === 'manual') {
+      ctx.body = { ok: true, models: [], normalizedBaseUrl: b.baseUrl, manualModelAllowed: true }
+      return
+    }
+    url.pathname = `${url.pathname.replace(/\/$/, '')}/models`
+    const response = await fetch(url, {
+      headers: b.apiKey ? { Authorization: `Bearer ${b.apiKey}` } : {},
+      signal: AbortSignal.timeout(10_000),
+      redirect: 'error',
+    })
+    const value = (await response.json()) as any
+    ctx.body = {
+      ok: response.ok,
+      models: Array.isArray(value.data)
+        ? value.data.slice(0, 500).map((m: any) => String(m.id))
+        : [],
+      normalizedBaseUrl: b.baseUrl,
+      manualModelAllowed: true,
+      errorSummary: response.ok ? '' : `HTTP ${response.status}`,
+    }
+  })
+}

+ 693 - 0
src/server/workspaceRuntime.ts

@@ -0,0 +1,693 @@
+import { randomUUID } from 'node:crypto'
+import { readFileSync } from 'node:fs'
+import { z } from 'zod'
+import { WorkspaceStore, parse } from './workspaceStore.js'
+import { WorkspaceNodes, WorkspaceGateway, type GatewayFrame } from './workspaceGateway.js'
+import { HttpError } from './errors.js'
+import { UploadStore } from './uploads.js'
+import type {
+  WorkspaceAgent as Agent,
+  WorkspaceConversation as Conversation,
+  WorkspaceMessage as Message,
+  WorkspaceRun,
+  WorkspaceInteraction,
+} from '../shared/workspace.js'
+
+type Run = WorkspaceRun & {
+  queue: string[]
+  next: string[]
+  hostReturn: boolean
+  currentMessageId?: string
+  turnConfiguration?: {
+    mode: 'host' | 'free'
+    administratorId: string
+    members: Array<Pick<Agent, 'id' | 'name'>>
+  }
+}
+export interface WorkspaceBinding {
+  id: string
+  nodeId: string
+  profile: string
+  storedId: string
+  runtimeId: string
+  aliases: string[]
+  runId: string
+  messageId: string
+}
+interface LiveTurn {
+  gateway: WorkspaceGateway
+  runtimeId: string
+  runId: string
+  agentId: string
+  done(error?: Error): void
+}
+export const sendInput = z
+  .object({
+    requestId: z.string().uuid(),
+    content: z.string().max(65_536).default(''),
+    mentionIds: z.array(z.string().uuid()).max(8).default([]),
+    fileIds: z.array(z.string().uuid()).max(8).default([]),
+  })
+  .strict()
+  .refine((b) => b.content.trim() || b.fileIds.length, '请输入消息或添加附件')
+export function mentionedAgents(text: string, agents: Array<Pick<Agent, 'id' | 'name'>>): string[] {
+  const plain = text
+    .replace(/```[\s\S]*?```/g, '')
+    .replace(/`[^`]*`/g, '')
+    .split('\n')
+    .filter((l) => !l.trimStart().startsWith('>'))
+    .join('\n')
+  if (/(?:^|\s)@all(?=$|[\s,。,::!!??])/i.test(plain)) return agents.map((a) => a.id)
+  return agents
+    .filter((a) => {
+      const escaped = a.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+      return new RegExp(`(?:^|\\s)@${escaped}(?=$|[\\s,。,::!!??])`, 'u').test(plain)
+    })
+    .map((a) => a.id)
+}
+export class WorkspaceRuntime {
+  private live = new Map<string, LiveTurn>()
+  private executing = new Set<string>()
+  private closing = false
+  onMessage: (owner: string, message: Message) => Promise<void> = async () => {}
+  onNotify: (
+    owner: string,
+    c: Conversation,
+    run: Run,
+    message?: Message,
+    interaction?: WorkspaceInteraction,
+  ) => void = () => {}
+  private notify(
+    owner: string,
+    c: Conversation,
+    run: Run,
+    message?: Message,
+    interaction?: WorkspaceInteraction,
+  ): void {
+    try {
+      this.onNotify(owner, c, run, message, interaction)
+    } catch {
+      /* Optional push failures never change the durable execution result. */
+    }
+  }
+  constructor(
+    readonly store: WorkspaceStore,
+    readonly nodes: WorkspaceNodes,
+    readonly uploads: UploadStore,
+    readonly userActive: (owner: string) => boolean = () => true,
+  ) {
+    // An admitted but unacknowledged turn may already have executed a tool.
+    for (const owner of store.owners())
+      for (const run of store.list<Run>(owner, 'run')) {
+        if (['running', 'waiting'].includes(run.status)) {
+          run.status = 'uncertain'
+          run.error = '服务已重启,请核对运行状态'
+          store.saveRun(owner, run)
+        }
+      }
+  }
+  start(): void {
+    for (const owner of this.store.owners())
+      for (const run of this.store.list<Run>(owner, 'run')) {
+        if (run.status === 'queued') void this.execute(owner, run.id)
+        else if (run.status === 'uncertain') void this.reconcile(owner, run.id).catch(() => {})
+      }
+  }
+  send(owner: string, conversationId: string, input: unknown): Run {
+    const body = parse(sendInput, input)
+    const result = this.store.command(owner, body.requestId, { conversationId, ...body }, () => {
+      const c = this.store.require<Conversation>(owner, 'conversation', conversationId)
+      if (c.archived) throw new HttpError(409, '聊天已归档', 'conversation_archived')
+      if (c.activeRunId) throw new HttpError(409, '请等待当前回复结束或先停止', 'conversation_busy')
+      if (body.mentionIds.some((a) => !c.memberIds.includes(a)))
+        throw new HttpError(400, '只能 @ 群内成员', 'invalid_mentions')
+      const records = this.uploads.records(body.fileIds, owner)
+      const now = Date.now(),
+        runId = randomUUID(),
+        agents = c.memberIds.map((id) => this.store.require<Agent>(owner, 'agent', id))
+      const mentions = [
+        ...new Set(
+          body.mentionIds.length ? body.mentionIds : mentionedAgents(body.content, agents),
+        ),
+      ]
+      const queue =
+        c.kind === 'direct'
+          ? [...c.memberIds]
+          : mentions.length
+            ? mentions
+            : c.mode === 'free' && c.autoReplyIds.length
+              ? [...c.autoReplyIds]
+              : [c.administratorId]
+      const message: Message = {
+        id: randomUUID(),
+        conversationId,
+        seq: 0,
+        role: 'user',
+        content: body.content.trim(),
+        reasoning: '',
+        runId,
+        status: 'complete',
+        attachments: records.map((f) => ({
+          id: f.id,
+          name: f.name,
+          mimeType: f.mimeType,
+          size: f.size,
+          sender: 'user',
+          createdAt: now,
+        })),
+        tools: [],
+        createdAt: now,
+      }
+      this.store.saveMessage(owner, message)
+      for (const file of records) {
+        const existing = this.store.get<Record<string, unknown>>(owner, 'file', file.id)
+        if (existing)
+          this.store.put(owner, 'file', file.id, {
+            ...existing,
+            conversationId,
+            messageId: message.id,
+          })
+      }
+      const run: Run = {
+        id: runId,
+        conversationId,
+        messageId: message.id,
+        mentionIds: mentions,
+        status: 'queued',
+        round: 0,
+        queue,
+        next: [],
+        hostReturn: c.mode === 'host' && queue.some((id) => id !== c.administratorId),
+        createdAt: now,
+        updatedAt: now,
+      }
+      this.store.saveRun(owner, run)
+      this.uploads.markReferenced(body.fileIds, owner)
+      return run
+    })
+    if (this.store.require<Run>(owner, 'run', result.id).status === 'queued')
+      void this.execute(owner, result.id)
+    return this.store.require<Run>(owner, 'run', result.id)
+  }
+  private async execute(owner: string, id: string): Promise<void> {
+    if (this.executing.has(id) || this.closing) return
+    this.executing.add(id)
+    try {
+      while (!this.closing) {
+        const run = this.store.require<Run>(owner, 'run', id)
+        if (!['queued', 'running'].includes(run.status)) break
+        if (!this.userActive(owner)) throw new HttpError(403, '账号已停用', 'account_disabled')
+        const c = this.store.require<Conversation>(owner, 'conversation', run.conversationId)
+        if (!run.queue.length) {
+          if (
+            c.kind === 'direct' ||
+            run.round + 1 >= c.maxReplyRounds ||
+            (!run.next.length && !run.hostReturn)
+          ) {
+            run.status = 'complete'
+            this.store.saveRun(owner, run)
+            this.notify(
+              owner,
+              c,
+              run,
+              this.store
+                .messages(owner, c.id)
+                .filter((m) => m.runId === id && m.role === 'assistant')
+                .at(-1),
+            )
+            break
+          }
+          run.round += 1
+          run.queue = run.hostReturn ? [c.administratorId] : [...new Set(run.next)]
+          run.hostReturn = false
+          run.next = []
+          this.store.saveRun(owner, run)
+        }
+        const agent = this.store.require<Agent>(owner, 'agent', run.queue[0]!)
+        run.turnConfiguration = {
+          mode: c.mode,
+          administratorId: c.administratorId,
+          members: c.memberIds.map((id) => {
+            const a = this.store.require<Agent>(owner, 'agent', id)
+            return { id: a.id, name: a.name }
+          }),
+        }
+        run.status = 'running'
+        this.store.saveRun(owner, run)
+        const message = await this.turn(owner, c, agent, run)
+        await this.onMessage(owner, message).catch(() => {})
+        if (this.closing) return
+        this.advance(owner, run.id, agent.id, message)
+      }
+    } catch (error) {
+      if (!this.closing) {
+        const run = this.store.require<Run>(owner, 'run', id)
+        if (!['interrupted', 'uncertain'].includes(run.status)) {
+          run.status = 'failed'
+          run.error = (error instanceof Error ? error.message : '执行失败').slice(0, 1000)
+          this.store.saveRun(owner, run)
+          this.store.saveMessage(owner, {
+            id:randomUUID(), conversationId:run.conversationId, seq:0, role:'system',
+            content:`执行失败:${run.error}`, reasoning:'', runId:run.id, status:'failed',
+            attachments:[], tools:[], createdAt:Date.now(),
+          })
+          this.notify(owner, this.store.require(owner, 'conversation', run.conversationId), run)
+        }
+      }
+    } finally {
+      this.executing.delete(id)
+    }
+  }
+  private advance(owner: string, runId: string, agentId: string, message: Message): void {
+    this.store.atomic(() => {
+      const run = this.store.require<Run>(owner, 'run', runId)
+      if (run.status === 'interrupted') return
+      const c = this.store.require<Conversation>(owner, 'conversation', run.conversationId)
+      const configuration = run.turnConfiguration
+      if (!configuration) throw new Error('运行配置缺失,已停止自动协作')
+      if (configuration.mode === 'free' || agentId === configuration.administratorId)
+        run.next.push(
+          ...mentionedAgents(message.content, configuration.members).filter((id) => id !== agentId),
+        )
+      if (
+        c.kind === 'group' &&
+        configuration.mode === 'host' &&
+        agentId !== configuration.administratorId
+      )
+        run.hostReturn = true
+      if (run.queue[0] === agentId) run.queue.shift()
+      run.currentMessageId = undefined
+      run.error = undefined
+      run.status = 'running'
+      this.store.saveRun(owner, run)
+    })
+  }
+  private async turn(
+    owner: string,
+    c: Conversation,
+    agent: Agent,
+    run: Run,
+    recovering = false,
+  ): Promise<Message> {
+    const key = `${c.id}:${agent.id}`,
+      target = this.nodes.target(owner, agent.nodeId)
+    const gateway = new WorkspaceGateway(target)
+    let binding = this.store.get<WorkspaceBinding>(owner, 'binding', key)
+    let message =
+      recovering && run.currentMessageId
+        ? this.store.require<Message>(owner, 'message', run.currentMessageId)
+        : undefined
+    if (!message) {
+      message = {
+        id: randomUUID(),
+        conversationId: c.id,
+        seq: 0,
+        role: 'assistant',
+        agentId: agent.id,
+        agentName: agent.name,
+        content: '',
+        reasoning: '',
+        status: 'streaming',
+        runId: run.id,
+        tools: [],
+        attachments: [],
+        createdAt: Date.now(),
+      }
+      run.currentMessageId = message.id
+      this.store.atomic(() => {
+        this.store.saveMessage(owner, message!)
+        this.store.saveRun(owner, run)
+      })
+    }
+    const resultMessage = message
+    let submitted = recovering,
+      settled = false,
+      completedEvidence = false,
+      completing = false,
+      runtimeId = '',
+      lastFlush = 0
+    let resolveTurn!: (m: Message) => void, rejectTurn!: (e: Error) => void
+    const completion = new Promise<Message>((resolve, reject) => {
+      resolveTurn = resolve
+      rejectTurn = reject
+    })
+    // Register rejection immediately; setup RPCs can still be awaiting a reply.
+    void completion.catch(() => {})
+    const finish = (error?: Error) => {
+      if (settled) return
+      settled = true
+      this.live.delete(key)
+      if (error) {
+        const current = this.store.require<Run>(owner, 'run', run.id)
+        resultMessage.status =
+          current.status === 'interrupted' ? 'interrupted' : submitted ? 'uncertain' : 'failed'
+        if (submitted && current.status !== 'interrupted') {
+          current.status = 'uncertain'
+          current.error = '执行状态待确认,未自动重发'
+          this.store.saveRun(owner, current)
+        }
+        this.store.saveMessage(owner, resultMessage)
+        rejectTurn(error)
+      } else {
+        resultMessage.status = 'complete'
+        this.store.saveMessage(owner, resultMessage)
+        resolveTurn(resultMessage)
+      }
+      gateway.close()
+    }
+    gateway.onDisconnect = () =>
+      finish(completedEvidence ? undefined : new Error('Hermes 连接断开'))
+    gateway.onEvent = (frame: GatewayFrame) => {
+      if (settled || !runtimeId || frame.session_id !== runtimeId) return
+      const p = frame.payload ?? {},
+        type = frame.type
+      if (type === 'message.delta') resultMessage.content += String(p.text ?? p.delta ?? '')
+      else if (type === 'reasoning.delta')
+        resultMessage.reasoning += String(p.text ?? p.delta ?? '')
+      else if (type === 'message.interim') {
+        resultMessage.content += '\n\n'
+      } else if (type.startsWith('tool.')) {
+        const id = String(p.tool_id ?? p.id ?? ''),
+          index = resultMessage.tools.findIndex((t) => t.id === id)
+        const value = { ...p, id, status: type }
+        if (index >= 0) resultMessage.tools[index] = { ...resultMessage.tools[index], ...value }
+        else resultMessage.tools.push(value)
+      } else if (
+        ['approval.request', 'approval.requested', 'clarify.request', 'clarify.requested'].includes(
+          type,
+        )
+      ) {
+        const upstreamId = String(p.request_id ?? p.requestId ?? p.id ?? '')
+        const interaction: WorkspaceInteraction = {
+          id: randomUUID(),
+          conversationId: c.id,
+          runId: run.id,
+          agentId: agent.id,
+          kind: type.startsWith('approval') ? 'approval' : 'clarification',
+          message: String(p.question ?? p.message ?? p.prompt ?? '需要确认'),
+          choices: Array.isArray(p.choices) ? p.choices.map(String) : [],
+          resolved: false,
+        }
+        this.store.put(owner, 'interaction', interaction.id, interaction)
+        this.store.put(owner, 'interaction-binding', interaction.id, { key, upstreamId })
+        this.store.event(owner, 'interaction.changed', interaction, c.id)
+        const current = this.store.require<Run>(owner, 'run', run.id)
+        current.status = 'waiting'
+        this.store.saveRun(owner, current)
+        this.notify(owner, c, current, undefined, interaction)
+      } else if (['message.complete', 'run.completed'].includes(type)) {
+        if (typeof p.text === 'string') resultMessage.content = p.text
+        if (p.status === 'interrupted') {
+          const current = this.store.require<Run>(owner, 'run', run.id)
+          current.status = 'interrupted'
+          this.store.saveRun(owner, current)
+          finish(new Error('已停止'))
+        } else if (p.error || p.status === 'failed') {
+          submitted = false
+          finish(new HttpError(502, String(p.error ?? '运行失败'), 'run_failed'))
+        } else if (!completing) {
+          completedEvidence = true
+          completing = true
+          let timeout: ReturnType<typeof setTimeout>
+          void Promise.race([
+            gateway.rpc('session.usage', { session_id: runtimeId }),
+            new Promise<undefined>((resolve) => {
+              timeout = setTimeout(() => resolve(undefined), 1000)
+            }),
+          ])
+            .then((usage) => {
+              if (usage && !this.closing) {
+                const used = usage.context_used ?? usage.used_tokens,
+                  limit = usage.context_max ?? usage.context_limit
+                this.store.put(owner, 'context', c.id, {
+                  ...usage,
+                  usedTokens: used,
+                  limitTokens: limit,
+                  percent:
+                    typeof used === 'number' && typeof limit === 'number' && limit > 0
+                      ? Math.round((used / limit) * 1000) / 10
+                      : undefined,
+                })
+                this.store.event(
+                  owner,
+                  'context.changed',
+                  this.store.get(owner, 'context', c.id),
+                  c.id,
+                )
+              }
+            })
+            .catch(() => {})
+            .finally(() => {
+              clearTimeout(timeout)
+              finish()
+            })
+        }
+        return
+      } else if (['error', 'message.error', 'run.failed'].includes(type)) {
+        submitted = false
+        finish(new HttpError(502, String(p.message ?? p.error ?? '运行失败'), 'run_failed'))
+        return
+      } else if (['session.usage', 'usage.update', 'context.update'].includes(type)) {
+        this.store.put(owner, 'context', c.id, p)
+        this.store.event(owner, 'context.changed', p, c.id)
+      } else if (type === 'session.info' && binding) {
+        const storedId = p.stored_session_id ?? p.session_key
+        if (typeof storedId === 'string' && storedId && storedId !== binding.storedId) {
+          binding.aliases = [...new Set([...binding.aliases, binding.storedId, storedId])]
+          binding.storedId = storedId
+          this.store.put(owner, 'binding', key, binding)
+        }
+      }
+      if (Date.now() - lastFlush >= 100) {
+        this.store.saveMessage(owner, resultMessage)
+        lastFlush = Date.now()
+      }
+    }
+    try {
+      await gateway.connect()
+      const opened = binding?.storedId
+        ? await gateway.rpc('session.resume', {
+            profile: agent.profile,
+            session_id: binding.storedId,
+            omit_messages: true,
+            close_on_disconnect: false,
+          })
+        : await gateway.rpc('session.create', {
+            profile: agent.profile,
+            title: `Yaoyao ${c.id}`,
+            source: 'yaoyao_workspace',
+            hidden: true,
+            room_plumbing: true,
+            close_on_disconnect: false,
+          })
+      runtimeId = String(opened.session_id ?? '')
+      const storedId = String(
+        opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? binding?.storedId ?? '',
+      )
+      if (
+        !runtimeId ||
+        !storedId ||
+        (opened.info?.profile_name && opened.info.profile_name !== agent.profile)
+      )
+        throw new Error('Hermes 会话身份不匹配')
+      binding = {
+        id: key,
+        nodeId: agent.nodeId,
+        profile: agent.profile,
+        storedId,
+        runtimeId,
+        aliases: [
+          ...new Set([
+            ...(binding?.aliases ?? []),
+            ...(binding ? [binding.storedId] : []),
+            storedId,
+          ]),
+        ],
+        runId: run.id,
+        messageId: resultMessage.id,
+      }
+      this.store.put(owner, 'binding', key, binding)
+      this.live.set(key, { gateway, runtimeId, runId: run.id, agentId: agent.id, done: finish })
+      if (this.closing || this.store.require<Run>(owner, 'run', run.id).status === 'interrupted')
+        throw new Error('运行已停止')
+      if (recovering) {
+        if (opened.running) {
+          const current = this.store.require<Run>(owner, 'run', run.id)
+          current.status = 'running'
+          this.store.saveRun(owner, current)
+        } else {
+          const response = await target.session.request(
+            `/api/sessions/${encodeURIComponent(storedId)}/messages`,
+            {
+              search: new URLSearchParams({
+                profile: agent.profile,
+                limit: '500',
+                order: 'latest',
+                include_compacted: 'true',
+              }),
+            },
+          )
+          if (response.status !== 200) throw new Error('无法核对历史')
+          const history = JSON.parse(response.body.toString()).messages ?? []
+          const marker = `[yaoyao-run:${run.id}:${resultMessage.id}]`
+          const index = history.findLastIndex(
+            (m: any) => m.role === 'user' && String(m.content ?? m.text).includes(marker),
+          )
+          const answer =
+            index >= 0
+              ? history
+                  .slice(index + 1)
+                  .filter((m: any) => m.role === 'assistant' && (m.content || m.text))
+                  .at(-1)
+              : undefined
+          if (!answer) throw new Error('无法确认本轮是否执行完成,请检查后停止此轮')
+          resultMessage.content = String(answer.content ?? answer.text)
+          finish()
+        }
+      } else {
+        if (opened.running) throw new HttpError(409, '上游会话仍在运行', 'session_busy')
+        const trigger = this.store.require<Message>(owner, 'message', run.messageId)
+        const attachmentRefs: string[] = []
+        for (const file of trigger.attachments) {
+          const record = this.uploads.records([file.id], owner)[0]!
+          const bytes = readFileSync(record.path).toString('base64')
+          const attached = record.mimeType.startsWith('image/')
+            ? await gateway.rpc('image.attach_bytes', {
+                session_id: runtimeId,
+                filename: record.name,
+                content_base64: bytes,
+              })
+            : await gateway.rpc('file.attach', {
+                session_id: runtimeId,
+                name: record.name,
+                data_url: `data:${record.mimeType};base64,${bytes}`,
+              })
+          if (attached.ref_text) attachmentRefs.push(String(attached.ref_text))
+        }
+        const members = run.turnConfiguration!.members
+        const rules = [
+          `你是 ${agent.name}。以下是用户为这个独立 Agent 配置的角色与规则(版本 ${agent.revision}):\n${agent.instructions}`,
+          c.kind === 'group'
+            ? `你正在群聊「${c.name}」发言。群成员:${members.map((a) => `@${a.name} (id=${a.id})`).join('、')}。\n群规则:${c.instructions}\n${c.mode === 'host' ? (agent.id === c.administratorId ? '你是管理员。必要时用精确 @成员名称 委派工作;收到结果后复核并给用户结论。任务完成时不要继续 @。' : '执行当前委派任务。公开给出结果,由管理员复核;不要安排其他成员。') : '按自己的职责回复,只在需要协作时 @成员。不要重复已完成的工作。'}`
+            : '',
+          '角色规则不赋予额外工具权限;仍遵守基础 Hermes 的工具和安全约束。',
+          `[yaoyao-run:${run.id}:${resultMessage.id}]`,
+        ]
+          .filter(Boolean)
+          .join('\n\n')
+        const text =
+          c.kind === 'group'
+            ? this.store
+                .messages(owner, c.id)
+              .filter((m) => !['queued','streaming'].includes(m.status))
+                .map(
+                  (m) => `${m.role === 'user' ? '用户' : (m.agentName ?? 'Agent')}:${m.content}`,
+                )
+                .join('\n\n')
+            : trigger.content
+        submitted = true
+        await gateway.rpc('prompt.submit', {
+          session_id: runtimeId,
+          text: `${rules}\n\n${text}\n${attachmentRefs.join('\n')}`,
+        })
+      }
+      return await completion
+    } catch (error) {
+      finish(error instanceof Error ? error : new Error('执行失败'))
+      return await completion
+    }
+  }
+  async respond(owner: string, id: string, answer: string): Promise<void> {
+    const interaction = this.store.require<WorkspaceInteraction>(owner, 'interaction', id)
+    if (interaction.resolved) return
+    const b = this.store.require<{ key: string; upstreamId: string }>(
+        owner,
+        'interaction-binding',
+        id,
+      ),
+      live = this.live.get(b.key)
+    if (!live || live.runId !== interaction.runId)
+      throw new HttpError(409, '请先恢复此轮连接', 'interaction_offline')
+    if (
+      interaction.kind === 'approval' &&
+      !['once', 'always', 'deny', 'allow', 'approve'].includes(answer)
+    )
+      throw new HttpError(400, '审批选项无效', 'invalid_approval')
+    await live.gateway.rpc(
+      interaction.kind === 'approval' ? 'approval.respond' : 'clarify.respond',
+      {
+        session_id: live.runtimeId,
+        request_id: b.upstreamId,
+        ...(interaction.kind === 'approval' ? { choice: answer } : { answer }),
+      },
+    )
+    interaction.resolved = true
+    this.store.put(owner, 'interaction', id, interaction)
+    this.store.event(owner, 'interaction.changed', interaction, interaction.conversationId)
+    const run = this.store.require<Run>(owner, 'run', interaction.runId)
+    run.status = 'running'
+    this.store.saveRun(owner, run)
+  }
+  async stop(owner: string, id: string): Promise<void> {
+    const run = this.store.require<Run>(owner, 'run', id)
+    if (['complete', 'failed', 'interrupted'].includes(run.status)) return
+    let live = [...this.live.values()].find((t) => t.runId === id)
+    if (live) {
+      await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId })
+      run.status = 'interrupted'
+      this.store.saveRun(owner, run)
+      live.done(new Error('已停止'))
+    } else {
+      const bindings = this.store
+        .list<WorkspaceBinding>(owner, 'binding')
+        .filter((b) => b.runId === id)
+      for (const b of bindings) {
+        const g = new WorkspaceGateway(this.nodes.target(owner, b.nodeId))
+        try {
+          await g.connect()
+          const s = await g.rpc('session.resume', {
+            profile: b.profile,
+            session_id: b.storedId,
+            close_on_disconnect: false,
+            omit_messages: true,
+          })
+          if (s.running) await g.rpc('session.interrupt', { session_id: s.session_id })
+        } finally {
+          g.close()
+        }
+      }
+      run.status = 'interrupted'
+      this.store.saveRun(owner, run)
+    }
+    for (const i of this.store
+      .list<WorkspaceInteraction>(owner, 'interaction')
+      .filter((i) => i.runId === id && !i.resolved)) {
+      i.resolved = true
+      this.store.put(owner, 'interaction', i.id, i)
+      this.store.event(owner, 'interaction.changed', i, i.conversationId)
+    }
+  }
+  async reconcile(owner: string, id: string): Promise<void> {
+    if (this.executing.has(id) || this.closing) return
+    const run = this.store.require<Run>(owner, 'run', id)
+    if (run.status !== 'uncertain' || !run.currentMessageId || !run.queue.length) return
+    this.executing.add(id)
+    try {
+      const agent = this.store.require<Agent>(owner, 'agent', run.queue[0]!),
+        c = this.store.require<Conversation>(owner, 'conversation', run.conversationId)
+      const message = await this.turn(owner, c, agent, run, true)
+      this.advance(owner, id, agent.id, message)
+    } finally {
+      this.executing.delete(id)
+    }
+    await this.execute(owner, id)
+  }
+  close(): void {
+    this.closing = true
+    for (const t of this.live.values()) {
+      t.gateway.close()
+      t.done(new Error('服务关闭'))
+    }
+    this.live.clear()
+  }
+}

+ 369 - 0
src/server/workspaceStore.ts

@@ -0,0 +1,369 @@
+import { chmodSync, mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { createHash, randomUUID } from 'node:crypto'
+import { DatabaseSync } from 'node:sqlite'
+import { EventEmitter } from 'node:events'
+import { z } from 'zod'
+import { HttpError } from './errors.js'
+import { notificationPlainText } from './notificationText.js'
+import type {
+  WorkspaceAgent as Agent,
+  WorkspaceConversation as Conversation,
+  WorkspaceMessage as Message,
+  WorkspaceRun as Run,
+  WorkspaceEvent,
+} from '../shared/workspace.js'
+
+const name = z
+  .string()
+  .trim()
+  .min(1)
+  .max(100)
+  .refine((v) => !/[\u0000-\u001f@]/.test(v), '名称不能包含 @ 或控制字符')
+const avatar = z
+  .string()
+  .max(2_800_000)
+  .default('')
+  .refine(
+    (v) => !v || /^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(v),
+    '头像须为 PNG、JPEG 或 WebP 图片',
+  )
+export const agentInput = z
+  .object({
+    name,
+    avatar,
+    instructions: z.string().max(24_000).default(''),
+    nodeId: z.string().default('local'),
+    profile: z.string().min(1).max(256),
+  })
+  .strict()
+export const agentPatch = z
+  .object({
+    name: name.optional(),
+    avatar: avatar.optional(),
+    instructions: z.string().max(24_000).optional(),
+    archived: z.boolean().optional(),
+  })
+  .strict()
+export const groupInput = z
+  .object({
+    name,
+    avatar,
+    memberIds: z.array(z.string().uuid()).min(2).max(8),
+    instructions: z.string().max(24_000).default(''),
+    administratorId: z.string().uuid(),
+    mode: z.enum(['host', 'free']).default('host'),
+    autoReplyIds: z.array(z.string().uuid()).max(8).default([]),
+    maxReplyRounds: z.number().int().min(1).max(100).default(3),
+  })
+  .strict()
+export const conversationPatch = z
+  .object({
+    name: name.optional(),
+    avatar: avatar.optional(),
+    instructions: z.string().max(24_000).optional(),
+    administratorId: z.string().uuid().optional(),
+    mode: z.enum(['host', 'free']).optional(),
+    autoReplyIds: z.array(z.string().uuid()).max(8).optional(),
+    maxReplyRounds: z.number().int().min(1).max(100).optional(),
+    archived: z.boolean().optional(),
+    pinned: z.boolean().optional(),
+  })
+  .strict()
+export function parse<T>(schema: z.ZodType<T>, value: unknown): T {
+  const parsed = schema.safeParse(value)
+  if (!parsed.success)
+    throw new HttpError(
+      400,
+      parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '),
+      'invalid_workspace_request',
+    )
+  return parsed.data
+}
+export class WorkspaceStore {
+  readonly db: DatabaseSync
+  readonly changes = new EventEmitter()
+  private transactionEvents: Array<{ owner: string; event: WorkspaceEvent }> | undefined
+  constructor(home: string) {
+    mkdirSync(home, { recursive: true, mode: 0o700 })
+    const path = join(home, 'workspace.sqlite3')
+    this.db = new DatabaseSync(path)
+    chmodSync(path, 0o600)
+    this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
+      CREATE TABLE IF NOT EXISTS workspace_entities(owner TEXT NOT NULL,kind TEXT NOT NULL,id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(owner,kind,id));
+      CREATE TABLE IF NOT EXISTS workspace_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,owner TEXT NOT NULL,type TEXT NOT NULL,conversation_id TEXT,data TEXT NOT NULL);
+      CREATE INDEX IF NOT EXISTS workspace_events_owner ON workspace_events(owner,seq);
+      CREATE TABLE IF NOT EXISTS workspace_commands(owner TEXT NOT NULL,id TEXT NOT NULL,fingerprint TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(owner,id));`)
+    this.changes.setMaxListeners(0)
+  }
+  get<T>(owner: string, kind: string, id: string): T | undefined {
+    const row = this.db
+      .prepare('SELECT data FROM workspace_entities WHERE owner=? AND kind=? AND id=?')
+      .get(owner, kind, id)
+    return row ? (JSON.parse(String(row.data)) as T) : undefined
+  }
+  require<T>(owner: string, kind: string, id: string): T {
+    const value = this.get<T>(owner, kind, id)
+    if (!value) throw new HttpError(404, '记录不存在', 'workspace_not_found')
+    return value
+  }
+  list<T>(owner: string, kind: string): T[] {
+    return this.db
+      .prepare('SELECT data FROM workspace_entities WHERE owner=? AND kind=?')
+      .all(owner, kind)
+      .map((r) => JSON.parse(String(r.data)) as T)
+  }
+  owners(): string[] {
+    return this.db
+      .prepare('SELECT DISTINCT owner FROM workspace_entities')
+      .all()
+      .map((r) => String(r.owner))
+  }
+  put(owner: string, kind: string, id: string, value: unknown): void {
+    this.db
+      .prepare(
+        'INSERT INTO workspace_entities VALUES(?,?,?,?) ON CONFLICT(owner,kind,id) DO UPDATE SET data=excluded.data',
+      )
+      .run(owner, kind, id, JSON.stringify(value))
+  }
+  remove(owner: string, kind: string, id: string): void {
+    this.db
+      .prepare('DELETE FROM workspace_entities WHERE owner=? AND kind=? AND id=?')
+      .run(owner, kind, id)
+  }
+  atomic<T>(fn: () => T): T {
+    if (this.transactionEvents) return fn()
+    this.db.exec('BEGIN IMMEDIATE')
+    this.transactionEvents = []
+    try {
+      const result = fn()
+      this.db.exec('COMMIT')
+      const events = this.transactionEvents
+      this.transactionEvents = undefined
+      for (const entry of events) this.changes.emit(entry.owner, entry.event)
+      return result
+    } catch (error) {
+      this.db.exec('ROLLBACK')
+      this.transactionEvents = undefined
+      throw error
+    }
+  }
+  event(owner: string, type: string, data: unknown, conversationId?: string): number {
+    const seq = Number(
+      this.db
+        .prepare('INSERT INTO workspace_events(owner,type,conversation_id,data) VALUES(?,?,?,?)')
+        .run(owner, type, conversationId ?? null, JSON.stringify(data)).lastInsertRowid,
+    )
+    const event = { seq, type, conversationId, data }
+    if (this.transactionEvents) this.transactionEvents.push({ owner, event })
+    else this.changes.emit(owner, event)
+    return seq
+  }
+  events(owner: string, after: number): WorkspaceEvent[] {
+    return this.db
+      .prepare('SELECT * FROM workspace_events WHERE owner=? AND seq>? ORDER BY seq LIMIT 250')
+      .all(owner, after)
+      .map((r) => ({
+        seq: Number(r.seq),
+        type: String(r.type),
+        conversationId: r.conversation_id ? String(r.conversation_id) : undefined,
+        data: JSON.parse(String(r.data)),
+      }))
+  }
+  cursor(owner: string): number {
+    return Number(
+      this.db
+        .prepare('SELECT coalesce(max(seq),0) AS n FROM workspace_events WHERE owner=?')
+        .get(owner)!.n,
+    )
+  }
+  command<T>(owner: string, id: string, payload: unknown, fn: () => T): T {
+    parse(z.string().uuid(), id)
+    const fingerprint = createHash('sha256').update(JSON.stringify(payload)).digest('hex')
+    return this.atomic(() => {
+      const old = this.db
+        .prepare('SELECT fingerprint,result FROM workspace_commands WHERE owner=? AND id=?')
+        .get(owner, id)
+      if (old) {
+        if (old.fingerprint !== fingerprint)
+          throw new HttpError(409, '请求编号已用于其他内容', 'idempotency_conflict')
+        return JSON.parse(String(old.result)) as T
+      }
+      const result = fn()
+      this.db
+        .prepare('INSERT INTO workspace_commands VALUES(?,?,?,?)')
+        .run(owner, id, fingerprint, JSON.stringify(result))
+      return result
+    })
+  }
+  createAgent(owner: string, input: unknown): Agent {
+    const body = parse(agentInput, input)
+    return this.atomic(() => {
+      if (
+        this.list<Agent>(owner, 'agent').some(
+          (a) => a.name.toLocaleLowerCase() === body.name.toLocaleLowerCase(),
+        )
+      )
+        throw new HttpError(409, 'Agent 名称已存在', 'duplicate_agent_name')
+      const now = Date.now(),
+        id = randomUUID()
+      const agent: Agent = {
+        ...body,
+        id,
+        archived: false,
+        revision: 1,
+        createdAt: now,
+        updatedAt: now,
+      }
+      this.put(owner, 'agent', id, agent)
+      const conversation: Conversation = {
+        id: randomUUID(),
+        kind: 'direct',
+        name: agent.name,
+        avatar: agent.avatar,
+        memberIds: [id],
+        instructions: '',
+        administratorId: id,
+        mode: 'host',
+        autoReplyIds: [],
+        maxReplyRounds: 1,
+        archived: false,
+        pinned: false,
+        readSeq: 0,
+        lastSeq: 0,
+        preview: '',
+        createdAt: now,
+        updatedAt: now,
+      }
+      this.put(owner, 'conversation', conversation.id, conversation)
+      this.event(owner, 'agent.changed', agent)
+      this.event(owner, 'conversation.changed', conversation, conversation.id)
+      return agent
+    })
+  }
+  updateAgent(owner: string, id: string, input: unknown): Agent {
+    const patch = parse(agentPatch, input)
+    return this.atomic(() => {
+      const agent = this.require<Agent>(owner, 'agent', id)
+      if (
+        patch.name &&
+        this.list<Agent>(owner, 'agent').some(
+          (a) => a.id !== id && a.name.toLocaleLowerCase() === patch.name!.toLocaleLowerCase(),
+        )
+      )
+        throw new HttpError(409, 'Agent 名称已存在', 'duplicate_agent_name')
+      const next = { ...agent, ...patch, revision: agent.revision + 1, updatedAt: Date.now() }
+      this.put(owner, 'agent', id, next)
+      this.event(owner, 'agent.changed', next)
+      for (const c of this.list<Conversation>(owner, 'conversation').filter(
+        (c) => c.kind === 'direct' && c.memberIds[0] === id,
+      )) {
+        Object.assign(c, { name: next.name, avatar: next.avatar, archived: next.archived })
+        this.put(owner, 'conversation', c.id, c)
+        this.event(owner, 'conversation.changed', c, c.id)
+      }
+      return next
+    })
+  }
+  createGroup(owner: string, input: unknown): Conversation {
+    const body = parse(groupInput, input)
+    const ids = new Set(body.memberIds)
+    if (
+      ids.size !== body.memberIds.length ||
+      !ids.has(body.administratorId) ||
+      body.autoReplyIds.some((id) => !ids.has(id))
+    )
+      throw new HttpError(400, '群成员或管理员无效', 'invalid_members')
+    for (const id of ids)
+      if (this.require<Agent>(owner, 'agent', id).archived)
+        throw new HttpError(409, '已归档 Agent 不能加入新群', 'agent_archived')
+    const now = Date.now()
+    const c: Conversation = {
+      ...body,
+      id: randomUUID(),
+      kind: 'group',
+      archived: false,
+      pinned: false,
+      readSeq: 0,
+      lastSeq: 0,
+      preview: '',
+      createdAt: now,
+      updatedAt: now,
+    }
+    this.atomic(() => {
+      this.put(owner, 'conversation', c.id, c)
+      this.event(owner, 'conversation.changed', c, c.id)
+    })
+    return c
+  }
+  updateConversation(owner: string, id: string, input: unknown): Conversation {
+    const patch = parse(conversationPatch, input),
+      c = this.require<Conversation>(owner, 'conversation', id)
+    if (c.kind === 'direct' && Object.keys(patch).some((k) => k !== 'pinned'))
+      throw new HttpError(400, '请编辑 Agent 资料', 'edit_agent_instead')
+    if (
+      (patch.administratorId && !c.memberIds.includes(patch.administratorId)) ||
+      patch.autoReplyIds?.some((a) => !c.memberIds.includes(a))
+    )
+      throw new HttpError(400, '只能选择现有成员', 'invalid_members')
+    const next = { ...c, ...patch, updatedAt: Date.now() }
+    this.atomic(() => {
+      this.put(owner, 'conversation', id, next)
+      this.event(owner, 'conversation.changed', next, id)
+    })
+    return next
+  }
+  messages(
+    owner: string,
+    conversationId: string,
+    before = Number.MAX_SAFE_INTEGER,
+    limit = 100,
+  ): Message[] {
+    this.require(owner, 'conversation', conversationId)
+    return this.db
+      .prepare(
+        `SELECT data FROM workspace_entities WHERE owner=? AND kind='message' AND json_extract(data,'$.conversationId')=? AND json_extract(data,'$.seq')<? ORDER BY json_extract(data,'$.seq') DESC LIMIT ?`,
+      )
+      .all(owner, conversationId, before, limit)
+      .map((r) => JSON.parse(String(r.data)) as Message)
+      .reverse()
+  }
+  saveMessage(owner: string, message: Message): void {
+    this.atomic(() => {
+      const c = this.require<Conversation>(owner, 'conversation', message.conversationId)
+      if (!message.seq) message.seq = c.lastSeq + 1
+      c.lastSeq = Math.max(c.lastSeq, message.seq)
+      c.updatedAt = Date.now()
+      c.preview = notificationPlainText(message.content, { maximum: 160, fallback: '' })
+      this.put(owner, 'message', message.id, message)
+      this.put(owner, 'conversation', c.id, c)
+      this.event(owner, 'message.changed', message, c.id)
+      this.event(owner, 'conversation.changed', c, c.id)
+    })
+  }
+  saveRun(owner: string, run: Run): void {
+    this.atomic(() => {
+      const c = this.require<Conversation>(owner, 'conversation', run.conversationId)
+      const terminal = ['complete', 'failed', 'interrupted'].includes(run.status)
+      c.activeRunId = terminal ? undefined : run.id
+      run.updatedAt = Date.now()
+      this.put(owner, 'run', run.id, run)
+      this.put(owner, 'conversation', c.id, c)
+      this.event(owner, 'run.changed', run, c.id)
+      this.event(owner, 'conversation.changed', c, c.id)
+    })
+  }
+  ownsUpstream(id: string): boolean {
+    return Boolean(
+      this.db
+        .prepare(
+          `SELECT 1 FROM workspace_entities WHERE kind='binding' AND (json_extract(data,'$.storedId')=? OR json_extract(data,'$.runtimeId')=? OR EXISTS(SELECT 1 FROM json_each(json_extract(data,'$.aliases')) WHERE value=?)) LIMIT 1`,
+        )
+        .get(id, id, id),
+    )
+  }
+  close(): void {
+    this.changes.removeAllListeners()
+    this.db.close()
+  }
+}

+ 1 - 0
src/shared/types.ts

@@ -463,6 +463,7 @@ export interface GroupSocketEnvelope {
 }
 
 export interface FileOrigin {
+  workspaceConversationId?: string
   id?: number | string
   profile?: string
   sessionId?: string

+ 92 - 0
src/shared/workspace.ts

@@ -0,0 +1,92 @@
+/** Application-owned identities. Hermes profile/session IDs never identify a chat. */
+export interface WorkspaceAgent {
+  id: string
+  name: string
+  avatar: string
+  instructions: string
+  nodeId: string
+  profile: string
+  archived: boolean
+  revision: number
+  createdAt: number
+  updatedAt: number
+}
+export interface WorkspaceConversation {
+  id: string
+  kind: 'direct' | 'group'
+  name: string
+  avatar: string
+  memberIds: string[]
+  instructions: string
+  administratorId: string
+  mode: 'host' | 'free'
+  autoReplyIds: string[]
+  maxReplyRounds: number
+  archived: boolean
+  pinned: boolean
+  readSeq: number
+  lastSeq: number
+  preview: string
+  activeRunId?: string
+  createdAt: number
+  updatedAt: number
+}
+export interface WorkspaceFile {
+  id: string
+  name: string
+  mimeType: string
+  size: number
+  createdAt: number
+  sourcePath?: string
+  conversationId?: string
+  messageId?: string
+  profile?: string
+  sender: 'user' | 'agent'
+}
+export interface WorkspaceMessage {
+  id: string
+  conversationId: string
+  seq: number
+  role: 'user' | 'assistant' | 'system'
+  agentId?: string
+  agentName?: string
+  content: string
+  reasoning: string
+  runId?: string
+  status: 'queued' | 'streaming' | 'complete' | 'failed' | 'interrupted' | 'uncertain'
+  attachments: WorkspaceFile[]
+  tools: Array<Record<string, unknown>>
+  createdAt: number
+}
+export interface WorkspaceRun {
+  id: string
+  conversationId: string
+  messageId: string
+  mentionIds: string[]
+  status: 'queued' | 'running' | 'waiting' | 'complete' | 'failed' | 'interrupted' | 'uncertain'
+  round: number
+  error?: string
+  createdAt: number
+  updatedAt: number
+}
+export interface WorkspaceInteraction {
+  id: string
+  conversationId: string
+  runId: string
+  agentId: string
+  kind: 'approval' | 'clarification'
+  message: string
+  choices: string[]
+  resolved: boolean
+}
+export interface WorkspaceEvent {
+  seq: number
+  type: string
+  conversationId?: string
+  data: unknown
+}
+export interface WorkspaceSource {
+  nodeId: string
+  profile: string
+  name: string
+}

+ 3 - 3
tests/client/remoteNodeFiles.test.ts

@@ -10,7 +10,7 @@ describe('remote node file links', () => {
       '[日志](file:///Users/remote/Agents/run.log)',
     ].join('\n')
     const rewritten = rewriteRemoteNodeFiles(content, node)
-    expect(rewritten).toContain(`/api/plugins/yaoyao/v1/nodes/${node}/files?path=%2FUsers%2Fremote%2FAgents%2Fresult%20one.png`)
+    expect(rewritten).toContain(`/api/app/groups/nodes/${node}/files?path=%2FUsers%2Fremote%2FAgents%2Fresult%20one.png`)
     expect(rewritten).toContain('path=%2FUsers%2Fremote%2FAgents%2Freport.pdf')
     expect(rewritten).toContain('path=%2FUsers%2Fremote%2FAgents%2Frun.log')
     expect(rewritten).not.toContain('](</Users/remote')
@@ -25,8 +25,8 @@ describe('remote node file links', () => {
 
     const rewritten = rewriteRemoteNodeFiles(content, node)
 
-    expect(rewritten).toContain(`![smoke_zimage_turbo_00001_.png](/api/plugins/yaoyao/v1/nodes/${node}/files?path=%2FUsers%2Fsamien%2FAgents%2Fsmoke_zimage_turbo_00001_.png)`)
-    expect(rewritten).toContain(`[远程 报告.pdf](/api/plugins/yaoyao/v1/nodes/${node}/files?path=%2FUsers%2Fsamien%2FAgents%2F%E8%BF%9C%E7%A8%8B%20%E6%8A%A5%E5%91%8A.pdf)`)
+    expect(rewritten).toContain(`![smoke_zimage_turbo_00001_.png](/api/app/groups/nodes/${node}/files?path=%2FUsers%2Fsamien%2FAgents%2Fsmoke_zimage_turbo_00001_.png)`)
+    expect(rewritten).toContain(`[远程 报告.pdf](/api/app/groups/nodes/${node}/files?path=%2FUsers%2Fsamien%2FAgents%2F%E8%BF%9C%E7%A8%8B%20%E6%8A%A5%E5%91%8A.pdf)`)
     expect(rewritten).not.toContain('MEDIA:')
   })
 

+ 0 - 3
tests/client/systemUpdate.test.ts

@@ -2,7 +2,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
 import {
   applySystemUpdate,
   checkSystemUpdate,
-  reconcileYaoyaoPlugin,
   rollbackSystemUpdate,
   systemUpdateJob,
   systemUpdateStatus,
@@ -33,7 +32,6 @@ describe('system update client protocol', () => {
     await applySystemUpdate('0.3.0')
     await systemUpdateJob('11111111-1111-4111-8111-111111111111')
     await rollbackSystemUpdate()
-    await reconcileYaoyaoPlugin()
 
     expect(calls.map(call => call.path)).toEqual([
       '/api/app/system/update/status',
@@ -41,7 +39,6 @@ describe('system update client protocol', () => {
       '/api/app/system/update/apply',
       '/api/app/system/update/jobs/11111111-1111-4111-8111-111111111111',
       '/api/app/system/update/rollback',
-      '/api/app/plugins/yaoyao/reconcile',
     ])
     expect(new Headers(calls[1]!.init?.headers).get('X-CSRF-Token')).toBe('csrf-system-update')
     expect(calls[2]!.init?.body).toBe(JSON.stringify({ targetVersion: '0.3.0' }))

+ 1 - 1
tests/client/systemUpdatePanel.test.ts

@@ -70,7 +70,7 @@ describe('SystemUpdatePanel', () => {
     const wrapper = mount(SystemUpdatePanel, { global: { stubs: { AppIcon: true } } })
     await flushPromises()
     expect(wrapper.text()).toContain('9119 离线或认证失败也不影响')
-    expect(wrapper.text()).toContain('未检测(不影响 Web 升级)')
+    expect(wrapper.text()).not.toContain('当前插件')
     expect(wrapper.find('.version-warning').exists()).toBe(false)
     const apply = wrapper.find<HTMLButtonElement>('.solid-button')
     expect(apply.element.disabled).toBe(false)

+ 83 - 0
tests/e2e/workspace-chat.spec.ts

@@ -0,0 +1,83 @@
+import { test, expect, type Page } from '@playwright/test'
+async function login(page: Page) {
+  await page.goto('/conversations')
+  await page.getByRole('textbox', { name: '账号', exact: true }).fill('fixture')
+  await page.getByRole('textbox', { name: '密码', exact: true }).fill('fixture-pass')
+  await page.getByRole('button', { name: '登录', exact: true }).click()
+  await expect(page.getByRole('heading', { name: '从一个角色开始' })).toBeVisible()
+}
+async function createAgent(page: Page, name: string) {
+  await page.getByRole('button', { name: '+ 创建 Agent', exact: true }).click()
+  const dialog = page.getByRole('dialog')
+  await dialog.getByRole('textbox', { name: '名称', exact: true }).fill(name)
+  await dialog
+    .getByRole('textbox', { name: '角色提示词与规则', exact: true })
+    .fill(`你是${name},每次回复给出验收证据。`)
+  await dialog.getByRole('button', { name: '保存', exact: true }).click()
+  await expect(page.getByRole('heading', { name, exact: true })).toBeVisible()
+}
+test('created roles and immutable teams share a durable chat list without plugin calls', async ({
+  page,
+  context,
+}, testInfo) => {
+  const pluginCalls: string[] = []
+  page.on('request', (r) => {
+    if (r.url().includes('/plugins/yaoyao')) pluginCalls.push(r.url())
+  })
+  await login(page)
+  await createAgent(page, '产品经理')
+  await page.getByRole('textbox', { name: '消息', exact: true }).fill('请说明角色职责')
+  await page.getByRole('button', { name: '发送', exact: true }).click()
+  await expect(page.locator('.message.assistant')).toContainText('我是产品经理')
+  await expect(page.locator('.message.assistant a').first()).toHaveAttribute(
+    'href',
+    /\/api\/app\/files\/.+\/download/,
+  )
+  const directURL = page.url()
+  await createAgent(page, '开发工程师')
+  await expect(page.locator('.message')).toHaveCount(0)
+  await page.getByRole('button', { name: '+ 创建群聊', exact: true }).click()
+  const dialog = page.getByRole('dialog')
+  await dialog.getByRole('textbox', { name: '名称', exact: true }).fill('产品开发团队')
+  await dialog.getByRole('checkbox', { name: '产品经理', exact: true }).check()
+  await dialog.getByRole('checkbox', { name: '开发工程师', exact: true }).check()
+  await dialog
+    .getByRole('combobox', { name: '管理员', exact: true })
+    .selectOption({ label: '产品经理' })
+  await dialog.getByRole('button', { name: '保存', exact: true }).click()
+  await expect(page.getByRole('heading', { name: '产品开发团队', exact: true })).toBeVisible()
+  await expect(page.locator('.desktop-sidebar .conversation-row')).toHaveCount(3)
+  await expect(page.locator('.desktop-sidebar')).not.toContainText('话题')
+  await expect(page.locator('.desktop-sidebar .sidebar-account-switcher')).not.toContainText(
+    '通用助手',
+  )
+  await page.getByRole('button', { name: '设置', exact: true }).click()
+  await expect(dialog.getByRole('checkbox', { name: '产品经理', exact: true })).toBeDisabled()
+  await expect(dialog.getByRole('checkbox', { name: '开发工程师', exact: true })).toBeDisabled()
+  await dialog.getByRole('button', { name: '取消', exact: true }).click()
+  await page.getByRole('checkbox', { name: '@开发工程师', exact: true }).check()
+  await page.getByRole('textbox', { name: '消息', exact: true }).fill('给出实现结果')
+  await page.getByRole('button', { name: '发送', exact: true }).click()
+  await expect(page.locator('.message.assistant')).toHaveCount(2)
+  await expect(page.locator('.run-status')).toHaveCount(0)
+  const second = await context.newPage()
+  await second.goto(page.url())
+  await expect(second.locator('.message.assistant')).toHaveCount(2)
+  await page.screenshot({ path: testInfo.outputPath('mixed-chats.png'), fullPage: true })
+  const groupURL=page.url()
+  await page.getByRole('button',{name:'文件库',exact:true}).click()
+  await page.getByRole('button',{name:'查看来源',exact:true}).first().click()
+  await expect(page).toHaveURL(groupURL)
+  await page.getByRole('button', { name: '归档', exact: true }).click()
+  await expect(page.locator('.desktop-sidebar .conversation-row')).toHaveCount(2)
+  await page.getByRole('checkbox', { name: '显示已归档', exact: true }).first().check()
+  await expect(page.locator('.desktop-sidebar .conversation-row')).toHaveCount(1)
+  await page.getByRole('button', { name: '恢复', exact: true }).click()
+  await page.goto(directURL)
+  await expect(page.locator('.message.assistant')).toHaveCount(1)
+  await expect(page.locator('.message.assistant')).toContainText('我是产品经理')
+  await page.getByRole('button', { name: '原生对话', exact: true }).click()
+  await expect(page).toHaveURL(/\/chat/)
+  expect(pluginCalls).toEqual([])
+  await second.close()
+})

+ 232 - 0
tests/fixtures/workspace-server.ts

@@ -0,0 +1,232 @@
+/** Isolated, deterministic standard-Hermes fixture. It exposes no plugin APIs. */
+import { createServer } from 'node:http'
+import { mkdtempSync, readFileSync, existsSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { randomUUID, randomBytes, scryptSync } from 'node:crypto'
+import { WebSocketServer } from 'ws'
+import serve from 'koa-static'
+import { createApplication, createNodeServer } from '../../src/server/app.js'
+import { loadServerConfig } from '../../src/server/config.js'
+import { LocalAuthStore } from '../../src/server/localAuth.js'
+const home =
+  process.env.WORKSPACE_FIXTURE_HOME || mkdtempSync(join(tmpdir(), 'yaoyao-workspace-browser-'))
+const port = Number(process.env.WORKSPACE_FIXTURE_PORT || 18800),
+  upstreamPort = Number(process.env.WORKSPACE_FIXTURE_UPSTREAM_PORT || 19119)
+const sessions = new Map<
+  string,
+  {
+    id: string
+    profile: string
+    messages: Array<{ role: string; content: string; id: string; timestamp: number }>
+    running: boolean
+  }
+>()
+const calls: Array<{ method: string; params: Record<string, unknown> }> = []
+const upstream = createServer((req, res) => {
+  const url = new URL(req.url || '/', `http://127.0.0.1:${upstreamPort}`)
+  res.setHeader('content-type', 'application/json')
+  const send = (v: unknown) => res.end(JSON.stringify(v))
+  if (url.pathname.includes('/plugins/')) {
+    res.statusCode = 404
+    send({ error: 'This fixture has no plugins' })
+    return
+  }
+  if (url.pathname === '/__calls') {
+    send({ calls })
+    return
+  }
+  if (url.pathname === '/api/status') {
+    send({ auth_required: true, overall: 'ready', gateway_running: true })
+    return
+  }
+  if (url.pathname === '/api/auth/me') {
+    send({ user_id: 'fixture', display_name: 'Fixture', provider: 'basic' })
+    return
+  }
+  if (url.pathname === '/auth/password-login') {
+    res.setHeader('set-cookie', 'hermes_session_at=fixture; Path=/; HttpOnly')
+    send({ ok: true })
+    return
+  }
+  if (url.pathname === '/api/auth/ws-ticket') {
+    send({ ticket: 'fixture' })
+    return
+  }
+  if (url.pathname === '/api/profiles') {
+    send({
+      profiles: [
+        { name: 'default', display_name: '通用助手', is_default: true, gateway_running: true },
+        { name: 'server', display_name: '开发助手', is_default: false, gateway_running: true },
+      ],
+    })
+    return
+  }
+  if (url.pathname === '/api/sessions') {
+    send({
+      sessions: [...sessions.values()].map((s) => ({
+        id: s.id,
+        title: 'Internal',
+        source: 'yaoyao_workspace',
+        profile: s.profile,
+      })),
+      total: sessions.size,
+    })
+    return
+  }
+  const history = /^\/api\/sessions\/([^/]+)\/messages$/.exec(url.pathname)
+  if (history) {
+    send({ messages: sessions.get(history[1]!)?.messages || [] })
+    return
+  }
+  if (url.pathname === '/api/files/download') {
+    res.setHeader('content-type', 'text/plain')
+    res.end('Fixture report\n')
+    return
+  }
+  send({ ok: true })
+})
+const wss = new WebSocketServer({ server: upstream, path: '/api/ws' })
+wss.on('connection', (socket) => {
+  const runtimes = new Map<string, string>()
+  socket.send(
+    JSON.stringify({
+      method: 'event',
+      params: { type: 'gateway.ready', payload: { capabilities: [] } },
+    }),
+  )
+  socket.on('message', (raw) => {
+    const f = JSON.parse(String(raw))
+    calls.push({ method: f.method, params: f.params })
+    const respond = (result: unknown) => socket.send(JSON.stringify({ id: f.id, result }))
+    const event = (type: string, payload: unknown, sessionId: string) => {
+      if (socket.readyState === 1)
+        socket.send(
+          JSON.stringify({
+            method: 'event',
+            params: { type, payload, session_id: sessionId, profile: 'default' },
+          }),
+        )
+    }
+    if (f.method === 'profiles.list') {
+      respond({
+        profiles: [
+          { name: 'default', display_name: '通用助手' },
+          { name: 'server', display_name: '开发助手', is_default: false, gateway_running: true },
+        ],
+      })
+      return
+    }
+    if (f.method === 'session.create' || f.method === 'session.resume') {
+      let stored = f.method === 'session.resume' ? sessions.get(f.params.session_id) : undefined
+      if (!stored) {
+        stored = { id: randomUUID(), profile: f.params.profile, messages: [], running: false }
+        sessions.set(stored.id, stored)
+      }
+      const runtimeId = randomUUID()
+      runtimes.set(runtimeId, stored.id)
+      respond({
+        session_id: runtimeId,
+        stored_session_id: stored.id,
+        session_key: stored.id,
+        running: stored.running,
+        info: { profile_name: stored.profile },
+      })
+      return
+    }
+    const stored = sessions.get(runtimes.get(f.params.session_id) ?? '')
+    if (f.method === 'prompt.submit' && stored) {
+      stored.running = true
+      stored.messages.push({
+        id: randomUUID(),
+        role: 'user',
+        content: f.params.text,
+        timestamp: Date.now() / 1000,
+      })
+      respond({ status: 'streaming' })
+      const name = /你是 (.*?)。/.exec(f.params.text)?.[1] || '助手'
+      const text = `我是${name}。已按角色规则处理这条消息。\n\n- 会话独立保存\n- 可以继续交流\n\n[报告](/tmp/workspace-report.txt)`
+      event('message.start', {}, f.params.session_id)
+      setTimeout(() => event('message.delta', { text: text.slice(0, 12) }, f.params.session_id), 80)
+      setTimeout(() => {
+        stored!.running = false
+        stored!.messages.push({
+          id: randomUUID(),
+          role: 'assistant',
+          content: text,
+          timestamp: Date.now() / 1000,
+        })
+        event('message.complete', { text, status: 'complete' }, f.params.session_id)
+      }, 250)
+      return
+    }
+    if (f.method === 'session.interrupt' && stored) stored.running = false
+    if (f.method === 'file.attach') {
+      respond({ attached: true, ref_text: '@file:fixture-upload.txt' })
+      return
+    }
+    respond({ ok: true, status: 'interrupted' })
+  })
+})
+await new Promise<void>((resolve) => upstream.listen(upstreamPort, '127.0.0.1', resolve))
+const config = loadServerConfig({
+  HERMES_YAOYAO_HOME: home,
+  HERMES_YAOYAO_PORT: String(port),
+  HERMES_YAOYAO_UPSTREAM: `http://127.0.0.1:${upstreamPort}`,
+  HERMES_YAOYAO_UPSTREAM_USERNAME: 'fixture',
+  HERMES_YAOYAO_UPSTREAM_PASSWORD: 'fixture',
+  HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
+})
+// Synthetic credentials are seeded only into this disposable fixture directory.
+const usersPath = join(home, 'users.json')
+if (!existsSync(usersPath)) {
+  const salt = randomBytes(16),
+    now = Date.now()
+  writeFileSync(
+    usersPath,
+    JSON.stringify({
+      version: 1,
+      users: [
+        {
+          id: randomUUID(),
+          username: 'fixture',
+          normalizedUsername: 'fixture',
+          role: 'admin',
+          enabled: true,
+          mustChangePassword: false,
+          salt: salt.toString('base64'),
+          passwordHash: scryptSync('fixture-pass', salt, 32, {
+            N: 2 ** 14,
+            r: 8,
+            p: 1,
+            maxmem: 64 * 1024 * 1024,
+          }).toString('base64'),
+          authVersion: 1,
+          createdAt: now,
+          updatedAt: now,
+        },
+      ],
+    }),
+    { mode: 0o600 },
+  )
+}
+const auth = new LocalAuthStore(home, false)
+const runtime = createApplication({ config, auth }),
+  node = createNodeServer(runtime)
+runtime.app.use(serve(resolve('dist')))
+runtime.app.use((ctx) => {
+  if (!ctx.path.startsWith('/api/')) {
+    ctx.type = 'html'
+    ctx.body = readFileSync(resolve('dist/index.html'))
+  }
+})
+await new Promise<void>((resolve) => node.server.listen(port, '127.0.0.1', resolve))
+process.stdout.write(`Workspace fixture http://127.0.0.1:${port}; home=${home}\n`)
+for (const signal of ['SIGTERM', 'SIGINT'])
+  process.once(signal, () => {
+    void node.close().then(() => {
+      for (const socket of wss.clients) socket.terminate()
+      wss.close()
+      upstream.close()
+    })
+  })

+ 1 - 3
tests/server/agentManagementRoutes.test.ts

@@ -101,11 +101,9 @@ describe('Agent management admin routes', () => {
       ['POST', '/api/providers/custom-endpoints/validate', ''],
       ['POST', '/api/providers/custom-endpoints/local/activate', '?profile=worker'],
       ['DELETE', '/api/providers/custom-endpoints/local', '?profile=worker'],
-      ['GET', '/api/plugins/yaoyao/voice/settings', ''],
-      ['PUT', '/api/plugins/yaoyao/voice/settings', ''],
     ])
     expect(featureCalls[1]!.body).toMatchObject({ name: 'Local', model: 'model-a' })
-    expect(featureCalls[6]!.body).not.toHaveProperty('apiKey')
+    expect(calls.some(call => call.url.pathname.includes('/plugins/yaoyao'))).toBe(false)
     const configWrite = calls.find(call => call.url.pathname === '/api/config' && call.method === 'PUT')!
     expect(configWrite.body).toMatchObject({ config: { custom_providers: [{ name: 'tingly', base_url: 'http://tingly.test/v2', model: 'omni-2', models: { omni: {}, 'omni-2': {} }, models_discovered: false }] } })
     const envWrite = calls.find(call => call.url.pathname === '/api/env' && call.method === 'PUT')!

+ 6 - 317
tests/server/app.test.ts

@@ -78,7 +78,7 @@ function fakeGateway(records: RecordedRequest[]): typeof fetch {
           user_id: 'user-1', display_name: '测试用户', provider: 'basic',
         })
       case '/api/profiles':
-        return jsonResponse({ profiles: [{ name: 'default', is_default: true }] })
+        return jsonResponse({ profiles: [{ name: 'default', is_default: true, display_name: '竹儿' }] })
       case '/api/plugins/yaoyao/profiles':
         return jsonResponse({ profiles: [{ name: 'default', botName: '竹儿', agentName: '旧插件名称', isDefault: true }] })
       case '/api/auth/providers':
@@ -116,187 +116,6 @@ describe('8800 BFF', () => {
     runtimes.push(restarted)
     expect(restarted.csrf.verify(cookies, bootstrap.body.csrfToken)).toBe(true)
   })
-
-  it('installs a fresh Yaoyao plugin through authenticated 9119 without restarting it', async () => {
-    const records: RecordedRequest[] = []
-    const baseGateway = fakeGateway(records)
-    const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
-      const url = new URL(input instanceof Request ? input.url : String(input))
-      if (url.pathname === '/api/dashboard/plugins') return jsonResponse([])
-      if (url.pathname === '/api/dashboard/agent-plugins/install') {
-        const rawBody = typeof init?.body === 'string' ? init.body : '{}'
-        records.push({
-          path: url.pathname,
-          method: init?.method ?? 'GET',
-          search: url.searchParams,
-          headers: new Headers(init?.headers),
-          body: JSON.parse(rawBody),
-        })
-        return jsonResponse({ ok: true, plugin_name: 'yaoyao', enabled: true })
-      }
-      return baseGateway(input, init)
-    }) as typeof fetch
-    const runtime = createApplication({
-      config: makeConfig(),
-      fetchImpl,
-    })
-    runtimes.push(runtime)
-    const bootstrap = await request(runtime.app.callback())
-      .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
-
-    const response = await request(runtime.app.callback())
-      .post('/api/app/plugins/yaoyao/install')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ force: false })
-      .expect(200)
-
-    const install = records.find((entry) => entry.path === '/api/dashboard/agent-plugins/install')
-    expect(install?.body).toEqual({
-      identifier: 'https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao',
-      force: false,
-      enable: true,
-    })
-    expect(response.body).toMatchObject({
-      ok: true,
-      plugin_name: 'yaoyao',
-      restarted: false,
-      restartRequired: false,
-    })
-  })
-
-  it('automatically reconciles an older Yaoyao plugin through 9119', async () => {
-    const records: RecordedRequest[] = []
-    const baseGateway = fakeGateway(records)
-    let pluginVersion = '1.7.1'
-    const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
-      const url = new URL(input instanceof Request ? input.url : String(input))
-      if (url.pathname === '/api/dashboard/plugins') {
-        return jsonResponse([{ name: 'yaoyao', version: pluginVersion }])
-      }
-      if (url.pathname === '/api/plugins/yaoyao/maintenance/storage') {
-        return jsonResponse({ ready: true })
-      }
-      if (url.pathname === '/api/dashboard/agent-plugins/install') {
-        const rawBody = typeof init?.body === 'string' ? init.body : '{}'
-        records.push({
-          path: url.pathname,
-          method: init?.method ?? 'GET',
-          search: url.searchParams,
-          headers: new Headers(init?.headers),
-          body: JSON.parse(rawBody),
-        })
-        pluginVersion = '1.7.3'
-        return jsonResponse({ ok: true, plugin_name: 'yaoyao', enabled: true })
-      }
-      return baseGateway(input, init)
-    }) as typeof fetch
-    const runtime = createApplication({ config: makeConfig(), fetchImpl })
-    runtimes.push(runtime)
-    const bootstrap = await request(runtime.app.callback())
-      .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
-
-    const response = await request(runtime.app.callback())
-      .post('/api/app/plugins/yaoyao/reconcile')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({})
-      .expect(200)
-
-    expect(response.body).toMatchObject({
-      updated: true,
-      installedPluginVersion: '1.7.3',
-      expectedPluginVersion: '1.7.3',
-      restarted: false,
-      restartRequired: false,
-    })
-    expect(records.find(entry => entry.path === '/api/dashboard/agent-plugins/install')?.body)
-      .toMatchObject({ force: true, enable: true })
-  })
-
-  it('refuses to replace an existing Yaoyao before durable storage is ready', async () => {
-    const records: RecordedRequest[] = []
-    const baseGateway = fakeGateway(records)
-    const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
-      const url = new URL(input instanceof Request ? input.url : String(input))
-      if (url.pathname === '/api/dashboard/plugins') {
-        return jsonResponse([{ name: 'yaoyao', version: '1.7.1' }])
-      }
-      if (url.pathname === '/api/plugins/yaoyao/maintenance/storage') {
-        return jsonResponse({ detail: 'Not Found' }, { status: 404 })
-      }
-      return baseGateway(input, init)
-    }) as typeof fetch
-    const runtime = createApplication({ config: makeConfig(), fetchImpl })
-    runtimes.push(runtime)
-    const bootstrap = await request(runtime.app.callback())
-      .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
-
-    const response = await request(runtime.app.callback())
-      .post('/api/app/plugins/yaoyao/install')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ force: true })
-      .expect(409)
-
-    expect(response.body.code).toBe('yaoyao_storage_migration_required')
-    expect(records.some((entry) => entry.path === '/api/dashboard/agent-plugins/install')).toBe(false)
-  })
-
-  it('upgrades an existing Yaoyao only after storage readiness and explicit force', async () => {
-    const records: RecordedRequest[] = []
-    const baseGateway = fakeGateway(records)
-    const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
-      const url = new URL(input instanceof Request ? input.url : String(input))
-      if (url.pathname === '/api/dashboard/plugins') {
-        return jsonResponse([{ name: 'yaoyao', version: '1.7.1' }])
-      }
-      if (url.pathname === '/api/plugins/yaoyao/maintenance/storage') {
-        return jsonResponse({ ready: true, profiles: [{ profile: 'default', ready: true }] })
-      }
-      if (url.pathname === '/api/dashboard/agent-plugins/install') {
-        const rawBody = typeof init?.body === 'string' ? init.body : '{}'
-        records.push({
-          path: url.pathname,
-          method: init?.method ?? 'GET',
-          search: url.searchParams,
-          headers: new Headers(init?.headers),
-          body: JSON.parse(rawBody),
-        })
-        return jsonResponse({ ok: true, plugin_name: 'yaoyao', enabled: true })
-      }
-      return baseGateway(input, init)
-    }) as typeof fetch
-    const runtime = createApplication({ config: makeConfig(), fetchImpl })
-    runtimes.push(runtime)
-    const bootstrap = await request(runtime.app.callback())
-      .get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
-    const common = request(runtime.app.callback())
-      .post('/api/app/plugins/yaoyao/install')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-
-    await common.send({ force: false }).expect(409)
-    await request(runtime.app.callback())
-      .post('/api/app/plugins/yaoyao/install')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ force: true })
-      .expect(200)
-
-    const install = records.find((entry) => entry.path === '/api/dashboard/agent-plugins/install')
-    expect(install?.body).toMatchObject({ force: true, enable: true })
-  })
   it('serves authenticated historical media only from the configured root', async () => {
     const config = makeConfig()
     writeFileSync(join(config.mediaRoot, '报告.txt'), '历史文件内容')
@@ -358,7 +177,6 @@ describe('8800 BFF', () => {
     expect(records.map((entry) => entry.path)).toEqual([
       '/api/status', '/api/auth/me', '/api/status',
       '/api/profiles',
-      '/api/plugins/yaoyao/profiles',
     ])
     expect(response.body).toMatchObject({
       authRequired: true,
@@ -386,7 +204,7 @@ describe('8800 BFF', () => {
       .set('Host', '127.0.0.1:8800')
       .expect(200)
     expect(records.map(entry => entry.path)).toEqual([
-      '/api/status', '/api/auth/me', '/api/profiles', '/api/plugins/yaoyao/profiles',
+      '/api/status', '/api/auth/me', '/api/profiles',
     ])
     expect(response.body.profiles).toEqual([
       { name: 'default', is_default: true, agentName: '竹儿', display_name: '竹儿', description: '竹儿' },
@@ -493,7 +311,7 @@ describe('8800 BFF', () => {
       .set('Host', '127.0.0.1:8800')
       .expect(200)
     expect(records.at(-1)?.path).toBe('/api/profiles/sessions')
-    expect(records.at(-1)?.search.get('exclude_sources')).toBe('cron,ios_group')
+    expect(records.at(-1)?.search.get('exclude_sources')).toBe('cron,ios_group,yaoyao_workspace')
 
     await request(runtime.app.callback())
       .get('/api/app/sessions/session-1/messages?offset=3&limit=50&order=oldest&include_compacted=false&profile=default')
@@ -507,98 +325,6 @@ describe('8800 BFF', () => {
     expect(history.search.get('profile')).toBe('default')
   })
 
-  it('proxies topic pagination and forwards topic-scoped message queries', async () => {
-    const records: RecordedRequest[] = []
-    const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
-    runtimes.push(runtime)
-    const roomID = '11111111-1111-4111-8111-111111111111'
-    const topicID = '22222222-2222-4222-8222-222222222222'
-
-    await request(runtime.app.callback())
-      .get('/api/app/groups/topics?limit=40&cursor=next-global-topic&archived=true&ignored=drop-me')
-      .set('Host', '127.0.0.1:8800')
-      .expect(200)
-    const globalTopics = records.at(-1)!
-    expect(globalTopics.path).toBe('/api/plugins/yaoyao/v1/topics')
-    expect(globalTopics.search.get('limit')).toBe('40')
-    expect(globalTopics.search.get('cursor')).toBe('next-global-topic')
-    expect(globalTopics.search.has('archived')).toBe(false)
-    expect(globalTopics.search.has('ignored')).toBe(false)
-
-    await request(runtime.app.callback())
-      .get(`/api/app/groups/rooms/${roomID}/topics?limit=25&cursor=next-topic&archived=true&ignored=drop-me`)
-      .set('Host', '127.0.0.1:8800')
-      .expect(200)
-    const topics = records.at(-1)!
-    expect(topics.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics`)
-    expect(topics.search.get('limit')).toBe('25')
-    expect(topics.search.get('cursor')).toBe('next-topic')
-    expect(topics.search.get('archived')).toBe('true')
-    expect(topics.search.has('ignored')).toBe(false)
-
-    const bootstrap = await request(runtime.app.callback())
-      .get('/api/app/bootstrap')
-      .set('Host', '127.0.0.1:8800')
-      .expect(200)
-    await request(runtime.app.callback())
-      .patch(`/api/app/groups/rooms/${roomID}/topics/${topicID}`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ requestId: '33333333-3333-4333-8333-333333333333', title: '新标题' })
-      .expect(200)
-    const renamed = records.at(-1)!
-    expect(renamed.method).toBe('PATCH')
-    expect(renamed.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}`)
-    expect(renamed.body).toEqual({ requestId: '33333333-3333-4333-8333-333333333333', title: '新标题' })
-
-    await request(runtime.app.callback())
-      .delete(`/api/app/groups/rooms/${roomID}/topics/${topicID}`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ requestId: '55555555-5555-4555-8555-555555555555' })
-      .expect(200)
-    expect(records.at(-1)?.method).toBe('DELETE')
-    expect(records.at(-1)?.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}`)
-
-    await request(runtime.app.callback())
-      .post(`/api/app/groups/rooms/${roomID}/topics/${topicID}/restore`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ requestId: '66666666-6666-4666-8666-666666666666' })
-      .expect(200)
-    expect(records.at(-1)?.method).toBe('POST')
-    expect(records.at(-1)?.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}/restore`)
-
-    await request(runtime.app.callback())
-      .patch(`/api/app/groups/rooms/${roomID}/topics/${topicID}/read`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookieHeader(bootstrap))
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ requestId: '44444444-4444-4444-8444-444444444444', throughSeq: 42 })
-      .expect(200)
-    const markedRead = records.at(-1)!
-    expect(markedRead.method).toBe('PATCH')
-    expect(markedRead.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/topics/${topicID}/read`)
-    expect(markedRead.body).toEqual({ requestId: '44444444-4444-4444-8444-444444444444', throughSeq: 42 })
-
-    await request(runtime.app.callback())
-      .get(`/api/app/groups/rooms/${roomID}/messages?topicId=${topicID}&beforeSeq=40&limit=20`)
-      .set('Host', '127.0.0.1:8800')
-      .expect(200)
-    const messages = records.at(-1)!
-    expect(messages.path).toBe(`/api/plugins/yaoyao/v1/rooms/${roomID}/messages`)
-    expect(messages.search.get('topicId')).toBe(topicID)
-    expect(messages.search.get('beforeSeq')).toBe('40')
-    expect(messages.search.get('limit')).toBe('20')
-  })
-
   it('keeps unknown API routes out of the SPA fallback', async () => {
     const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway([]) })
     runtimes.push(runtime)
@@ -659,6 +385,9 @@ describe('8800 BFF', () => {
     }) as typeof fetch
     const runtime = createApplication({ config: makeConfig(), fetchImpl })
     runtimes.push(runtime)
+    const file = join(runtime.config.home, 'unsafe.html')
+    writeFileSync(file, '<script>window.pwned=true</script>')
+    runtime.workspace.put('test-admin','file','1',{id:'1',name:'unsafe.html',path:file,mimeType:'text/html',size:37,sender:'agent',createdAt:Date.now()})
     const response = await request(runtime.app.callback())
       .get('/api/app/files/1/preview')
       .set('Host', '127.0.0.1:8800')
@@ -666,44 +395,4 @@ describe('8800 BFF', () => {
     expect(response.headers['content-type']).toMatch(/^application\/octet-stream/)
     expect(response.headers['content-disposition']).toContain('attachment')
   })
-
-  it('stores group files opaquely and injects the local path only upstream', async () => {
-    const records: RecordedRequest[] = []
-    const runtime = createApplication({ config: makeConfig(), fetchImpl: fakeGateway(records) })
-    runtimes.push(runtime)
-    const bootstrap = await request(runtime.app.callback())
-      .get('/api/app/bootstrap')
-      .set('Host', '127.0.0.1:8800')
-      .expect(200)
-    const cookies = cookieHeader(bootstrap)
-    const upload = await request(runtime.app.callback())
-      .post('/api/app/group-uploads')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookies)
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .attach('files', Buffer.from('hello'), { filename: 'hello.txt', contentType: 'text/plain' })
-      .expect(201)
-    expect(upload.body.files[0]).toMatchObject({ name: 'hello.txt', size: 5 })
-    expect(upload.body.files[0].path).toBeUndefined()
-
-    await request(runtime.app.callback())
-      .post('/api/app/groups/rooms/11111111-1111-4111-8111-111111111111/messages')
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('Cookie', cookies)
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({
-        requestId: '22222222-2222-4222-8222-222222222222',
-        clientMessageId: '33333333-3333-4333-8333-333333333333',
-        content: '请看文件',
-        mentionAgentIds: [],
-        uploadIds: [upload.body.files[0].id],
-      })
-      .expect(200)
-    const sent = records.at(-1)?.body as { content: string; uploadIds?: unknown }
-    expect(sent.uploadIds).toBeUndefined()
-    expect(sent.content).toContain('请看文件')
-    expect(sent.content).toContain(runtime.uploads.uploadRoot)
-  })
 })

+ 2 - 63
tests/server/localAuthRoutes.test.ts

@@ -34,7 +34,7 @@ describe('8800 local authentication routes', () => {
       if (path === '/api/status') return Response.json({ auth_required: false })
       if (path === '/') return new Response(`<script>window.__HERMES_SESSION_TOKEN__="${token}";</script>`)
       if (new Headers(init?.headers).get('x-hermes-session-token') !== token) return Response.json({}, { status: 401 })
-      return Response.json({ profiles: [{ name: 'default', is_default: true }] })
+      return Response.json({ profiles: [{ name: 'default', is_default: true, display_name: '丫头' }] })
     }) as typeof fetch }); runtimes.push(runtime)
     expect(runtime.auth.upstreamCredentials()).toBeUndefined()
     const agent = request.agent(runtime.app.callback()), origin = 'http://127.0.0.1:8800'
@@ -75,7 +75,7 @@ describe('8800 local authentication routes', () => {
       if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), {
         headers: { 'content-type': 'application/json', 'set-cookie': 'hermes_service=session; Path=/; HttpOnly' },
       })
-      if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true }] })
+      if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true, display_name: '丫头' }] })
       if (path === '/api/auth/ws-ticket') {
         wsTicketForwardedFor = headers.get('x-forwarded-for')
         return Response.json({ ticket: 'upstream-ticket' })
@@ -150,65 +150,4 @@ describe('8800 local authentication routes', () => {
     await native.post('/api/auth/ws-ticket').set('Host', '127.0.0.1:8800').send({}).expect(410)
     expect(wsTicketForwardedFor).toBeUndefined()
   })
-
-  it('lets one 8800 claim another 8800 as a direct child node', async () => {
-    const registrations: unknown[] = []
-    const make = (label: string) => {
-      const home = mkdtempSync(join(tmpdir(), `yaoyao-${label}-`)); roots.push(home)
-      const config: ServerConfig = {
-        host: '127.0.0.1', port: 0, upstream: new URL('http://127.0.0.1:9119'),
-        allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
-        mediaOwner: 'tester', allowInsecureLan: true, insecureLan: true, production: false,
-        superviseDashboard: true,
-        upstreamUsername: 'service', upstreamPassword: 'fixture-password',
-      }
-      const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
-        const path = new URL(input instanceof Request ? input.url : String(input)).pathname
-        const headers = new Headers(init?.headers)
-        if (path === '/api/status') return Response.json({ auth_required: true })
-        if (path === '/api/auth/me') return headers.get('cookie') ? Response.json({ user_id: 'service' }) : Response.json({}, { status: 401 })
-        if (path === '/api/auth/providers') return Response.json({ providers: [{ name: 'basic', supports_password: true }] })
-        if (path === '/auth/password-login') return new Response(JSON.stringify({ ok: true }), { headers: { 'content-type': 'application/json', 'set-cookie': `service_${label}=session; Path=/; HttpOnly` } })
-        if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true, model: 'test' }] })
-        if (path === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [] })
-        if (path === '/api/plugins/yaoyao/v1/nodes' && init?.method === 'POST') {
-          registrations.push(JSON.parse(String(init.body))); return Response.json({ nodeId: JSON.parse(String(init.body)).nodeId })
-        }
-        return Response.json({ ok: true })
-      }) as typeof fetch
-      const app = createApplication({ config, fetchImpl })
-      const node = createNodeServer(app); nodeRuntimes.push(node)
-      return { app, node, config }
-    }
-    const child = make('child')
-    const parent = make('parent')
-    await Promise.all([child, parent].map(({ node, config }) => new Promise<void>(resolve => {
-      node.server.listen(0, '127.0.0.1', () => {
-        config.port = (node.server.address() as { port: number }).port
-        resolve()
-      })
-    })))
-    const authenticate = async (runtime: ApplicationRuntime, port: number) => {
-      const agent = request.agent(runtime.app.callback())
-      const initial = await agent.get('/api/app/bootstrap').set('Host', `127.0.0.1:${port}`)
-      const login = await agent.post('/api/app/login').set('Host', `127.0.0.1:${port}`)
-        .set('Origin', `http://127.0.0.1:${port}`).set('X-CSRF-Token', initial.body.csrfToken)
-        .send({ username: 'admin', password: 'admin' })
-      const changed = await agent.put('/api/app/account/credentials').set('Host', `127.0.0.1:${port}`)
-        .set('Origin', `http://127.0.0.1:${port}`).set('X-CSRF-Token', login.body.csrfToken)
-        .send({ currentPassword: 'admin', newPassword: 'new-password', username: 'admin' })
-      const ready = await agent.get('/api/app/bootstrap').set('Host', `127.0.0.1:${port}`)
-      return { agent, csrf: ready.body.csrfToken, origin: `http://127.0.0.1:${port}`, changed }
-    }
-    const childAuth = await authenticate(child.app, child.config.port)
-    const parentAuth = await authenticate(parent.app, parent.config.port)
-    const pairing = await childAuth.agent.post('/api/app/pairings').set('Host', `127.0.0.1:${child.config.port}`)
-      .set('Origin', childAuth.origin).set('X-CSRF-Token', childAuth.csrf)
-      .send({ scopes: ['agents.read', 'history.read', 'sessions.execute', 'groups.read', 'groups.execute'] }).expect(201)
-    await parentAuth.agent.post('/api/app/groups/nodes/pair').set('Host', `127.0.0.1:${parent.config.port}`)
-      .set('Origin', parentAuth.origin).set('X-CSRF-Token', parentAuth.csrf)
-      .send({ qrPayload: pairing.body.qrPayload, name: '子 8800' }).expect(201)
-    expect(registrations).toHaveLength(1)
-    expect(registrations[0]).toMatchObject({ name: '子 8800', profiles: [{ name: 'default' }] })
-  })
 })

+ 1 - 1
tests/server/offlineSystemUpdate.test.ts

@@ -13,7 +13,7 @@ const roots: string[] = []
 const host = '127.0.0.1:8800'
 const origin = `http://${host}`
 const base = '/api/app/system/update'
-const latest = { schemaVersion: 1 as const, releaseVersion: '0.3.0', webVersion: '0.3.0', pluginVersion: '9.0.0', gitTag: 'v0.3.0' }
+const latest = { schemaVersion: 1 as const, releaseVersion: '0.3.0', webVersion: '0.3.0', gitTag: 'v0.3.0' }
 
 afterEach(() => {
   for (const runtime of runtimes.splice(0)) runtime.close()

+ 2 - 7
tests/server/pairing.test.ts

@@ -205,13 +205,8 @@ describe('Hermes node pairing', () => {
       .set('X-File-Name-B64', Buffer.from('note.txt').toString('base64url'))
       .set('X-Mime-Type', 'text/plain')
       .send(attachment)
-      .expect(200)
-    expect(upstreamRequests.at(-1)).toMatchObject({
-      path: '/api/plugins/yaoyao/v1/node-worker/sessions/runtime-1/attachments',
-      contentType: 'application/octet-stream',
-      nodeClient: claim.body.deviceId,
-      body: attachment,
-    })
+      .expect(410)
+    expect(upstreamRequests.some(r => r.path.includes('/node-worker/'))).toBe(false)
 
     await request(runtime.app.callback())
       .delete(`/api/app/paired-devices/${claim.body.deviceId}`)

+ 61 - 158
tests/server/pushEventAdapter.test.ts

@@ -2,175 +2,78 @@ import { mkdtempSync, rmSync } from 'node:fs'
 import { tmpdir } from 'node:os'
 import { join } from 'node:path'
 import { afterEach, describe, expect, it } from 'vitest'
-import type { APNsRequest } from '../../src/server/apns.js'
-import type { APNsProviderConfig } from '../../src/server/config.js'
-import type { UpstreamServiceSession } from '../../src/server/localAuth.js'
 import { PushCoordinator } from '../../src/server/pushCoordinator.js'
 import { PushCoordinatorEventAdapter } from '../../src/server/pushEventAdapter.js'
-
+import type { APNsRequest } from '../../src/server/apns.js'
 const roots: string[] = []
 afterEach(() => {
-  for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+  for (const home of roots.splice(0)) rmSync(home, { recursive: true, force: true })
 })
-
-describe('push event reset reconciliation', () => {
-  it('recovers only post-subscription terminal messages and pending interactions before advancing cursor', async () => {
-    const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-reconcile-'))
-    roots.push(home)
-    let now = 1_000_000
-    const requests: APNsRequest[] = []
-    const apns: APNsProviderConfig = {
-      keyFile: join(home, 'unused.p8'), keyId: 'KEY123', teamId: 'TEAM123', topic: 'cn.samien.yaoyao.hermes',
-    }
-    const push = new PushCoordinator({
-      home, apns, autoFlush: false, now: () => now,
-      provider: { send: async request => { requests.push(request); return { disposition: 'success', status: 200 } } },
-    })
-    push.registerInstallation({
-      userId: 'user-a', installationId: 'phone-a', clientAccountId: 'account-a',
-      deviceToken: 'ab'.repeat(32), environment: 'development',
-    })
-    push.setGroupSubscription('user-a', 'room-1', true, 1)
-    now += 10_000
-
-    const upstreamSession = {
-      request: async (path: string) => {
-        if (path.endsWith('/messages')) {
-          return {
-            status: 200,
-            body: Buffer.from(JSON.stringify({ items: [
-              { id: 'old-message', seq: 1, senderKind: 'agent', senderName: '旧 Agent', status: 'completed', content: '旧消息', updatedAt: 900 },
-              { id: 'new-message', seq: 2, topicId: 'topic-1', senderKind: 'agent', senderName: '新 Agent', status: 'completed', content: '断线期间回复', updatedAt: 1_005 },
-            ] })),
-          }
-        }
-        return {
-          status: 200,
-          body: Buffer.from(JSON.stringify({
-            room: {
-              id: 'room-1', name: '项目团队',
-              pendingInteractions: [{
-                id: 'interaction-1', kind: 'clarification', status: 'pending', topicId: 'topic-1',
-                updatedAt: 1_006, payload: { question: '请选择方案' },
-              }],
-            },
-          })),
-        }
+function fixture() {
+  const home = mkdtempSync(join(tmpdir(), 'yaoyao-web-push-'))
+  roots.push(home)
+  const requests: APNsRequest[] = []
+  const push = new PushCoordinator({
+    home,
+    autoFlush: false,
+    apns: {
+      keyFile: join(home, 'unused.p8'),
+      keyId: 'KEY123',
+      teamId: 'TEAM123',
+      topic: 'cn.samien.yaoyao.hermes',
+    },
+    provider: {
+      send: async (request) => {
+        requests.push(request)
+        return { disposition: 'success', status: 200 }
       },
-    } as unknown as UpstreamServiceSession
-    const adapter = new PushCoordinatorEventAdapter(push, upstreamSession)
-
-    await expect(adapter.resetGroupCursor({
-      epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 42, reason: 'cursor_expired',
-    })).resolves.toEqual({ epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 42 })
-    expect(push.status().pendingCount).toBe(2)
-    await expect(push.flushDue()).resolves.toMatchObject({ delivered: 2 })
-    expect(requests).toHaveLength(2)
-    expect(requests.map(request => request.payload)).toEqual(expect.arrayContaining([
-      expect.objectContaining({ eventId: 'group-message:new-message:completed', roomId: 'room-1', messageId: 'new-message' }),
-      expect.objectContaining({ eventId: 'group-interaction:interaction-1', roomId: 'room-1', interactionId: 'interaction-1' }),
-    ]))
-    expect(JSON.stringify(requests)).not.toContain('old-message')
-
-    await adapter.resetGroupCursor({
-      epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 43, reason: 'cursor_expired',
-    })
-    expect(push.status().pendingCount).toBe(0)
-    push.close()
+    },
   })
-
-  it('ignores a lagged live event older than the current subscription', () => {
-    const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-lagged-'))
-    roots.push(home)
-    let now = 2_000_000
-    const apns: APNsProviderConfig = {
-      keyFile: join(home, 'unused.p8'), keyId: 'KEY123', teamId: 'TEAM123', topic: 'cn.samien.yaoyao.hermes',
-    }
-    const push = new PushCoordinator({
-      home, apns, autoFlush: false, now: () => now,
-      provider: { send: async () => ({ disposition: 'success', status: 200 }) },
-    })
-    push.registerInstallation({
-      userId: 'user-a', installationId: 'phone-a', clientAccountId: 'account-a',
-      deviceToken: 'ab'.repeat(32), environment: 'development',
-    })
-    push.setGroupSubscription('user-a', 'room-1', true)
-    const adapter = new PushCoordinatorEventAdapter(push, {} as UpstreamServiceSession)
-
-    expect(adapter.enqueueNotification({
-      eventID: 'group-message:old:completed', localUserID: 'user-a', kind: 'group.message.completed',
-      title: '旧消息', body: '旧消息', collapseID: 'old', data: {}, roomID: 'room-1',
-      epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 1, occurredAt: now - 10_000,
-    })).toBe('ignored')
-    expect(push.status().pendingCount).toBe(0)
-    now += 10_000
-    expect(adapter.enqueueNotification({
-      eventID: 'group-message:new:completed', localUserID: 'user-a', kind: 'group.message.completed',
-      title: '新消息', body: '新消息', collapseID: 'new', data: {}, roomID: 'room-1',
-      epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 2, occurredAt: now,
-    })).toBe('enqueued')
-    push.close()
+  push.registerInstallation({
+    userId: 'owner',
+    installationId: 'phone',
+    clientAccountId: 'account',
+    deviceToken: 'ab'.repeat(32),
+    environment: 'development',
   })
-
-  it('drops a deleted room subscription instead of wedging the global reset', async () => {
-    const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-deleted-room-'))
-    roots.push(home)
-    const apns: APNsProviderConfig = {
-      keyFile: join(home, 'unused.p8'), keyId: 'KEY123', teamId: 'TEAM123', topic: 'cn.samien.yaoyao.hermes',
+  return { push, requests, adapter: new PushCoordinatorEventAdapter(push) }
+}
+describe('Web-owned push delivery', () => {
+  it('deduplicates workspace completion notifications and retains application navigation', async () => {
+    const { push, requests, adapter } = fixture()
+    push.setGroupSubscription('owner', 'room', true, 0)
+    const candidate = {
+      kind: 'group.message.completed' as const,
+      eventID: 'workspace:run',
+      localUserID: 'owner',
+      roomID: 'room',
+      title: '团队',
+      body: '已完成',
+      collapseID: 'workspace:room',
+      data: { workspace: '1', conversationId: 'room' },
     }
-    const push = new PushCoordinator({
-      home, apns, autoFlush: false,
-      provider: { send: async () => ({ disposition: 'success', status: 200 }) },
-    })
-    push.setGroupSubscription('user-a', 'deleted-room', true, 9)
-    const upstream = {
-      request: async () => ({ status: 404, body: Buffer.from('{}') }),
-    } as unknown as UpstreamServiceSession
-    const adapter = new PushCoordinatorEventAdapter(push, upstream)
-
-    await expect(adapter.resetGroupCursor({
-      epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 10, reason: 'epoch_mismatch',
-    })).resolves.toMatchObject({ cursor: 10 })
-    expect(push.listGroupSubscriptions('user-a')).toEqual([])
+    expect(adapter.enqueueNotification(candidate)).toBe('enqueued')
+    expect(adapter.enqueueNotification(candidate)).toBe('duplicate')
+    await push.flushDue()
+    expect(requests).toHaveLength(1)
+    expect(requests[0]!.payload).toMatchObject({ workspace: '1', conversationId: 'room' })
     push.close()
   })
-
-  it('walks backward from the latest page when a room baseline is zero', async () => {
-    const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-zero-baseline-'))
-    roots.push(home)
-    const apns: APNsProviderConfig = {
-      keyFile: join(home, 'unused.p8'), keyId: 'KEY123', teamId: 'TEAM123', topic: 'cn.samien.yaoyao.hermes',
-    }
-    const push = new PushCoordinator({
-      home, apns, autoFlush: false,
-      provider: { send: async () => ({ disposition: 'success', status: 200 }) },
-    })
-    push.setGroupSubscription('user-a', 'room-zero', true, 0)
-    const searches: string[] = []
-    const message = (seq: number) => ({
-      id: `message-${seq}`, seq, senderKind: 'agent', senderName: 'Agent', status: 'completed', content: `消息 ${seq}`,
-    })
-    const upstream = {
-      request: async (path: string, options?: { search?: URLSearchParams }) => {
-        if (!path.endsWith('/messages')) {
-          return { status: 200, body: Buffer.from('{"room":{"id":"room-zero","name":"零基线团队"}}') }
-        }
-        const search = options?.search?.toString() ?? ''
-        searches.push(search)
-        const before = Number(options?.search?.get('beforeSeq') ?? 0)
-        const items = before === 51
-          ? Array.from({ length: 50 }, (_, index) => message(index + 1))
-          : Array.from({ length: 100 }, (_, index) => message(index + 51))
-        return { status: 200, body: Buffer.from(JSON.stringify({ items })) }
-      },
-    } as unknown as UpstreamServiceSession
-    const adapter = new PushCoordinatorEventAdapter(push, upstream)
-
-    await adapter.resetGroupCursor({
-      epoch: '123e4567-e89b-42d3-a456-426614174000', cursor: 150, reason: 'cursor_expired',
-    })
-    expect(searches).toEqual(['limit=100', 'limit=100&beforeSeq=51'])
-    expect(push.listGroupSubscriptions('user-a')[0]?.lastMessageSeq).toBe(150)
+  it('does not deliver group events to an unsubscribed account', () => {
+    const { push, adapter } = fixture()
+    expect(
+      adapter.enqueueNotification({
+        kind: 'group.message.completed',
+        eventID: 'workspace:run',
+        localUserID: 'owner',
+        roomID: 'other-room',
+        title: '团队',
+        body: '结果',
+        collapseID: 'workspace:other',
+        data: { conversationId: 'other-room' },
+      }),
+    ).toBe('ignored')
+    expect(push.status().pendingCount).toBe(0)
     push.close()
   })
 })

+ 0 - 53
tests/server/pushEvents.test.ts

@@ -8,7 +8,6 @@ import { UpstreamServiceSession } from '../../src/server/localAuth.js'
 import {
   ChatPushJobManager,
   ChatPushRelayObserver,
-  GroupPushEventProcessor,
   HermesChatNotificationResolver,
   HermesChatPushJobWatcher,
   type ChatPushJob,
@@ -229,58 +228,6 @@ describe('push event bridge', () => {
     expect(coordinator.notifications).toHaveLength(0)
   })
 
-  it('filters group events by terminal agent state, subscription, and stable event id', async () => {
-    const coordinator = new FakeCoordinator()
-    coordinator.anchor = { epoch, cursor: 5 }
-    coordinator.subscribers.set('room-1', ['user-a', 'user-a', 'user-b'])
-    const processor = new GroupPushEventProcessor({ epoch, cursor: 5 }, coordinator)
-
-    await expect(processor.accept({ type: 'group.ready', epoch, cursor: 5 })).resolves.toBe('ready')
-    await processor.accept({
-      type: 'group.event', epoch, cursor: 6, roomId: 'room-1', event: 'message.upsert',
-      payload: { id: 'message-1', roomId: 'room-1', senderKind: 'agent', status: 'streaming', content: '半成品' },
-    })
-    expect(coordinator.notifications).toHaveLength(0)
-    await processor.accept({
-      type: 'group.event', epoch, cursor: 7, roomId: 'room-1', event: 'message.upsert',
-      payload: {
-        id: 'message-1', roomId: 'room-1', topicId: 'topic-1', senderKind: 'agent', senderName: '夭夭',
-        status: 'completed', content: '团队最终回复',
-      },
-    })
-    expect(coordinator.notifications).toHaveLength(2)
-    expect(coordinator.notifications.every(item => item.kind === 'group.message.completed')).toBe(true)
-    expect((coordinator.notifications[0] as GroupPushCandidate).roomID).toBe('room-1')
-
-    await processor.accept({
-      type: 'group.event', epoch, cursor: 8, roomId: 'room-1', event: 'message.upsert',
-      payload: { id: 'message-1', roomId: 'room-1', senderKind: 'agent', status: 'completed', content: '重复终态' },
-    })
-    expect(coordinator.notifications).toHaveLength(2)
-    await processor.accept({
-      type: 'group.event', epoch, cursor: 9, roomId: 'room-1', event: 'interaction.requested',
-      payload: {
-        id: 'interaction-1', roomId: 'room-1', kind: 'clarification', status: 'pending',
-        payload: { question: '选择哪个?' },
-      },
-    })
-    expect(coordinator.notifications.filter(item => item.kind === 'group.interaction.requested')).toHaveLength(2)
-    expect(coordinator.anchor).toEqual({ epoch, cursor: 9 })
-  })
-
-  it('does not advance the group cursor when durable enqueue fails', async () => {
-    const coordinator = new FakeCoordinator()
-    coordinator.anchor = { epoch, cursor: 1 }
-    coordinator.subscribers.set('room-1', ['user-a'])
-    coordinator.failEnqueue = true
-    const processor = new GroupPushEventProcessor({ epoch, cursor: 1 }, coordinator)
-    await expect(processor.accept({
-      type: 'group.event', epoch, cursor: 2, roomId: 'room-1', event: 'message.upsert',
-      payload: { id: 'message-1', roomId: 'room-1', senderKind: 'agent', status: 'failed', error: '失败' },
-    })).rejects.toThrow('outbox unavailable')
-    expect(coordinator.anchor).toEqual({ epoch, cursor: 1 })
-  })
-
   it('resolves the authoritative latest assistant body from Hermes REST', async () => {
     let requested = ''
     const upstreamSession = {

+ 3 - 83
tests/server/pushRoutes.test.ts

@@ -247,7 +247,9 @@ describe('iOS push routes', () => {
       .set('Origin', 'http://127.0.0.1:8800')
     const installationID = '11111111-1111-4111-8111-111111111111'
     const accountID = '22222222-2222-4222-8222-222222222222'
-    const roomID = '33333333-3333-4333-8333-333333333333'
+    const a = runtime.workspace.createAgent('test-admin', {name:'甲',profile:'default'})
+    const b = runtime.workspace.createAgent('test-admin', {name:'乙',profile:'default'})
+    const roomID = runtime.workspace.createGroup('test-admin', {name:'通知测试',memberIds:[a.id,b.id],administratorId:a.id}).id
     const bootstrap = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
 
     const capabilities = await host(agent.get('/api/push/v1/capabilities')).expect(200)
@@ -308,86 +310,4 @@ describe('iOS push routes', () => {
       .send({ enabled: 'yes' })
       .expect(400, /enabled must be a boolean/)
   })
-
-  it('automatically subscribes the current user after Web or native team participation', async () => {
-    const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-auto-subscribe-'))
-    roots.push(home)
-    const config: ServerConfig = {
-      host: '127.0.0.1', port: 8800, upstream: new URL('http://127.0.0.1:9119'),
-      allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
-      mediaOwner: 'tester', allowInsecureLan: false, insecureLan: false, production: false,
-    }
-    const fetchImpl = (async (input: string | URL | Request) => {
-      const url = new URL(input instanceof Request ? input.url : String(input))
-      if (url.pathname === '/api/status') return Response.json({ auth_required: false })
-      if (url.pathname === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true }] })
-      if (url.pathname === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [] })
-      if (/\/api\/plugins\/yaoyao\/v1\/rooms\/[0-9a-f-]{36}\/messages$/.test(url.pathname)) {
-        return Response.json({ message: { id: 'message', seq: 7, senderKind: 'human', content: 'hello' }, runs: [] })
-      }
-      return Response.json({ ok: true })
-    }) as typeof fetch
-    const runtime = createAuthenticatedApplication({ config, fetchImpl })
-    runtimes.push(runtime)
-    const agent = request.agent(runtime.app.callback())
-    const firstRoom = '44444444-4444-4444-8444-444444444444'
-    const secondRoom = '55555555-5555-4555-8555-555555555555'
-    const bootstrap = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
-
-    await agent.post(`/api/app/groups/rooms/${firstRoom}/messages`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ requestId: 'request-web', clientMessageId: 'client-web', content: 'Web 参与', mentionAgentIds: [] })
-      .expect(200)
-    await agent.post(`/api/plugins/yaoyao/v1/rooms/${secondRoom}/messages`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .send({ requestId: 'request-ios', clientMessageId: 'client-ios', content: 'iOS 参与', mentionAgentIds: [] })
-      .expect(200)
-
-    const subscriptions = await agent.get('/api/push/v1/group-subscriptions')
-      .set('Host', '127.0.0.1:8800')
-      .expect(200)
-    expect(subscriptions.body.roomIds).toEqual([firstRoom, secondRoom])
-    expect(subscriptions.body.subscriptions.every((item: { lastMessageSeq?: number }) => item.lastMessageSeq === 7)).toBe(true)
-  })
-
-  it('never turns a successful team send into a failure when optional push state is unavailable', async () => {
-    const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-state-failure-'))
-    roots.push(home)
-    mkdirSync(join(home, 'push'))
-    writeFileSync(join(home, 'push', 'state.json'), '{broken', { mode: 0o600 })
-    const config: ServerConfig = {
-      host: '127.0.0.1', port: 8800, upstream: new URL('http://127.0.0.1:9119'),
-      allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
-      mediaOwner: 'tester', allowInsecureLan: false, insecureLan: false, production: true,
-    }
-    const fetchImpl = (async (input: string | URL | Request) => {
-      const path = new URL(input instanceof Request ? input.url : String(input)).pathname
-      if (path === '/api/status') return Response.json({ auth_required: false })
-      if (path === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true }] })
-      if (path === '/api/plugins/yaoyao/profiles') return Response.json({ profiles: [] })
-      if (path.endsWith('/messages')) {
-        return Response.json({ message: { id: 'accepted', seq: 1, senderKind: 'human', content: '已接收' }, runs: [] })
-      }
-      return Response.json({ ok: true })
-    }) as typeof fetch
-    const push = new PushCoordinator({ home, autoFlush: false })
-    const runtime = createAuthenticatedApplication({ config, fetchImpl, push })
-    runtimes.push(runtime)
-    // The error event is operational telemetry; suppress Koa's default stderr
-    // output while asserting the primary response remains authoritative.
-    runtime.app.on('error', () => undefined)
-    const agent = request.agent(runtime.app.callback())
-    const roomID = '66666666-6666-4666-8666-666666666666'
-    const bootstrap = await agent.get('/api/app/bootstrap').set('Host', '127.0.0.1:8800').expect(200)
-
-    await agent.post(`/api/app/groups/rooms/${roomID}/messages`)
-      .set('Host', '127.0.0.1:8800')
-      .set('Origin', 'http://127.0.0.1:8800')
-      .set('X-CSRF-Token', bootstrap.body.csrfToken)
-      .send({ requestId: 'request', clientMessageId: 'client', content: '仍应成功', mentionAgentIds: [] })
-      .expect(200, /accepted/)
-  })
 })

+ 2 - 39
tests/server/pushRuntime.test.ts

@@ -5,12 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
 import { createNodeServer, type ApplicationRuntime } from '../../src/server/app.js'
 import type { ServerConfig } from '../../src/server/config.js'
 import { PushCoordinator } from '../../src/server/pushCoordinator.js'
-import {
-  GroupPushEventWatcher,
-  type GroupEventConnection,
-  type GroupEventSource,
-  type PushEventCoordinator,
-} from '../../src/server/pushEvents.js'
+
 import { createAuthenticatedApplication } from './authenticatedApplication.js'
 
 const roots: string[] = []
@@ -22,32 +17,6 @@ afterEach(() => {
 })
 
 describe('dynamic push runtime', () => {
-  it('closes a group connection that finishes opening after the watcher was stopped', async () => {
-    const epoch = '11111111-1111-4111-8111-111111111111'
-    let resolveConnection!: (connection: GroupEventConnection) => void
-    const connection = { close: vi.fn() }
-    const source: GroupEventSource = {
-      currentAnchor: async () => ({ epoch, cursor: 0 }),
-      connect: () => new Promise(resolve => { resolveConnection = resolve }),
-    }
-    const coordinator: PushEventCoordinator = {
-      saveChatJob: () => undefined,
-      completeChatJob: () => undefined,
-      pendingChatJobs: () => [],
-      enqueueNotification: () => 'ignored',
-      groupWatchAnchor: () => ({ epoch, cursor: 0 }),
-      groupSubscribers: () => [],
-      advanceGroupCursor: () => undefined,
-      resetGroupCursor: reset => ({ epoch: reset.epoch, cursor: reset.cursor }),
-    }
-    const watcher = new GroupPushEventWatcher(source, coordinator)
-    watcher.start()
-    await vi.waitFor(() => expect(resolveConnection).toBeTypeOf('function'))
-    watcher.stop()
-    resolveConnection(connection)
-    await vi.waitFor(() => expect(connection.close).toHaveBeenCalledTimes(1))
-  })
-
   it('starts and stops background observers when Web configuration changes', async () => {
     const home = mkdtempSync(join(tmpdir(), 'yaoyao-push-runtime-'))
     roots.push(home)
@@ -65,21 +34,17 @@ describe('dynamic push runtime', () => {
     const runtime = createAuthenticatedApplication({ config, push })
     const chatStart = vi.spyOn(runtime.chatPushJobs, 'start').mockImplementation(() => undefined)
     const chatStop = vi.spyOn(runtime.chatPushJobs, 'stop').mockImplementation(() => undefined)
-    const groupStart = vi.spyOn(runtime.groupPushEvents, 'start').mockImplementation(() => undefined)
-    const groupStop = vi.spyOn(runtime.groupPushEvents, 'stop').mockImplementation(() => undefined)
+    expect(runtime).not.toHaveProperty('groupPushEvents')
     const node = createNodeServer(runtime)
 
     expect(chatStop).toHaveBeenCalledTimes(1)
-    expect(groupStop).toHaveBeenCalledTimes(1)
     await push.configureAPNs({
       keyFile: '/private/unused.p8', keyId: 'KEY1234567', teamId: 'TEAM123456',
       topic: 'cn.samien.yaoyao.hermes', environments: ['development'],
     })
     expect(chatStart).toHaveBeenCalledTimes(1)
-    expect(groupStart).toHaveBeenCalledTimes(1)
     await push.configureAPNs()
     expect(chatStop).toHaveBeenCalledTimes(2)
-    expect(groupStop).toHaveBeenCalledTimes(2)
 
     await push.configureFCM({
       serviceAccountFile: '/private/unused.json',
@@ -87,10 +52,8 @@ describe('dynamic push runtime', () => {
       packageName: 'cn.samien.yaoyao.hermes',
     })
     expect(chatStart).toHaveBeenCalledTimes(2)
-    expect(groupStart).toHaveBeenCalledTimes(2)
     await push.configureFCM()
     expect(chatStop).toHaveBeenCalledTimes(3)
-    expect(groupStop).toHaveBeenCalledTimes(3)
 
     await node.close()
   })

+ 1 - 9
tests/server/security.test.ts

@@ -133,19 +133,11 @@ describe('server security boundary', () => {
     const value = loadServerConfig(isolatedEnv())
     expect(value.host).toBe('127.0.0.1')
     expect(value.insecureLan).toBe(false)
-    expect(value.yaoyaoPluginSource).toBe(
-      'https://git.samien.cn/samien/hermes-yaoyao.git#hermes-plugins/yaoyao',
-    )
+    expect(value).not.toHaveProperty('yaoyaoPluginSource')
     expect(value.releaseSource).toBe('https://git.samien.cn/samien/hermes-yaoyao.git')
     expect(value.allowRemoteUpdate).toBe(false)
   })
 
-  it('rejects credentials embedded in the configured Yaoyao plugin source', () => {
-    expect(() => loadServerConfig(isolatedEnv({
-      HERMES_YAOYAO_PLUGIN_SOURCE: 'https://user:secret@git.example/yaoyao.git#hermes-plugins/yaoyao',
-    }))).toThrow(/must not contain credentials/)
-  })
-
   it('requires a credential-free HTTPS or SSH system release source', () => {
     expect(() => loadServerConfig(isolatedEnv({
       HERMES_YAOYAO_RELEASE_SOURCE: 'http://git.example/hermes-yaoyao.git',

+ 2 - 2
tests/server/systemUpdateRoutes.test.ts

@@ -42,7 +42,7 @@ describe('system update routes', () => {
     const projectRoot = join(root, 'project')
     mkdirSync(projectRoot)
     writeFileSync(join(projectRoot, 'release.json'), JSON.stringify({
-      schemaVersion: 1, releaseVersion: '0.2.0', webVersion: '0.2.0', pluginVersion: '1.7.1', gitTag: 'v0.2.0',
+      schemaVersion: 1, releaseVersion: '0.2.0', webVersion: '0.2.0', gitTag: 'v0.2.0',
     }))
     const config: ServerConfig = {
       host: '127.0.0.1', port: 8800, upstream: new URL('http://127.0.0.1:9119'),
@@ -53,7 +53,7 @@ describe('system update routes', () => {
     }
     const launched: string[] = []
     const latest = {
-      schemaVersion: 1 as const, releaseVersion: '0.3.0', webVersion: '0.3.0', pluginVersion: '1.8.0', gitTag: 'v0.3.0',
+      schemaVersion: 1 as const, releaseVersion: '0.3.0', webVersion: '0.3.0', gitTag: 'v0.3.0',
     }
     const updates = new SystemUpdateManager(config, {
       projectRoot,

Некоторые файлы не были показаны из-за большого количества измененных файлов