@zhin.js/adapter-discord 1.1.26 → 1.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/LICENSE +21 -0
  3. package/PERMITS.md +15 -14
  4. package/README.md +7 -2
  5. package/adapters/discord/index.js +3 -0
  6. package/adapters/discord/index.ts +3 -0
  7. package/agents/discord/conversation.js +70 -0
  8. package/agents/discord/conversation.ts +77 -0
  9. package/agents/discord/messages.js +18 -2
  10. package/agents/discord/messages.ts +18 -2
  11. package/agents/discord/skills/discord/SKILL.md +1 -1
  12. package/agents/discord/skills/discord/tools/react/index.js +7 -6
  13. package/agents/discord/skills/discord/tools/react/index.ts +8 -7
  14. package/agents/discord/skills/discord/tools/send_embed/index.js +6 -11
  15. package/agents/discord/skills/discord/tools/send_embed/index.ts +7 -12
  16. package/agents/discord/skills/discord-guild/tools/add_role/index.js +11 -9
  17. package/agents/discord/skills/discord-guild/tools/add_role/index.ts +11 -10
  18. package/agents/discord/skills/discord-guild/tools/create_thread/index.js +5 -5
  19. package/agents/discord/skills/discord-guild/tools/create_thread/index.ts +6 -6
  20. package/agents/discord/skills/discord-guild/tools/forum_post/index.js +7 -3
  21. package/agents/discord/skills/discord-guild/tools/forum_post/index.ts +7 -4
  22. package/agents/discord/skills/discord-guild/tools/list_roles/index.js +7 -8
  23. package/agents/discord/skills/discord-guild/tools/list_roles/index.ts +8 -9
  24. package/agents/discord/skills/discord-guild/tools/remove_role/index.js +11 -9
  25. package/agents/discord/skills/discord-guild/tools/remove_role/index.ts +11 -10
  26. package/lib/channel-visibility.d.ts +9 -0
  27. package/lib/channel-visibility.js +44 -0
  28. package/lib/endpoint.d.ts +1 -0
  29. package/lib/endpoint.js +76 -12
  30. package/lib/gateway.d.ts +1 -0
  31. package/lib/gateway.js +21 -8
  32. package/lib/index.d.ts +1 -1
  33. package/lib/index.js +1 -1
  34. package/lib/platform-permit.d.ts +4 -11
  35. package/lib/platform-permit.js +7 -40
  36. package/lib/protocol.d.ts +18 -0
  37. package/lib/protocol.js +32 -3
  38. package/lib/sender-standing.d.ts +18 -0
  39. package/lib/sender-standing.js +91 -0
  40. package/lib/webhook.d.ts +2 -6
  41. package/lib/webhook.js +23 -55
  42. package/package.json +23 -25
  43. package/plugin.js +0 -6
  44. package/schema.json +0 -56
  45. package/src/channel-visibility.ts +44 -0
  46. package/src/endpoint.ts +77 -11
  47. package/src/gateway.ts +22 -5
  48. package/src/index.ts +1 -6
  49. package/src/platform-permit.ts +5 -52
  50. package/src/protocol.ts +43 -3
  51. package/src/sender-standing.ts +91 -0
  52. package/src/webhook.ts +21 -58
package/CHANGELOG.md CHANGED
@@ -1,5 +1,180 @@
1
1
  # @zhin.js/adapter-discord
2
2
 
3
+ ## 1.1.28
4
+
5
+ ### Patch Changes
6
+
7
+ - c606d51: 各适配器按平台能力上报入站发送者的 `sender.platform`(ADR 0056 §1),并在能力画像 `scene.platformStanding` 中声明:OneBot11、NapCat、Milky、ICQQ 群消息上报群主 / 管理员 / 成员;QQ 官方频道上报频道主 / 超级管理员与身份组;Discord 服务器频道上报所有者 / 管理员 / 成员、身份组与 snake*case 权限位;Telegram 群消息按 `getChatMember` 上报 creator / administrator / member / 已离开,以及管理员的 `can*\*` 权限;KOOK 服务器频道上报服务器主 / 管理员角色、角色列表与权限位;飞书、钉钉群消息上报群主 / 管理员 / 成员;Sandbox 把模拟角色作为平台身份上报,不再授予框架主人角色。Satori、Slack、OneBot12、企业微信、LINE 的事件不带可靠的成员身份,不上报。README 补充「成员身份」说明。
8
+
9
+ 机器人自身身份(`management.inspectSelfStanding` + 能力画像 `scene.selfStanding`,供 `bot:*` permit):ICQQ、OneBot11、NapCat、Milky 群(`get_group_member_info` self);QQ 官方群(`getBotState`)与频道(机器人频道成员身份组);Discord(`guild.members.me` 身份组与频道权限);Telegram(`getChatMember` bot);KOOK(`/v3/user/view` self 的服务器角色与权限位);飞书(`chat.get` 群主与 `bot_manager_id_list`)。钉钉没有对应接口,不声明。群管理类 Agent 工具补上 `bot:admin` / `bot:owner` / `bot-permission:*`,需要发言者是群管的平台操作改用 `platform:admin` 等。
10
+
11
+ - 53932e5: 修复平台身份 permit 与操作目标不一致的问题(ADR 0056 §5):`platform:*` / `platform-permission:*` / `bot:*` / `bot-permission:*` 按**当前会话**判定,但群管理工具此前接受模型传入的任意群 / 服务器 / 频道 ID,机器人同在 A、B 两群当管理员时,A 群管理员可让 Agent 在 B 群踢人。
12
+
13
+ - 目标改为取自当前会话、去掉目标 ID 入参(模型传入的 ID 被忽略):ICQQ(踢人、禁言、设管理员、头衔、公告、匿名;设精华校验消息属于本群)、Telegram(邀请链接、置顶 / 取消置顶、群描述、默认权限)、Discord(加 / 移除身份组、身份组列表、建子线程)、KOOK(黑名单、授予 / 撤销 / 创建 / 删除角色)、飞书(加成员、设 / 撤管理员、改群信息、解散群)、NapCat(群公告、删公告、头衔、群头像;精华消息校验属于本群)、OneBot11(头衔)、QQ 官方频道(身份组增删建与列表、子频道列表、成员详情;子频道详情只限本频道)。核心场景治理工具工厂(`createSceneManagementTools`)同样只作用于调用消息所在会话,没有会话时拒绝;Agent 侧同名工厂改用与核心一致的 `platform:<地位>` + `bot:<地位>`(此前误作 zhin 角色)。
14
+ - 钉钉群管理接口使用旧版 `chatid`(无法由当前会话推出),`dingtalk_add_chat_members` / `dingtalk_update_chat` 改为要求 zhin `owner`(`update_chat` 此前没有任何门禁);`dingtalk_create_chat` 改为要求 zhin `trusted`(`admin` / `owner` 亦满足),不再依赖钉钉从不上报的 `platform-permission:chat_owner`。
15
+ - Slack 不上报发言者平台身份,频道工具改用 zhin 角色并只作用于当前频道:话题、用途、邀请、置顶 / 取消置顶要求 `admin`,归档 / 恢复归档要求 `owner`;`PERMITS.md` 同步修正。
16
+ - Discord:加 / 移除身份组要求目标身份组低于发起者的最高身份组(服务器主豁免;托管身份组拒绝),低位 `manage_roles` 管理员不能借机器人给自己加更高身份组。平台权限统一为服务器级:机器人自身改读 `GuildMember.permissions`(不再用频道级 `permissionsFor`);Interactions 模式的位域含频道覆盖,只上报不能被频道覆盖的权限(管理员上报全部),并用最近一次交互的 `app_permissions` 上报机器人自身身份(同一口径,10 分钟内有效)。
17
+ - Telegram:`set_permissions` 改要求 `platform-permission:restrict_members`,`set_description` 改 `change_info`,`create_invite` 改 `invite_users`;发送者 `getChatMember` 并发合并为一次、失败负缓存 10 秒,收到 `chat_member` / `my_chat_member` 更新时以新状态覆盖缓存(默认 `allowedUpdates` 增加这两项);restricted 成员的个人 `can_*` 不再作为平台权限上报(与普通成员一致,只有管理员上报权限)。
18
+ - KOOK:服务器主与持有「管理员」位的成员(含机器人自身)展开为全部权限;并入「全体成员」(role_id 0)的基础权限。
19
+ - 飞书:`chat.get` 失败或未返回 `owner_id` 时发送者 / 机器人地位为未知(不再报确定的 `member` 并缓存 60 秒),失败负缓存 10 秒。
20
+ - QQ 官方:发送者平台身份只在频道子频道上报(群、单聊、频道私信不上报)。
21
+ - `AdapterIndex.selfStanding`:共享查询使用独立的 10 秒期限,调用方的 `signal` 只中止自己的等待,不再取消他人共享的查询或把结果缓存为未知;查询期间被 `invalidateSelfStanding` 失效时不写回旧结果。
22
+ - OneBot11 / NapCat / Milky:机器人自身身份不再永久记住首次 `get_login_info` 的账号(重连或换号后刷新;只为合并突发请求复用 5 秒,查询失败即丢弃)。
23
+ - 删除遗留导出(生成永不匹配的 permit 或已不再注册):`discordGroupPermitResolver` / `checkDiscordPlatformPermit` / `normalizeDiscordSenderForPermit`、`telegramGroupPermitResolver` / `checkTelegramPlatformPermit` / `normalizeTelegramChatMember`、`kookGroupPermitResolver` / `checkKookPlatformPermit` / `normalizeKookSenderForPermit` / `KookSenderInfo`、`larkGroupPermitResolver` / `checkLarkPlatformPermit` / `normalizeLarkSenderForPermit`、`slackGroupPermitResolver` / `checkSlackPlatformPermit` / `normalizeSlackSenderForPermit`、`dingtalkGroupPermitResolver` / `checkDingtalkPlatformPermit` / `normalizeDingtalkSenderForPermit`、`wecomGroupPermitResolver` / `checkWecomPlatformPermit` / `normalizeWecomSenderForPermit`、`qqGuildPermitResolver` / `checkQqPlatformPermit` / `normalizeQqGuildSenderForPermit`。permit 一律交给内置评估器(`@zhin.js/permission`),`platformPermit()` 仍保留;各适配器 `PERMITS.md` 按实际上报的字段重写。
24
+
25
+ - 89b63fa: 适配器工具的操作目标与角色层级收尾(ADR 0056 §5):
26
+
27
+ - KOOK:`kook_grant_role` / `kook_revoke_role` 要求目标角色严格低于发起者的最高角色(KOOK 角色 `position` 值越小优先级越高;服务器主豁免;「全体成员」与不存在的角色拒绝),低位 `manage_roles` 成员不能借机器人给自己授予更高角色;`kook_blacklist` 拉黑时要求目标成员低于发起者、不能拉黑服务器主;`kook_list_roles` 改为只读当前服务器(去掉 `guild_id`)。
28
+ - 不带层级限定 owner 的工具不再接受任意群 / 频道 / 会话 ID,目标改为取自当前会话(模型传入的 ID 被忽略):
29
+ - ICQQ:`group_invite`、`group_member_info`、`group_sign`、`poke`、`group_files`、`list_muted`;
30
+ - Discord:`discord_react`、`discord_send_embed`(当前频道 / 线程 / 私信)、`discord_forum_post`(在当前帖子所属的论坛发帖);
31
+ - NapCat:精华列表、群公告列表、群文件(根目录、下载链接、上传)、群消息历史、AI 语音与角色、群详情、禁言列表、群签到;`get_friend_msg_history` 只读当前私聊;`send_poke` 在当前会话;`send_forward_msg` 发往当前会话,引用已有消息的节点只能引用当前会话的消息;
32
+ - Slack:`slack_add_reaction`、`slack_remove_reaction`、`slack_edit_message`;
33
+ - Telegram:`telegram_list_admins`、`telegram_member_count`、`telegram_react`、`telegram_send_poll`、`telegram_send_sticker`;
34
+ - LINE:`line_get_group_members`。
35
+ - 本身就跨会话的工具改为要求全局层 `owner`(`owner@global`):NapCat `forward_single_msg`(转发任意消息到任意好友 / 群)、`upload_group_file`(`file` 可为宿主本地路径)、钉钉 `dingtalk_send_work_notice`、企业微信 `wecom_send_text`(发给任意用户)。
36
+ - 各适配器 `PERMITS.md` 同步(Slack `slack_unarchive`、钉钉跨群工具更正为 `owner@global`)。
37
+
38
+ - 74f34c0: 适配器 Agent 工具不再读取宿主文件、不再绕过出站发送链:
39
+
40
+ - 读取宿主文件的工具要求全局层 `owner`(`owner@global`):飞书 `lark_upload_file`(本地路径)、NapCat `set_group_portrait`(另需 `bot:admin`)、`set_avatar`(同时是机器人账号身份)、`download_file`(由宿主网络拉取任意 URL 并写入宿主文件)。NapCat `ocr_image`、`send_group_notice` 的图片与 `send_forward_msg` 节点内的媒体只接受 http(s) 链接、`base64://` 或平台文件标识,拒绝 `file://` 与本机路径。
41
+ - 发消息的工具改经 IM 出站链(`outboundMessageToken` → 渲染 → 出站中间件 → Endpoint),平台特有内容用适配器的命名空间段:Discord `send_embed` → `discord:embed`;Telegram `send_poll` / `send_sticker` → `telegram:poll` / `telegram:sticker`(贴纸只接受 file_id 或 http(s) 链接);NapCat `send_forward_msg` → `napcat:node`(OneBot `node` 段);企业微信 `send_text` 以当前账号发往指定用户的会话。
42
+ - `pnpm check:harness-paths` 增加检查:适配器 Agent 工具直调平台发送接口即失败;无法由出站链表达的调用(钉钉工作通知、NapCat 单条原生转发与 AI 语音、Discord 建论坛帖 / 子线程)登记在 `scripts/agent-send-bypass-allowlist.json` 并写明理由。
43
+
44
+ - e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
45
+
46
+ **行为变更(升级前请阅读)**
47
+
48
+ - kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
49
+ - kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
50
+ - agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
51
+ - ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
52
+ - cli:`zhin send` / `watch` / `schedule` 改为与运行中的 Host 通信(新增 `POST /message/send` 与 `/assistant/jobs` 写接口),`schedule` 不再支持离线改文件;移除 `zhin uninstall service`(用 `zhin service uninstall`)、`build --analyze`、`install -S`;`zhin stop` 杀不掉进程时保留 pid 文件并以非零退出;`runtime migrate` 新增 `verify`;未设置 `TZ` 时调度默认时区改为系统时区;不带 `ZHIN_SUPERVISOR_PID` 的进程被 init 接管后不再自行退出。
53
+ - schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
54
+ - schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
55
+ - client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
56
+ - a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
57
+ - speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
58
+ - adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
59
+ - plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
60
+
61
+ **其余**
62
+
63
+ - host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
64
+ - pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
65
+ - command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
66
+ - html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
67
+ - 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
68
+
69
+ - a9c7a13: 聊天角色安全审查修复(ADR 0056 修订):
70
+
71
+ - 角色的作用范围:Runtime 在 `sender.chatRole` 之外写入 `sender.chatRoleLevels`(每个角色最高来自哪一层)。宿主全局能力——Agent 危险工具 / exec / 文件策略、主人审批的接收人、重启实例、写全局 / 平台记忆、定时任务的高信任运行、聊天改项目配置、`icqq login` 跨适配器恢复——只认**全局层** `owner`;增删适配器账号需要适配器层或以上的 `owner`。会话 / 账号 / 适配器层的 owner 在 Agent 信任档位上按 `admin` 计(`principal.roles`),链上角色保留在 `principal.chatRole` / `chatRoleLevels`。`@zhin.js/im-contract` / `@zhin.js/core` 新增 `chatRoleHeldAt`、`hostChatRole`、`ChatRoleLevels`。
72
+ - permit 新增层级限定写法 `<角色>@<层级>`(`owner@global`、`owner@adapter`、`admin@endpoint`……,也可写在 `role(…)` 中);不带层级的 `owner` 含义不变。
73
+ - 聊天 `角色 授予 / 撤销`:被替换或撤销的已有角色同样计入「被触及的角色」,低角色的授予不能覆盖同级或更高的角色,触及 owner 需更高层 owner;`角色 列表` 需要 admin,上级条目不显示身份。
74
+ - Console `chat-roles.grant|revoke`:涉及 owner(授予、替换、撤销)需要全局 `iam.manage`;`chat-roles.list` 对调用者作用域之外的条目脱敏(`redacted: true`,`ConsoleChatRoleEntry.adapter` / `userId` 变为可选)。
75
+ - 非关系型数据库时授予 / 撤销被拒绝(RPC 503 `chat-roles-unpersisted`,聊天回复「未保存」);迁移来的授予只在内存生效、记录保持 pending 并标记,不再「撤销后复活」。
76
+ - 迁移保持旧语义:适配器 `master` 迁为「没有自己 master 的账号」的账号层 owner(不再建适配器层 owner);`ai.trigger.masters / trusted` 不再登记到声明 `runtime.sandbox` 的模拟适配器与无法判断的适配器(写日志)。
77
+ - 线程 / 子话题沿用父会话键:Discord 线程上报为父频道 + `threadId`(出站仍发到线程);会话无法生成会话键时退回账号层链解析,全局 owner 不再丢失角色。
78
+ - 执行时复检重新读取发言者当前角色与机器人身份(`PermissionHost.setSenderRoleResolver` / `currentSenderRoles`);定时任务记录创建者所在会话,到期按创建者当前角色运行,普通用户的任务以普通成员信任运行。
79
+ - `AdapterIndex.selfStanding` 的 `cachedOnly` 读到过期缓存视为未知;入站时丢弃适配器上报的 `chatRole`,事件流发布增强后的 sender。`@zhin.js/testing` 的 `PluginTestKit` 声明的角色按全局层处理。
80
+ - 跨群 / 账号级 Agent 工具改用层级限定:钉钉 `add_chat_members` / `update_chat`、Slack `unarchive` 要求 `owner@global`;NapCat `delete_friend` 要求 `owner@endpoint`。
81
+
82
+ - 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
83
+
84
+ - zhin.js:实例首次启动把适配器 `master` / `trusted`、`endpoints[i].master|trusted` 与 `ai.trigger.masters|trusted` 迁入项目数据库 `chat_roles`(先记入 `.zhin/chat-roles-migration.json`,再从配置移除并记日志);之后配置再出现这些字段时启动报错并指向升级指南。平台身份不再映射为 zhin 角色:删除 `roles.mappings`(适配器块与 `endpoints[i].roles` 出现即启动报错)、`chat_role_mappings` 表与 Console `chat-roles.mappings` / `chat-roles.set-mappings`;`features.selfService.platformAdmins|roles|allowUsers` 删除;群内「功能」「角色」命令只认 zhin 角色,平台群主不再自动具备;聊天改配置、聊天重启、Agent 主人审批按 zhin `owner` 判断。
85
+ - @zhin.js/core(minor,破坏性):角色模型与解析移入 core(`ChatRoleService`、`createChatRoleSenderEnricher`),入站消息带 `sender.chatRole` 与归一的 `sender.platform`;删除 `SenderRole`、`senderRolesFromMessage`、`roleSatisfies` 等,`master` 改名 `owner`;删除映射规则 API(`createMappingChatRoleSource`、`DEFAULT_CHAT_ROLE_MAPPINGS` 等)与 `ChatRoleSource`;`createSenderEnricher` / `createConfigurationChatAuthorizer` 改为基于聊天角色。IM Runtime 为 PermissionHost 提供机器人自身身份(经 Adapter 索引缓存),机器人的角色变化事件使缓存失效;命令拒绝回复说明缺少的平台 / 机器人条件;`<Button permit>` 按点击者鉴权;场景治理工具工厂同时要求 `platform:*` 与 `bot:*`;`ai.trigger.masters|trusted` 删除。
86
+ - @zhin.js/permission(minor,破坏性):permit 语法 `owner` / `admin` / `trusted` / `role(...)`(zhin 角色)、`platform:owner|admin`、`platform-role:<id>`、`platform-permission:<name>`(发言者平台身份),新增 `bot:owner|admin`、`bot-role:<id>`、`bot-permission:<name>`(机器人自身平台身份,`PermissionSubject.bot`);`PermissionHost` 新增 `setBotStandingResolver`、`withBotStanding`、`firstDenied`,`checkAll` 可带 `source` 解析机器人身份;新增 `describeDeniedPermit`、`permitsNeedBotStanding`。删除 `role(master)`、`scene_admin`、`scene_owner`、`platform(adapter,perm)` 及 `registerPlatform`、`createSceneRolePlatformChecker`、`platformPermission`、`definePlatformPermission`,定义时报错并给出替代写法。
87
+ - @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
88
+ - @zhin.js/agent(minor,破坏性):危险工具、文件 / exec 策略、主人审批、Agent 回合主体只读 zhin 角色(`principal.roles` 只含展开的聊天角色,平台地位在 `principal.platform`);`SenderRole` → `PrincipalRole`,`SELF_CHANGE_MASTER_ROLE` → `SELF_CHANGE_OWNER_ROLE`;回合开始时读取机器人自身身份(`contextState.bot.platform`),按三条维度过滤 tool / skill / Agent 包后才披露,执行工具时再校验一次;群规「群主和管理员豁免」改为平台群主 / 管理员与 zhin `owner`。
89
+ - @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
90
+ - @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
91
+ - @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
92
+ - @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
93
+ - @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
94
+ - @zhin.js/ai:注释更新。
95
+ - @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
96
+ - @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
97
+ - @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
98
+ - @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
99
+ - 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
100
+ - 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
101
+
102
+ - c2bbdcf: Console 访问控制(ADR 0049):用户、角色、会话、API 令牌与审计日志存入项目数据库,每个 Console RPC、`/api` 路由与 Host 鉴权的 WebSocket 都按 `@zhin.js/console-protocol` 的权限表放行,未登记的一律拒绝。
103
+
104
+ **破坏性变更**
105
+
106
+ - `http.tokens` 与演示模式(`scope: demo` / `user`)删除;配置里仍有 `http.tokens` 时 Host 拒绝启动。Host 配置 Schema 同步删除该字段。
107
+ - `http.token` 变为初始化令牌:只在创建第一个所有者之前有效,之后在所有接口上被拒绝。
108
+ - 未在 `CONSOLE_WS_PERMISSIONS` 登记、又使用 Host 鉴权的插件 WebSocket 不再接受 Console 账号;插件自己的 WebSocket 应改用 `ws(path, { auth: 'protocol' })` 并自行校验凭据(新增 `verifyProtocolAccessToken`、`isLoopbackAddress`)。
109
+ - OneBot 11 / 12、NapCat、Milky 的反向 WebSocket 改为只认适配器自己的 `access_token`;未配置 `access_token` 时只接受本机回环连接。
110
+ - `zhin doctor --live` 等改从 `ZHIN_CONSOLE_TOKEN` 读取 API 令牌(仍兼容 `ZHIN_HTTP_TOKEN`)。
111
+
112
+ **迁移步骤**(详见文档「升级到 Console 访问控制」)
113
+
114
+ 1. 升级后用 `http.token` 打开 Console 初始化向导创建第一个所有者,或运行 `zhin console init`(脚本:`zhin console init --yes --owner <名> --password-stdin`)。
115
+ 2. 删除配置里的 `http.tokens`,在 Console「访问控制」里为原来的令牌持有人创建用户并绑定角色(`viewer` / `operator` / `admin`);演示环境改用 `viewer` 账号。
116
+ 3. 自动化在 Console 签发 API 令牌,放进 `ZHIN_CONSOLE_TOKEN`。
117
+ 4. 从其他机器或容器连接的反向 WebSocket endpoint 补上 `access_token`。
118
+ 5. 忘记密码或所有者被锁时,停下 Host,用 `zhin console user passwd|enable|create` 离线恢复。
119
+
120
+ MCP / A2A 的 Bearer 访问同样接受用户 API 令牌(分别需要 `mcp.access`、`a2a.access`)。适配器与插件文档同步改为账号与角色的说法。
121
+
122
+ - 5cd9d3d: HTTP 路由契约改为 Web 标准 `Request` / `Response`(ADR 0054 §2,B1.0)
123
+
124
+ - host-http-contract:路由处理函数签名改为 `(request, context) => Response`,`context` 提供 `url`、`params`、`principal`、`remoteAddress`;新增 `readBodyBytes` / `readTextBody` / `readJsonBody`(带大小上限,超限先读完再报 413)、`jsonResponse` / `emptyResponse`、带背压的 `createResponseStream`(SSE、大文件下载)与 `WsConnection`。契约不再引用 `node:http` / `ws`。
125
+ - host-http:Node 服务器移到 `@zhin.js/host-http/node`(`createHttpHost`),负责 Node 请求与 `Request` / `Response` 的互转;认证结果经 `context.principal` 传给路由,删除旧的按请求取主体的辅助函数;未预期的异常只返回通用错误信息,细节写日志。
126
+ - runtime、mcp、a2a、gateway、zhin.js、calendar 插件与各适配器的 Webhook / 反向 WebSocket 路由迁移到新契约,行为不变。
127
+
128
+ - 663473b: Agent 模型输出不能再借出站媒体段发送宿主文件(ADR 0056 §2):
129
+
130
+ - 此前模型可以在回复里写 `{"kind":"file","value":"file:///etc/passwd"}`(或 `/etc/passwd`)这样的「平台文件引用」,Agent 发布层原样放行,OneBot / NapCat 会把它当作本地文件读取上传;模型以 `path` 引用工作区文件时也只做了工作区与敏感文件名检查,没有按发起人角色做 `read_file` 的读取判定(普通成员可发出 `.git/config`、`package.json`)。
131
+ - Core 新增不可信来源的出站媒体策略:`untrustedContent(content, trust)` 包装的内容在渲染器里(出站中间件与 Endpoint 之前,出站链仍唯一)只允许 http(s) 链接、有上限的内联数据(默认 25 MiB)与裸平台文件标识;本地路径(含 `file://`)只在 `trust.authorizePath` 认可或由可信代码 `trustedMediaRef()` 构造时放行;嵌套的本地来源拒绝,`html` 只保留文字,不做 `${…}` 模板替换。被拒的段替换为可见提示(「[图片未发送:媒体来源不被允许]」)并记录 `op=outbound_media_refused`。
132
+ - Agent 的回复、流式回复(`OpenReplyStreamOptions.mediaTrust`)、场景事件回复、主动发送与 QQ / ICQQ / Telegram / Discord / NapCat / 企业微信的 Agent 工具发送都按不可信来源投递;模型引用的本地路径按发起人文件角色(只有全局 `owner` 是 `owner`)做与 `read_file` 相同的判定,需要确认的敏感读取直接拒绝。插件代码自己构造的内容不受影响;工作区内工具生成的截图、图表与 Agent 落盘的大附件照常发送。
133
+
134
+ - 68659cd: `zod` 改为运行时依赖(原为可选对等依赖):插件运行时在启动时就会加载这些包的约定目录(Agent 工具、命令等),其中静态导入了 `zod`;生成的项目里没有安装可选对等依赖,启动会报 `Cannot find package 'zod'`。范围为 `^4.6.7`(已修复的版本)。
135
+ - Updated dependencies [53932e5]
136
+ - Updated dependencies [57c6cdc]
137
+ - Updated dependencies [e1fda87]
138
+ - Updated dependencies [4e8ba38]
139
+ - Updated dependencies [a9c7a13]
140
+ - Updated dependencies [120e225]
141
+ - Updated dependencies [c2bbdcf]
142
+ - Updated dependencies [c2bbdcf]
143
+ - Updated dependencies [63595fc]
144
+ - Updated dependencies [fd055d2]
145
+ - Updated dependencies [4e8ba38]
146
+ - Updated dependencies [cc7a5f9]
147
+ - Updated dependencies [4e8ba38]
148
+ - Updated dependencies [f8bf684]
149
+ - Updated dependencies [e0bc008]
150
+ - Updated dependencies [5cd9d3d]
151
+ - Updated dependencies [5cd9d3d]
152
+ - Updated dependencies [c2bbdcf]
153
+ - Updated dependencies [f8bf684]
154
+ - Updated dependencies [663473b]
155
+ - Updated dependencies [c606d51]
156
+ - Updated dependencies [5cd9d3d]
157
+ - Updated dependencies [d655ef0]
158
+ - Updated dependencies [1e54b1e]
159
+ - @zhin.js/adapter@1.1.33
160
+ - @zhin.js/core@1.2.0
161
+ - @zhin.js/logger@1.1.3
162
+ - @zhin.js/host-http@1.2.0
163
+ - @zhin.js/feature-kit@1.1.16
164
+ - @zhin.js/agent-feature@1.1.17
165
+ - @zhin.js/console-contract@1.1.6
166
+ - @zhin.js/permission@1.2.0
167
+ - @zhin.js/skill@1.1.17
168
+ - @zhin.js/tool@1.1.19
169
+ - @zhin.js/im-contract@1.1.14
170
+ - @zhin.js/page@1.1.18
171
+
172
+ ## 1.1.27
173
+
174
+ ### Patch Changes
175
+
176
+ - ae4c8ae: fix(adapter-discord): `listChannels` 默认过滤 Discord 混淆频道(`flags` 含 `CHANNEL_OBFUSCATED` = `1 << 17`)。自 2026-11-16 起,机器人缺少 `VIEW_CHANNEL` 的频道会以 `___hidden___` 名称经 Gateway 下发,而 HTTP `GET /guilds/{id}/channels` 不再返回它们。Console 频道列表不再显示机器人无权查看的频道,与 Discord HTTP 列表一致。在 Discord 开发者后台 Overview > Bot 打开 Private Channel Obfuscation,可以让 Gateway 提前下发这些混淆频道(该开关是临时测试;HTTP 列表没有对应的提前开关)。
177
+
3
178
  ## 1.1.26
4
179
 
5
180
  ### Patch Changes
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 凉菜
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PERMITS.md CHANGED
@@ -1,25 +1,26 @@
1
1
  # Discord Platform Permits
2
2
 
3
- ## 入站字段
4
-
5
- Guild 频道消息从 `msg.member.permissions` bitfield 解析:
3
+ ## 入站字段(ADR 0056 §1)
6
4
 
7
5
  | 字段 | 取值 |
8
6
  |------|------|
9
- | `$sender.role` | `owner`(`guild.ownerId === author.id`)· `member` |
10
- | `$sender.permissions` | `guild_owner` · `ADMINISTRATOR` · `MANAGE_ROLES` · `MODERATE_MEMBERS` · `MANAGE_CHANNELS` · … |
7
+ | `sender.platform.standing` | `owner`(服务器主)· `admin`(`administrator` / `moderate_members`)· `member` |
8
+ | `sender.platform.roles` | 发送者的服务器身份组(不含 `@everyone`) |
9
+ | `sender.platform.permissions` | **服务器级**权限名(snake_case,如 `manage_roles`、`ban_members`) |
10
+
11
+ 权限口径统一为服务器级:
11
12
 
12
- 需 `GuildMembers` intent;缺失时 checker 保守拒绝。
13
+ - Gateway 模式:发送者与机器人自身都读 `GuildMember.permissions`(不含频道覆盖)。
14
+ - Interactions 模式:交互只带频道级位域(已叠加频道覆盖),因此只上报不能被频道覆盖的权限(`administrator`、`kick_members`、`ban_members`、`manage_guild`、`moderate_members`、`manage_nicknames` …),管理员上报全部权限;`manage_roles`、`manage_channels` 等在此模式下不上报。机器人自身身份取自该服务器最近一次交互的 `app_permissions`(同样口径,10 分钟内有效),否则未知。
13
15
 
14
16
  ## Permit 词汇表
15
17
 
16
- | `platform(discord,…)` | 含义 |
17
- |-----------------------|------|
18
- | `guild_owner` | 服务器主 |
19
- | `moderate_members` | 踢人/禁言 |
20
- | `manage_roles` | 管理身份组 |
21
- | `manage_channels` | 管理频道/线程 |
18
+ | Permit | 含义 |
19
+ |--------|------|
20
+ | `platform:owner` / `platform:admin` | 服务器主 / 管理员(含服务器主) |
21
+ | `platform-permission:<name>` | 服务器级权限,如 `manage_roles`、`manage_channels`、`moderate_members` |
22
+ | `bot:*` / `bot-permission:<name>` | 同上,判定机器人账号自身 |
22
23
 
23
- ## 工厂映射
24
+ 平台身份与机器人身份都按**当前会话**判定,因此服务器管理工具只作用于当前服务器 / 频道(不接受 `guild_id` / `channel_id` 入参)。`discord_add_role` / `discord_remove_role` 另外要求目标身份组低于发起者的最高身份组(服务器主豁免)。
24
25
 
25
- `scene_admin` → `moderate_members` · `scene_owner` → `guild_owner`
26
+ 不带平台 permit 的工具同样只作用于当前会话:`discord_react` / `discord_send_embed` 作用于当前频道(线程内为该线程,私信为该私信);`discord_forum_post` 只在论坛帖子里可用,在该帖子所属的论坛中发新帖(不接受 `channel_id`)。
package/README.md CHANGED
@@ -7,6 +7,7 @@ Zhin.js Discord 适配器(Plugin Runtime),默认通过 **Gateway WebSocket
7
7
  - Gateway WebSocket 入站(默认;无需公网 HTTPS / host)
8
8
  - 解析 text / mention / attachment / embed / sticker / button
9
9
  - 支持私聊、群组与服务器频道
10
+ - `listChannels` 会过滤带 `CHANNEL_OBFUSCATED`(`1 << 17`)的混淆频道:自 2026-11-16 起,机器人缺少 `VIEW_CHANNEL` 时 Gateway 仍会下发这些频道(名字常为 `___hidden___`),HTTP 频道列表则不会返回它们。
10
11
  - 出站 `send({ conversation, payload })` → Discord channel message(Markdown content / media / embed / keyboard)
11
12
  - 约定式 `defineAdapter` / `definePlugin`(无需 `usePlugin`)
12
13
  - Interactions HTTP webhook(需 `httpHostToken`),支持验签、PING 与 slash command
@@ -31,7 +32,7 @@ pnpm add @zhin.js/adapter-discord discord.js
31
32
 
32
33
  ### 平台权限(platform permit)
33
34
 
34
- - sender role 已恢复:Gateway 入站 `metadata.role` / `metadata.permissions`(来自 member 权限位与 guild owner 判定,见 `src/gateway.ts` `resolveSenderRole`)。
35
+ - 成员身份:服务器频道消息上报 `sender.platform`(见下文「成员身份」);`metadata.role` / `metadata.permissions` 仅为兼容保留。
35
36
  - `plugin.ts` 在 generation setup 注册 checker,并在 dispose 注销;Plugin Runtime CapabilityIngress 与 ToolSystem 统一经 Core `canAccessTool()` 消费 `permissions`。
36
37
 
37
38
  ## 前置条件
@@ -96,7 +97,7 @@ discord:
96
97
  - 在账号库保存、修改、启动、停止、替换或删除该 Adapter 的账号;新增仅保存,不创建 SDK Client,需手动启动;
97
98
  - 如果适配器要求登录,页面会显示 LoginAssist 的扫码 / 滑块 / 设备确认待办;
98
99
 
99
- 读取需要 `discord:read`,写操作需要 `discord:write`;管理员 full token 不受限。页面里的「添加 endpoint」等价于原来的 `discord endpoint add`。
100
+ 读取需要 `discord:read`(`read` 级别,内置角色 `viewer` 及以上都有);增删改账号等写操作需要 `discord:write`(`operate` 级别,`operator` 及以上都有,绑定到本适配器的角色也算),首次迁移还需管理员身份;全局所有者不受限,见[插件权限的级别](https://zhin.js.org/console/#插件权限的级别)。页面里的「添加 endpoint」等价于原来的 `discord endpoint add`。
100
101
 
101
102
  首次修改启动配置里的既有账号前,管理员必须核对清单并确认一次迁移。原 canonical 身份与历史保留,完整账号配置加密进入 Host 数据库;此后账号管理只写数据库,不修改启动文件或 `.env`,不重启进程。没有持久化账号端口的环境可使用静态配置连接,动态写操作明确不可用。
102
103
 
@@ -151,3 +152,7 @@ Gateway 和 Interactions 模式均通过资料端口暴露当前认证账号的
151
152
  支持修改昵称和头像;其他资料字段没有对应适配器操作时不声明可写。平台响应提供有效头像资料时返回其 CDN URL;若仅确认修改成功,则不返回未确认的资料。图片字节只在请求内部使用,不返回模型;Agent 解析图片沿用现有本地图片和网络权限。
152
153
 
153
154
  `nickname` / `profile` 配置仅补足平台缺失字段,Endpoint 配置优先于适配器默认值。接口依据 [discord.js ClientUser](https://discord.js.org/docs/packages/discord.js/main/ClientUser:Class)。
155
+
156
+ ## 成员身份
157
+
158
+ 服务器频道消息上报 `sender.platform`:服务器所有者 → `owner`;拥有 `Administrator` 或 `ModerateMembers` → `admin`;其余 → `member`。`roles` 为成员持有的身份组(不含 `@everyone`,Gateway 消息带名称、斜杠命令只有 id);`permissions` 为成员的服务器权限位,按 snake_case 命名(`ban_members`、`manage_roles` …)。私信不上报。能力画像:`channel.scene.platformStanding = { standing: true, roles: true, permissions: true }`。详见 [ADR 0056 §1](https://github.com/zhinjs/zhin/blob/main/docs/adr/0056-chat-roles.md)。
@@ -32,6 +32,9 @@ export default defineAdapter({
32
32
  feedback: { mode: 'reaction' },
33
33
  delivery: { send: true, proactive: true, spool: true },
34
34
  },
35
+ // ADR 0056 §1:服务器频道消息上报群主 / 管理员 / 成员、身份组与权限位。
36
+ // 机器人自身:guild.members.me 的身份组与频道权限(bot:admin、bot-permission:manage_roles 等)。
37
+ channel: { scene: { platformStanding: { standing: true, roles: true, permissions: true }, selfStanding: { standing: true, roles: true, permissions: true } } },
35
38
  },
36
39
  createAdapter: context => new DiscordAdapter(context),
37
40
  });
@@ -43,6 +43,9 @@ export default defineAdapter<DiscordEndpointConfig>({
43
43
  feedback: { mode: 'reaction' },
44
44
  delivery: { send: true, proactive: true, spool: true },
45
45
  },
46
+ // ADR 0056 §1:服务器频道消息上报群主 / 管理员 / 成员、身份组与权限位。
47
+ // 机器人自身:guild.members.me 的身份组与频道权限(bot:admin、bot-permission:manage_roles 等)。
48
+ channel: { scene: { platformStanding: { standing: true, roles: true, permissions: true }, selfStanding: { standing: true, roles: true, permissions: true } } },
46
49
  },
47
50
  createAdapter: context => new DiscordAdapter(context),
48
51
  });
@@ -0,0 +1,70 @@
1
+ // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { outboundMessageToken, untrustedContent } from '@zhin.js/core/runtime';
3
+ import { messages as t } from './messages.js';
4
+ /**
5
+ * The trusted turn owns the guild channel; model input cannot select another one. Platform
6
+ * (`platform-permission:*`) and Bot (`bot-permission:*`) permits are judged in the current
7
+ * conversation, so tools that rely on them act on the current guild / channel only (ADR 0056 §5).
8
+ */
9
+ export function currentGuildChannel(context) {
10
+ const { origin } = context;
11
+ const conversation = origin?.kind === 'im' && origin.platform === 'discord' ? origin.conversation : undefined;
12
+ const guildId = conversation?.kind === 'channel' && conversation.parent?.kind === 'channel' ? conversation.parent.id : '';
13
+ if (!conversation || !guildId)
14
+ throw new Error(t(context.locale, 'guildChannelRequired'));
15
+ context.signal?.throwIfAborted();
16
+ return { guildId, channelId: conversation.threadId ?? conversation.id };
17
+ }
18
+ /**
19
+ * The current Discord conversation's channel: the thread when there is one (`channelId`), and the
20
+ * conversation's own channel (`conversationChannelId`: the parent channel of a thread, e.g. the forum
21
+ * of a forum post). Works in DMs and guild channels; model input cannot select another channel.
22
+ */
23
+ export function currentChannel(context) {
24
+ const { origin } = context;
25
+ const conversation = origin?.kind === 'im' && origin.platform === 'discord' ? origin.conversation : undefined;
26
+ if (!conversation?.id)
27
+ throw new Error(t(context.locale, 'conversationRequired'));
28
+ context.signal?.throwIfAborted();
29
+ const guildId = conversation.kind === 'channel' && conversation.parent?.kind === 'channel' ? conversation.parent.id : undefined;
30
+ return { channelId: conversation.threadId ?? conversation.id, conversationChannelId: conversation.id, ...(guildId ? { guildId } : {}) };
31
+ }
32
+ /**
33
+ * Deliver through the IM outbound chain (renderer → outbound middleware → Endpoint) to the current
34
+ * conversation (CLAUDE.md Guardrail #1); tools never call the Discord SDK's `send` themselves.
35
+ */
36
+ export async function sendToCurrentConversation(context, content) {
37
+ const { origin } = context;
38
+ const conversation = origin?.kind === 'im' && origin.platform === 'discord' ? origin.conversation : undefined;
39
+ if (!conversation?.id)
40
+ throw new Error(t(context.locale, 'conversationRequired'));
41
+ context.signal?.throwIfAborted();
42
+ // Built from model input: Core admits only remote / inline media and platform tokens (ADR 0056 §2).
43
+ const receipt = await context.use(outboundMessageToken).send({
44
+ requester: context.owner.id,
45
+ conversation,
46
+ content: untrustedContent(content, { source: 'discord:agent-tool', locale: context.locale }),
47
+ });
48
+ return { success: receipt.status === 'sent', ...(receipt.message?.id ? { message_id: receipt.message.id } : {}), receipt };
49
+ }
50
+ /**
51
+ * Discord role hierarchy for the requester (the Bot's own hierarchy is enforced by Discord): a member
52
+ * with `manage_roles` may only manage roles strictly below their highest role; the guild owner is exempt.
53
+ * Without this check a low-placed manager could have the Bot grant them a higher role.
54
+ */
55
+ export async function requireRoleBelowRequester(context, guild, roleId) {
56
+ const role = await guild.roles.fetch(roleId);
57
+ context.signal?.throwIfAborted();
58
+ if (!role || role.id === guild.id)
59
+ return t(context.locale, 'roleMissing', { p0: roleId });
60
+ if (role.managed)
61
+ return t(context.locale, 'roleAboveRequester', { p0: roleId });
62
+ const requester = context.principal?.subjectId?.trim();
63
+ if (!requester)
64
+ return t(context.locale, 'roleAboveRequester', { p0: roleId });
65
+ if (requester === guild.ownerId)
66
+ return undefined;
67
+ const member = await guild.members.fetch(requester);
68
+ context.signal?.throwIfAborted();
69
+ return role.position < member.roles.highest.position ? undefined : t(context.locale, 'roleAboveRequester', { p0: roleId });
70
+ }
@@ -0,0 +1,77 @@
1
+ import { outboundMessageToken, untrustedContent, type SendContent } from '@zhin.js/core/runtime';
2
+ import type { ToolExecutionContext } from '@zhin.js/tool';
3
+ import { messages as t } from './messages.js';
4
+
5
+ export type DiscordToolContext = ToolExecutionContext<unknown, 'discord'>;
6
+
7
+ /**
8
+ * The trusted turn owns the guild channel; model input cannot select another one. Platform
9
+ * (`platform-permission:*`) and Bot (`bot-permission:*`) permits are judged in the current
10
+ * conversation, so tools that rely on them act on the current guild / channel only (ADR 0056 §5).
11
+ */
12
+ export function currentGuildChannel(context: DiscordToolContext): { guildId: string; channelId: string } {
13
+ const { origin } = context;
14
+ const conversation = origin?.kind === 'im' && origin.platform === 'discord' ? origin.conversation : undefined;
15
+ const guildId = conversation?.kind === 'channel' && conversation.parent?.kind === 'channel' ? conversation.parent.id : '';
16
+ if (!conversation || !guildId) throw new Error(t(context.locale, 'guildChannelRequired'));
17
+ context.signal?.throwIfAborted();
18
+ return { guildId, channelId: conversation.threadId ?? conversation.id };
19
+ }
20
+
21
+ /**
22
+ * The current Discord conversation's channel: the thread when there is one (`channelId`), and the
23
+ * conversation's own channel (`conversationChannelId`: the parent channel of a thread, e.g. the forum
24
+ * of a forum post). Works in DMs and guild channels; model input cannot select another channel.
25
+ */
26
+ export function currentChannel(context: DiscordToolContext): { channelId: string; conversationChannelId: string; guildId?: string } {
27
+ const { origin } = context;
28
+ const conversation = origin?.kind === 'im' && origin.platform === 'discord' ? origin.conversation : undefined;
29
+ if (!conversation?.id) throw new Error(t(context.locale, 'conversationRequired'));
30
+ context.signal?.throwIfAborted();
31
+ const guildId = conversation.kind === 'channel' && conversation.parent?.kind === 'channel' ? conversation.parent.id : undefined;
32
+ return { channelId: conversation.threadId ?? conversation.id, conversationChannelId: conversation.id, ...(guildId ? { guildId } : {}) };
33
+ }
34
+
35
+ /**
36
+ * Deliver through the IM outbound chain (renderer → outbound middleware → Endpoint) to the current
37
+ * conversation (CLAUDE.md Guardrail #1); tools never call the Discord SDK's `send` themselves.
38
+ */
39
+ export async function sendToCurrentConversation(context: DiscordToolContext, content: SendContent) {
40
+ const { origin } = context;
41
+ const conversation = origin?.kind === 'im' && origin.platform === 'discord' ? origin.conversation : undefined;
42
+ if (!conversation?.id) throw new Error(t(context.locale, 'conversationRequired'));
43
+ context.signal?.throwIfAborted();
44
+ // Built from model input: Core admits only remote / inline media and platform tokens (ADR 0056 §2).
45
+ const receipt = await context.use(outboundMessageToken).send({
46
+ requester: context.owner.id,
47
+ conversation,
48
+ content: untrustedContent(content, { source: 'discord:agent-tool', locale: context.locale }),
49
+ });
50
+ return { success: receipt.status === 'sent', ...(receipt.message?.id ? { message_id: receipt.message.id } : {}), receipt };
51
+ }
52
+
53
+ interface RoleLike { readonly id: string; readonly position: number; readonly managed?: boolean }
54
+ interface GuildLike {
55
+ readonly id: string;
56
+ readonly ownerId: string;
57
+ readonly roles: { fetch(id: string): Promise<RoleLike | null> };
58
+ readonly members: { fetch(id: string): Promise<{ readonly roles: { readonly highest: RoleLike } }> };
59
+ }
60
+
61
+ /**
62
+ * Discord role hierarchy for the requester (the Bot's own hierarchy is enforced by Discord): a member
63
+ * with `manage_roles` may only manage roles strictly below their highest role; the guild owner is exempt.
64
+ * Without this check a low-placed manager could have the Bot grant them a higher role.
65
+ */
66
+ export async function requireRoleBelowRequester(context: DiscordToolContext, guild: GuildLike, roleId: string): Promise<string | undefined> {
67
+ const role = await guild.roles.fetch(roleId);
68
+ context.signal?.throwIfAborted();
69
+ if (!role || role.id === guild.id) return t(context.locale, 'roleMissing', { p0: roleId });
70
+ if (role.managed) return t(context.locale, 'roleAboveRequester', { p0: roleId });
71
+ const requester = context.principal?.subjectId?.trim();
72
+ if (!requester) return t(context.locale, 'roleAboveRequester', { p0: roleId });
73
+ if (requester === guild.ownerId) return undefined;
74
+ const member = await guild.members.fetch(requester);
75
+ context.signal?.throwIfAborted();
76
+ return role.position < member.roles.highest.position ? undefined : t(context.locale, 'roleAboveRequester', { p0: roleId });
77
+ }
@@ -1,6 +1,22 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
2
  import { createMessages } from 'zhin.js/i18n';
3
3
  export const messages = createMessages({
4
+ "guildChannelRequired": {
5
+ "zh-CN": "此操作仅支持当前 Discord 服务器频道",
6
+ "en": "This operation requires the current Discord server channel"
7
+ },
8
+ "conversationRequired": {
9
+ "zh-CN": "此操作仅支持当前 Discord 会话",
10
+ "en": "This operation requires the current Discord conversation"
11
+ },
12
+ "roleMissing": {
13
+ "zh-CN": "当前服务器没有身份组 {p0}",
14
+ "en": "Role {p0} does not exist in this server"
15
+ },
16
+ "roleAboveRequester": {
17
+ "zh-CN": "身份组 {p0} 不低于你的最高身份组,不能由你管理",
18
+ "en": "Role {p0} is not below your highest role, so you cannot manage it"
19
+ },
4
20
  "reactionAdded": {
5
21
  "zh-CN": "已添加反应 {p0}",
6
22
  "en": "Reaction added: {p0}"
@@ -38,8 +54,8 @@ export const messages = createMessages({
38
54
  "en": "Forum post \"{p0}\" created"
39
55
  },
40
56
  "notForumChannel": {
41
- "zh-CN": "Channel {p0} 不是论坛频道",
42
- "en": "Channel {p0} is not a forum channel"
57
+ "zh-CN": "Channel {p0} 不是论坛频道(请在论坛的帖子里发起)",
58
+ "en": "Channel {p0} is not a forum channel (ask from a post in the forum)"
43
59
  },
44
60
  "memberRoleRemoved": {
45
61
  "zh-CN": "已移除用户 {p0} 的角色",
@@ -1,6 +1,22 @@
1
1
  import { createMessages } from 'zhin.js/i18n';
2
2
 
3
3
  export const messages = createMessages({
4
+ "guildChannelRequired": {
5
+ "zh-CN": "此操作仅支持当前 Discord 服务器频道",
6
+ "en": "This operation requires the current Discord server channel"
7
+ },
8
+ "conversationRequired": {
9
+ "zh-CN": "此操作仅支持当前 Discord 会话",
10
+ "en": "This operation requires the current Discord conversation"
11
+ },
12
+ "roleMissing": {
13
+ "zh-CN": "当前服务器没有身份组 {p0}",
14
+ "en": "Role {p0} does not exist in this server"
15
+ },
16
+ "roleAboveRequester": {
17
+ "zh-CN": "身份组 {p0} 不低于你的最高身份组,不能由你管理",
18
+ "en": "Role {p0} is not below your highest role, so you cannot manage it"
19
+ },
4
20
  "reactionAdded": {
5
21
  "zh-CN": "已添加反应 {p0}",
6
22
  "en": "Reaction added: {p0}"
@@ -38,8 +54,8 @@ export const messages = createMessages({
38
54
  "en": "Forum post \"{p0}\" created"
39
55
  },
40
56
  "notForumChannel": {
41
- "zh-CN": "Channel {p0} 不是论坛频道",
42
- "en": "Channel {p0} is not a forum channel"
57
+ "zh-CN": "Channel {p0} 不是论坛频道(请在论坛的帖子里发起)",
58
+ "en": "Channel {p0} is not a forum channel (ask from a post in the forum)"
43
59
  },
44
60
  "memberRoleRemoved": {
45
61
  "zh-CN": "已移除用户 {p0} 的角色",
@@ -16,4 +16,4 @@ tools:
16
16
  ---
17
17
  # Discord
18
18
 
19
- 用 react 回应消息,用 send_embed 发送结构化内容;使用真实消息和频道 ID。
19
+ 用 react 回应当前频道中的消息,用 send_embed 在当前频道发送结构化内容;两者都只作用于当前会话,使用真实消息 ID。
@@ -1,22 +1,23 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
2
  import { messages as t } from "../../../../messages.js";
3
+ import { currentChannel } from "../../../../conversation.js";
3
4
  import { defineAgentTool } from '@zhin.js/tool';
4
5
  import { z } from 'zod';
5
6
  import { requireDiscordGatewayClient } from '@zhin.js/adapter-discord';
6
7
  export default defineAgentTool({
7
- description: '对 Discord 消息添加表情反应',
8
+ description: '对当前 Discord 频道(或线程)中的消息添加表情反应',
8
9
  inputSchema: z.object({
9
- channel_id: z.string().describe('频道 ID'),
10
- message_id: z.string().describe('消息 ID'),
10
+ message_id: z.string().describe('当前频道中的消息 ID'),
11
11
  emoji: z.string().describe('表情(Unicode 表情或自定义表情如 <:name:id>)'),
12
12
  }),
13
13
  adapter: 'discord',
14
14
  tags: ['discord'],
15
- async execute({ channel_id, message_id, emoji }, context) {
15
+ async execute({ message_id, emoji }, context) {
16
+ const { channelId } = currentChannel(context);
16
17
  const client = requireDiscordGatewayClient(context.$client);
17
- const channel = await client.channels.fetch(channel_id);
18
+ const channel = await client.channels.fetch(channelId);
18
19
  if (!channel?.isTextBased() || !channel.messages) {
19
- throw new Error(t(context.locale, 'notTextChannel', { p0: channel_id }));
20
+ throw new Error(t(context.locale, 'notTextChannel', { p0: channelId }));
20
21
  }
21
22
  const message = await channel.messages.fetch(message_id);
22
23
  await message.react(emoji);
@@ -1,22 +1,23 @@
1
1
  import { messages as t } from "../../../../messages.js";
2
+ import { currentChannel } from "../../../../conversation.js";
2
3
  import { defineAgentTool } from '@zhin.js/tool';
3
4
  import { z } from 'zod';
4
5
  import { requireDiscordGatewayClient } from '@zhin.js/adapter-discord';
5
6
 
6
- export default defineAgentTool<{ channel_id: string; message_id: string; emoji: string }>({
7
- description: '对 Discord 消息添加表情反应',
7
+ export default defineAgentTool<{ message_id: string; emoji: string }>({
8
+ description: '对当前 Discord 频道(或线程)中的消息添加表情反应',
8
9
  inputSchema: z.object({
9
- channel_id: z.string().describe('频道 ID'),
10
- message_id: z.string().describe('消息 ID'),
10
+ message_id: z.string().describe('当前频道中的消息 ID'),
11
11
  emoji: z.string().describe('表情(Unicode 表情或自定义表情如 <:name:id>)'),
12
12
  }),
13
13
  adapter: 'discord',
14
14
  tags: ['discord'],
15
- async execute({ channel_id, message_id, emoji }: { channel_id: string; message_id: string; emoji: string }, context) {
15
+ async execute({ message_id, emoji }, context) {
16
+ const { channelId } = currentChannel(context);
16
17
  const client = requireDiscordGatewayClient(context.$client);
17
- const channel = await client.channels.fetch(channel_id);
18
+ const channel = await client.channels.fetch(channelId);
18
19
  if (!channel?.isTextBased() || !channel.messages) {
19
- throw new Error(t(context.locale, 'notTextChannel', { p0: channel_id }));
20
+ throw new Error(t(context.locale, 'notTextChannel', { p0: channelId }));
20
21
  }
21
22
  const message = await channel.messages.fetch(message_id);
22
23
  await message.react(emoji);