@zhin.js/plugin-roulette 0.1.14 → 0.1.16

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,80 @@
1
1
  # @zhin.js/plugin-roulette
2
2
 
3
+ ## 0.1.16
4
+
5
+ ### Patch Changes
6
+
7
+ - d80964d: 修复 1.2 发版撞号:`@zhin.js/core` 与 `@zhin.js/agent` 按 minor 升到 1.2.0 时,npm 上早已有同号的旧架构版本(core 1.2.0–1.5.16、agent 1.2.0–1.2.1),`changeset publish` 只提示 already published 就跳过,导致 `zhin.js@1.1.26` 等已发布的包依赖了旧 core / agent,启动时缺少 `CHAT_ROLES`。
8
+
9
+ 本次把 core 发为 1.6.0、agent 发为 1.3.0(npm 上第一个空闲的 minor),并重新发布所有直接依赖它们的包,让依赖版本与 peer 范围指向新版本(`^1.6.0` / `^1.3.0`,不再落进旧架构版本)。
10
+
11
+ - Updated dependencies [d80964d]
12
+ - @zhin.js/core@1.6.0
13
+ - @zhin.js/game-kit@1.1.27
14
+
15
+ ## 0.1.15
16
+
17
+ ### Patch Changes
18
+
19
+ - e1fda87: fix: 按审计待审清单处理(安全、功能、清理)
20
+
21
+ **行为变更(升级前请阅读)**
22
+
23
+ - kernel / core / zhin.js:出站文本中的 `${…}` 不再用 `vm` 求值,只替换 `TemplateContext` 上能解析到值的属性路径(如 `${sender.name}`);表达式、函数调用、未知名字原样保留。整套 vm 沙箱(`evaluate` / `execute` / `compiler` / `getValueWithRuntime`)已移除。
24
+ - kernel / core / zhin.js:移除零引用的遗留导出——`Scheduler`、错误管理器与 `ZhinError` 子类、`compose`、`segment.from/toString`、AI 触发/准入函数、`@zhin.js/core/queue-im-field-contract`、`zhin.js/contexts`。
25
+ - agent:readonly 执行预设不再放行重定向、后台 `&`、进程替换、`find -delete/-exec`、`sed -i`、`sort -o`、`tee`、`xargs`、awk;curl/wget 校验每个 URL 与裸主机并识别更多上传参数;自定义 `execAllowlist` 中的只读命令带写入风险时改走审批。沙箱超时/取消会杀掉进程组或具名容器,默认镜像改为 `node:22-bookworm-slim` + `bash`。移除无生产调用的 `AuditLogger`、`AnomalyDetector`、旧 vision 回合等导出。
26
+ - ai:移除 `storage`、`FileStateCache`、`CostTracker`、`model-name-utils`、`./agent-step-checkpoint` 子路径、`ContextManager` 及旧压缩管线;延迟工具快照改为有界 LRU。
27
+ - 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 接管后不再自行退出。
28
+ - schedule:后台 reconcile 出错不再产生未处理 rejection(新增 `onStoreError`);启动途中 `stop()` 不再遗留定时器。
29
+ - schema:元组校验与 `safeParse`、JSON Schema 一致(空数组不通过,缺省的可选元组为 `undefined`)。
30
+ - client / contract:删除无后端路由的 agent-stream API、未使用的 `definePage` 与旧 PageManager 类型;`@zhin.js/contract` 不再依赖 `@zhin.js/ai`;客户端收到 401 会清除已保存的凭据;安装/更新/卸载 RPC 默认超时 120 秒。
31
+ - a2a:流式响应中途出错写入 SSE error 并结束;未配置 token 的非生产环境只接受本机请求;任务存储有上限与过期;Mailbox 凭据回退与生产环境缺密钥检查修复。
32
+ - speech:`provider: openai` 不再套用 Ollama 的默认 host/model;识别语言改为可配置,不再写死 `zh`。
33
+ - adapter-lark:支持 `encryptKey` 加密事件解密。adapter-github:Device Flow 可取消、带超时并回复失败原因。adapter-wecom / dingtalk:请求加超时并校验 HTTP 状态。adapter-weixin-ilink:输入关闭期间暂停轮询。adapter-milky:SSE 支持 CRLF、缓冲上限与空闲重连。adapter-onebot-events:好友删除通知改为 `notice.friend.decrease`。
34
+ - plugin-group-suite:`teachAllowRegex` 默认关闭,正则安全检查更严格。plugin-qrcode:改为本地生成,回复 data URL 图片。plugin-rss / short-url / link-poster:拒绝解析到内网的地址;rss 修复条目每周重复推送;short-url 的 Console 创建改为真实调用 is.gd。plugin-lottery:按 `historyLimit` 同步。
35
+
36
+ **其余**
37
+
38
+ - host-http:插件市场详情加缓存与包名校验,SSE 回放容忍背压。host-http-contract:新增 `readTextBody()`,九个适配器改用它。
39
+ - pagemanager:页面外壳 importmap 升级到 React 19.2.8 / react-router 7.12.0。console-contract:`definePage` 接受 `description` / `group` / `parent` / `fullWidth`。
40
+ - command:进度提示本地化,匹配不再重复拷贝消息段。runtime:源码监听降级后退避重试原生监听。
41
+ - html-renderer:删除未接线的 `aiTextAsImage`。create-zhin-app / scaffold-wizard:移除不起作用的"全局安装 CLI"与运行时选择提示。
42
+ - 依赖声明清理、发布清单不再携带解析不到的 `src` 目录、移除未使用的 Skill 挂载、README 与示例配置按当前实现更正。
43
+
44
+ - 120e225: 聊天角色(ADR 0056,2026-11-12 修订):zhin 角色 owner / admin / trusted 分四级、只来自授予;发言者的平台身份与机器人自身的平台身份是独立维度,命令、Agent 工具 / 技能、中间件与按钮按三条维度共用一个评估器过滤。升级说明见 docs/migrations/chat-roles.md。
45
+
46
+ - 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` 判断。
47
+ - @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` 删除。
48
+ - @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`,定义时报错并给出替代写法。
49
+ - @zhin.js/command(minor,破坏性):命令会话的发送者改为 `chatRole` / `platform`,不再从 metadata 读角色;`CONVERSATION_MANAGER_PERMIT` 改为 `admin`(平台群主不再自动满足);分发结果 `denied` 带 `denial`(第一条不满足的规则与原因);指令菜单只列出当前发送者在本会话可用的命令。
50
+ - @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`。
51
+ - @zhin.js/feature-kit:`OperationSession.sender` 改为 `chatRole` / `platform`。
52
+ - @zhin.js/im-contract:新增 `PlatformStanding`、`SelfStandingRequest`、`standingFromMemberRole`。
53
+ - @zhin.js/adapter:入站 sender 可带 `platform`;账号管理命令需要聊天角色 `owner`;`EndpointManagement` 新增可选 `inspectSelfStanding`,能力画像新增 `scene.selfStanding`(声明即须实现),`AdapterIndex.selfStanding` / `invalidateSelfStanding` 按会话缓存机器人自身身份。
54
+ - @zhin.js/middleware:入站中间件可声明 `permit`,不满足时跳过该中间件(机器人身份只读缓存)。
55
+ - @zhin.js/tool:定义工具时拒绝已移除的 permit 写法。
56
+ - @zhin.js/ai:注释更新。
57
+ - @zhin.js/console-protocol:`chat-roles.list|grant|revoke`(`iam.manage`);`ConsoleChatRoleSource` 只有 `grant`。
58
+ - @zhin.js/runtime:Host 配置 Schema 删除 `features.selfService.platformAdmins|roles|allowUsers`。
59
+ - @zhin.js/testing:伪造消息与 `PluginTestKit` 用 `sender.chatRole` 声明测试身份。
60
+ - @zhin.js/scaffold-wizard:ICQQ 向导不再写 `master`,完成后提示在 Console 账号「角色」页签或聊天 `角色 授予` 设置 owner。
61
+ - 适配器:配置 Schema 删除 `master` / `trusted`(以及预览版的 `roles`);群管理类工具同时声明发言者条件与机器人条件(如 `platform:admin` + `bot:admin`、`bot-permission:manage_roles`),NapCat / OneBot11 工具不再使用已移除的 `platform(adapter,…)` 写法。
62
+ - 插件:内容审核以 `inbound.bypass`(permit 列表,默认 `owner` 或 `platform:admin`)取代 `masters` / `inbound.bypassMasters`;群管、音乐、日历、地震、B 站、轮盘赌的权限改用 zhin 角色,订阅类命令只认 zhin `admin` / `owner`。
63
+
64
+ - eae4ea8: 官方插件接入分层功能配置(ADR 0050 / 0055):所有带配置 Schema 的官方插件都声明全部四级(全局 / 适配器 / 账号 / 会话),Console 的适配器、账号与会话页面都能开关它们;密钥、调度与全局资源类字段收窄为仅全局。answers 与 group-suite 可按会话覆盖字段并开放群内自助字段(答题超时、科目一开关;欢迎语、排行条数、教学冷却与分页),ledger 的 `reportWhenEmpty` 可按订阅者会话覆盖。主动推送在发送前按目标会话检查开关:提醒(含管理员提醒)、日历授权通知、地震速报、记账日报、彩票推送、B 站开播 / 动态推送、activity-feedback 的状态提示在已停用的账号或会话上不再发送;roulette 的超时扫描在已停用的会话里静默结束对局(不结算、不禁言、不发消息)。`@zhin.js/schema` 新增 `.fieldLevels(levels)` 用于收窄单个字段的层级;`@zhin.js/testing` 的假插件上下文提供 `isEnabledFor` / `configFor`(`feature` 选项可模拟按会话停用与字段覆盖)。
65
+ - c606d51: 平台身份归一(ADR 0056 §1):`@zhin.js/im-contract` 新增 `PlatformStanding`(`standing` 为 `owner` / `admin` / `member` / `guest`,可选平台原生 `roles` 与 `permissions`)及 `normalizePlatformStanding`,入站消息的发送者身份挂在 `sender.platform` 上;能力画像新增 `scene.platformStanding`,声明适配器上报其中哪些字段。适配器不再能通过 `sender.roles` 上报身份:入站时框架只保留发送者的 `id`、`name` 与校验后的 `platform`,`sender.roles` 已删除(聊天角色见 `sender.chatRole`,ADR 0056)。平台身份检查(`platform:admin` 等)、发言门控与参与者标签读 `sender.platform`(平台身份不映射为 zhin 角色),不再读取元数据里的 `senderRole` / `role` / `roles` / `senderPermissions`;`OperationSession.sender.platformRoles` 改为 `platform`。
66
+ - Updated dependencies [53932e5]
67
+ - Updated dependencies [e1fda87]
68
+ - Updated dependencies [a9c7a13]
69
+ - Updated dependencies [120e225]
70
+ - Updated dependencies [63595fc]
71
+ - Updated dependencies [c2bbdcf]
72
+ - Updated dependencies [663473b]
73
+ - Updated dependencies [c606d51]
74
+ - Updated dependencies [1e54b1e]
75
+ - @zhin.js/core@1.2.0
76
+ - @zhin.js/game-kit@1.1.26
77
+
3
78
  ## 0.1.14
4
79
 
5
80
  ### 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/README.md CHANGED
@@ -5,12 +5,13 @@
5
5
  ## 安装
6
6
 
7
7
  ```yaml
8
+ configVersion: 2
8
9
  plugins:
9
10
  game-hub: "@zhin.js/plugin-game-hub"
10
11
  roulette: "@zhin.js/plugin-roulette"
11
12
  database:
12
13
  dialect: sqlite
13
- storage: ./data/zhin.db
14
+ filename: ./data/zhin.db
14
15
  ```
15
16
 
16
17
  没有数据库时对局保存在内存里,重启后丢失。
@@ -43,7 +44,7 @@ database:
43
44
 
44
45
  ## 禁言惩罚
45
46
 
46
- - 按群开关,默认关闭。只有群主、群管理员、机器人主人或受信任用户可以切换;判断的是适配器投影到消息上的规范角色(`owner` / `admin` / `master` / `trusted`),不额外请求平台。
47
+ - 按群开关,默认关闭。只有本会话 zhin 聊天角色 `trusted` 及以上(`owner` / `admin` / `trusted`,ADR 0056)可以切换;平台群主 / 管理员身份不算,需要先被授予 zhin 角色。实际禁言还要求机器人在群里有禁言权限。
47
48
  - 插件不判断平台名称。每次需要时,用消息自带的 `conversation.endpoint`(适配器插件和 Endpoint 能力 id)走 `project(adapterFeatureId).connection(adapter, endpointId)`,再看 `resolveEndpointManagement(endpoint)?.muteGroupMember` 是否存在。存在就能禁言,不存在(或运行时没有 Adapter Feature)就只计分。
48
49
  - 超时判负由 `schedules/deadlines` 每 5 秒检查一次,它拿到的也是同样的能力上下文,所以超时的输家同样会按上面的规则处理。
49
50
  - 平台不支持禁言时无法开启;开启后平台失去这项能力,或禁言被拒绝(例如机器人不是群管理员),这一局照常结算,只是不禁言。
@@ -60,6 +61,10 @@ roulette:
60
61
  muteSeconds: 60 # 开启禁言惩罚的群里输家禁言秒数,10-3600
61
62
  ```
62
63
 
64
+ ## 分层配置(ADR 0050 / 0055)
65
+
66
+ 所有字段只能在全局层修改;启停开关支持适配器、账号与会话四级。在 Console「功能」区可以按适配器、账号或会话(群 / 私聊)单独停用;开启 `features.selfService.enabled` 后,群里有 `admin` 角色(默认含群主 / 管理员)的人也可以用 `功能 关闭 roulette` 关闭本群。上级停用后下级锁定,不能再开启。停用后该群的命令和「开枪」都不再响应;进行中的对局到时由超时扫描静默结束(记为取消,不结算、不禁言、不发消息)。
67
+
63
68
  ## 开发
64
69
 
65
70
  ```bash
@@ -0,0 +1,19 @@
1
+ import { gameCommandFeedback, gamePlayerFromInput, replyGameOperation } from '@zhin.js/game-kit';
2
+ import { defineCommand } from 'zhin.js/command';
3
+ import { resolveRouletteFlow } from '../../../src/runtime.js';
4
+ import { getRouletteHelp, normalizeRouletteAction } from '../../../src/roulette-actions.js';
5
+ import { runRouletteCommand } from '../../../src/roulette-command.js';
6
+
7
+ export default defineCommand({
8
+ description: '俄罗斯轮盘:多人轮流开枪,中弹者输', descriptionI18n: { en: "Russian roulette: take turns; the player hit loses" },
9
+ params: { action: { type: 'string', default: '' } },
10
+ async execute(context) {
11
+ const action = String(context.params.action ?? '');
12
+ const normalized = normalizeRouletteAction(action);
13
+ if (normalized === 'help') return getRouletteHelp(context);
14
+ if (!normalized) return gameCommandFeedback(context, 'unknown', action) + '\n\n' + getRouletteHelp(context);
15
+ const flow = resolveRouletteFlow(context), player = gamePlayerFromInput(context.input, context);
16
+ await replyGameOperation({ session: flow.services.sessions, player, reply: context.session?.reply,
17
+ run: () => runRouletteCommand(context, context.input, action) });
18
+ },
19
+ });
@@ -1,7 +1,7 @@
1
1
  import { outboundHostToken } from 'zhin.js';
2
- import { sendGameSessionMessage } from '@zhin.js/game-kit';
2
+ import { gameTargetFromKey, sendGameSessionMessage } from '@zhin.js/game-kit';
3
3
  import { expireOverdueSessions } from './game-flow.js';
4
- import { resolveRouletteFlow } from './runtime.js';
4
+ import { resolveRouletteFlow, rouletteFeatureGateStore } from './runtime.js';
5
5
  /** Turn and lobby deadlines are checked every five seconds. */
6
6
  export const DEADLINE_CRON = '*/5 * * * * *';
7
7
  /**
@@ -12,10 +12,22 @@ export const DEADLINE_CRON = '*/5 * * * * *';
12
12
  export async function runDeadlineSweep(context, now) {
13
13
  const flow = resolveRouletteFlow(context);
14
14
  const outbound = readOutbound(context);
15
+ const enabledFor = readFeatureGate(context);
15
16
  await expireOverdueSessions(flow, now, (notice) => {
16
17
  if (outbound)
17
18
  return announce(outbound, notice);
18
- });
19
+ }, enabledFor && ((session) => {
20
+ const target = gameTargetFromKey(session.channel_key);
21
+ return !target || enabledFor.isEnabledFor(target);
22
+ }));
23
+ }
24
+ function readFeatureGate(context) {
25
+ try {
26
+ return context.use(rouletteFeatureGateStore);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
19
31
  }
20
32
  function readOutbound(context) {
21
33
  try {
@@ -21,5 +21,5 @@ export interface ExpiredSessionNotice {
21
21
  }
22
22
  export declare function runRouletteAction(flow: RouletteFlow, actor: RouletteActor, action: RouletteCommandAction): Promise<string>;
23
23
  /** Called by the deadline schedule; each returned notice still has to be delivered. */
24
- export declare function expireOverdueSessions(flow: RouletteFlow, now: number, onNotice?: (notice: ExpiredSessionNotice) => Promise<void> | void): Promise<readonly ExpiredSessionNotice[]>;
24
+ export declare function expireOverdueSessions(flow: RouletteFlow, now: number, onNotice?: (notice: ExpiredSessionNotice) => Promise<void> | void, isEnabled?: (session: RouletteSessionRow) => boolean): Promise<readonly ExpiredSessionNotice[]>;
25
25
  export declare function conversationOfSession(session: RouletteSessionRow): PenaltyConversation;
package/lib/game-flow.js CHANGED
@@ -5,7 +5,8 @@ import { getRouletteHelp } from './roulette-actions.js';
5
5
  import { playerFromMessage, stateOf, } from './session-service.js';
6
6
  import { describeAbort, describeClick, describeEnding, describeLobby, describeRoundStart, describeStatus, } from './view.js';
7
7
  const DEADLINE_ACTOR = 'deadline';
8
- const MANAGER_ROLES = ['master', 'trusted', 'owner', 'admin'];
8
+ /** zhin chat role `trusted` or higher (ADR 0056; platform standing does not count). */
9
+ const MANAGER_ROLES = ['trusted'];
9
10
  function noGame(message) { return messages(message.locale, 'noGame') + gameCommandHint(message, 'roulette', 'open'); }
10
11
  export async function runRouletteAction(flow, actor, action) {
11
12
  return flow.services.sessions.runInScope({ scope: channelKey(actor.message), run: async () => {
@@ -31,12 +32,18 @@ export async function runRouletteAction(flow, actor, action) {
31
32
  } });
32
33
  }
33
34
  /** Called by the deadline schedule; each returned notice still has to be delivered. */
34
- export async function expireOverdueSessions(flow, now, onNotice) {
35
+ export async function expireOverdueSessions(flow, now, onNotice, isEnabled) {
35
36
  const overdue = await flow.services.sessions.listOverdue(now);
36
37
  const notices = [];
37
38
  for (const session of overdue) {
38
39
  try {
39
40
  await flow.services.sessions.runInScope({ scope: session.channel_key, run: async () => {
41
+ // Switched off for this conversation (ADR 0050 / 0055): end the game silently, without a
42
+ // result, records, mute penalty or announcement.
43
+ if (isEnabled && !isEnabled(session)) {
44
+ await abortSilently(flow, session);
45
+ return;
46
+ }
40
47
  const text = await expireSession(flow, session);
41
48
  if (!text)
42
49
  return;
@@ -119,6 +126,16 @@ async function describeResult(flow, action, result, message) {
119
126
  }
120
127
  return describeLobby(state, flow.config, presentation);
121
128
  }
129
+ async function abortSilently(flow, session) {
130
+ try {
131
+ await flow.services.sessions.applyAction(session, DEADLINE_ACTOR, { type: 'cancel' }, flow.config);
132
+ }
133
+ catch (error) {
134
+ if (error instanceof SessionRevisionConflictError)
135
+ return;
136
+ throw error;
137
+ }
138
+ }
122
139
  async function expireSession(flow, session) {
123
140
  // Read everything that can fail before the state transition is committed: once the
124
141
  // session is stored as finished it is no longer overdue and would never be retried.
@@ -245,7 +262,7 @@ const messages = createMessages({
245
262
  text7: { 'zh-CN': "🔇 {p0} 被禁言 {p1} 秒。", en: "🔇 {p0} was muted for {p1} seconds." },
246
263
  text8: { 'zh-CN': "(禁言没有成功,可能是机器人没有群管理权限;本局只计分。)", en: "(Muting failed, possibly because the bot lacks group management permission. Only scores were recorded.)" },
247
264
  text9: { 'zh-CN': "禁言惩罚只能在群聊里设置。", en: "Mute penalties can only be configured in a group chat." },
248
- text10: { 'zh-CN': "只有群主、群管理员、机器人主人或受信任用户可以修改禁言惩罚。", en: "Only the group owner, group admin, bot owner or a trusted user may change mute penalties." },
265
+ text10: { 'zh-CN': "只有本会话 zhin 角色 trusted 及以上(owner / admin / trusted)的用户可以修改禁言惩罚。", en: "Only users with the zhin role trusted or higher (owner / admin / trusted) in this conversation may change mute penalties." },
249
266
  text11: { 'zh-CN': "已关闭禁言惩罚,本群轮盘只计分。", en: "Mute penalties are disabled. This group now records scores only." },
250
267
  text12: { 'zh-CN': "当前平台不支持禁言,禁言惩罚没有开启;本群轮盘只计分。", en: "This platform does not support muting. Mute penalties remain disabled; only scores are recorded." },
251
268
  text13: { 'zh-CN': "已开启禁言惩罚:每局输家会被禁言 {p0} 秒(需要机器人有群管理权限)。", en: "Mute penalties enabled: each loser is muted for {p0} seconds (the bot needs group management permission)." },
package/lib/runtime.d.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  import type { Locale } from 'zhin.js/i18n';
2
- import { type Token } from 'zhin.js';
2
+ import { type DeliveryTarget, type Token } from 'zhin.js';
3
3
  import type { RouletteFlow } from './game-flow.js';
4
4
  import { type AdapterProjectionContext } from './mute-penalty.js';
5
5
  import type { RouletteServices } from './session-service.js';
6
6
  /** Owner-scoped services consumed by discovered commands, middleware and the deadline job. */
7
7
  export declare const rouletteServicesStore: import("zhin.js").PluginStore<RouletteServices, unknown>;
8
8
  export declare const rouletteServicesToken: import("zhin.js").PluginStore<RouletteServices, unknown>;
9
+ /**
10
+ * Whether roulette is enabled for one game conversation (ADR 0050 / 0055). The deadline sweep is
11
+ * not a message, so the dispatch gate does not see it; the sweep asks before announcing a result.
12
+ */
13
+ export declare const rouletteFeatureGateStore: import("zhin.js").PluginStore<RouletteFeatureGate, unknown>;
14
+ export interface RouletteFeatureGate {
15
+ isEnabledFor(target: DeliveryTarget): boolean;
16
+ }
9
17
  /** A command, middleware or schedule capability context. */
10
18
  export interface RouletteCapabilityContext extends AdapterProjectionContext {
11
19
  readonly locale?: Locale;
@@ -14,5 +22,5 @@ export interface RouletteCapabilityContext extends AdapterProjectionContext {
14
22
  readonly config?: unknown;
15
23
  }
16
24
  export declare function resolveRouletteFlow(context: RouletteCapabilityContext): RouletteFlow;
17
- /** Framework roles (master / trusted / user) of whoever sent the message. */
25
+ /** Chat roles (ADR 0056, expanded: owner → owner / admin / trusted) of whoever sent the message. */
18
26
  export declare function senderRolesOf(input: unknown): readonly string[];
package/lib/runtime.js CHANGED
@@ -4,6 +4,11 @@ import { resolveMutePenalty } from './mute-penalty.js';
4
4
  /** Owner-scoped services consumed by discovered commands, middleware and the deadline job. */
5
5
  export const rouletteServicesStore = definePluginStore('zhin.game.roulette.services');
6
6
  export const rouletteServicesToken = rouletteServicesStore;
7
+ /**
8
+ * Whether roulette is enabled for one game conversation (ADR 0050 / 0055). The deadline sweep is
9
+ * not a message, so the dispatch gate does not see it; the sweep asks before announcing a result.
10
+ */
11
+ export const rouletteFeatureGateStore = definePluginStore('zhin.game.roulette.feature-gate');
7
12
  export function resolveRouletteFlow(context) {
8
13
  return {
9
14
  services: rouletteServicesStore.use(context),
@@ -11,15 +16,15 @@ export function resolveRouletteFlow(context) {
11
16
  penalty: resolveMutePenalty(context),
12
17
  };
13
18
  }
14
- /** Framework roles (master / trusted / user) of whoever sent the message. */
19
+ const CHAT_ROLE_CHAIN = ['owner', 'admin', 'trusted'];
20
+ /** Chat roles (ADR 0056, expanded: owner → owner / admin / trusted) of whoever sent the message. */
15
21
  export function senderRolesOf(input) {
16
22
  if (!input || typeof input !== 'object')
17
23
  return [];
18
24
  const sender = input.sender;
19
25
  if (!sender || typeof sender !== 'object')
20
26
  return [];
21
- const roles = sender.roles;
22
- if (!Array.isArray(roles))
23
- return [];
24
- return roles.filter((role) => typeof role === 'string');
27
+ const role = sender.chatRole;
28
+ const index = CHAT_ROLE_CHAIN.indexOf(role);
29
+ return index < 0 ? [] : CHAT_ROLE_CHAIN.slice(index);
25
30
  }
@@ -0,0 +1,22 @@
1
+ import { defineGameCommandAliasMiddleware, gamePlayerFromInput, replyGameOperation } from '@zhin.js/game-kit';
2
+ import { normalizeRouletteAction, getRouletteHelp } from '../../src/roulette-actions.js';
3
+ import { resolveRouletteFlow } from '../../src/runtime.js';
4
+ import { runRouletteCommand } from '../../src/roulette-command.js';
5
+
6
+ /** `轮盘 加入` / `/轮盘赌 开枪` / `roulette start` route to the same logic as the command. */
7
+ export default defineGameCommandAliasMiddleware({
8
+ aliases: ['轮盘', '轮盘赌', 'roulette'],
9
+ async run(action, input, context) {
10
+ const normalized = normalizeRouletteAction(action);
11
+ if (!normalized) return false;
12
+ if (normalized === 'help') {
13
+ await context.input.$reply(getRouletteHelp({ locale: context.input.locale,
14
+ formatCommand: path => context.input.formatCommand?.(path, context.owner.id) }));
15
+ return true;
16
+ }
17
+ const flow = resolveRouletteFlow(context), player = gamePlayerFromInput(input);
18
+ await replyGameOperation({ session: flow.services.sessions, player, reply: content => context.input.$reply(content),
19
+ run: () => runRouletteCommand(context, input, action) });
20
+ return true;
21
+ },
22
+ });
@@ -0,0 +1,32 @@
1
+ import type { Message } from '@zhin.js/core/runtime';
2
+ import { channelKey, gamePlayerFromInput, replyGameOperation } from '@zhin.js/game-kit';
3
+ import { defineMiddleware } from 'zhin.js/middleware';
4
+ import { runRouletteCommand } from '../../src/roulette-command.js';
5
+ import { rouletteServicesToken } from '../../src/runtime.js';
6
+
7
+ const FIRE_WORDS: readonly string[] = ['开枪', '扣动扳机'];
8
+
9
+ /**
10
+ * A bare 「开枪」 fires only for the player whose turn it is in this group,
11
+ * so the word stays ordinary chat everywhere else.
12
+ */
13
+ export default defineMiddleware<Message>({
14
+ target: 'inbound',
15
+ async handle(context, next) {
16
+ if (!context.input.sender?.id) { await next(); return; }
17
+ const text = context.input.content?.trim() ?? '';
18
+ if (!FIRE_WORDS.includes(text)) {
19
+ await next();
20
+ return;
21
+ }
22
+ const message = gamePlayerFromInput(context.input);
23
+ const services = context.use(rouletteServicesToken);
24
+ const session = await services.sessions.getActiveByChannel(channelKey(message));
25
+ if (!session || session.turn !== message.sender.id) {
26
+ await next();
27
+ return;
28
+ }
29
+ await replyGameOperation({ session: services.sessions, player: message, reply: content => context.input.$reply(content),
30
+ run: () => runRouletteCommand(context, context.input, 'fire') });
31
+ },
32
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/plugin-roulette",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "Zhin.js 俄罗斯轮盘 — 多人轮流开枪,可按群开启禁言惩罚 (Plugin Runtime)",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -13,12 +13,13 @@
13
13
  "./package.json": "./package.json"
14
14
  },
15
15
  "files": [
16
- "lib",
17
16
  "plugin.js",
18
17
  "schema.json",
19
- "commands/**/*.js",
20
- "middlewares/**/*.js",
21
- "schedules/**/*.js",
18
+ "commands",
19
+ "middlewares",
20
+ "schedules",
21
+ "src",
22
+ "lib",
22
23
  "README.md",
23
24
  "CHANGELOG.md"
24
25
  ],
@@ -30,15 +31,15 @@
30
31
  ],
31
32
  "license": "MIT",
32
33
  "dependencies": {
33
- "@zhin.js/core": "1.1.60",
34
- "@zhin.js/game-kit": "1.1.25"
34
+ "@zhin.js/core": "1.6.0",
35
+ "@zhin.js/game-kit": "1.1.27"
35
36
  },
36
37
  "devDependencies": {
37
38
  "typescript": "^6.0.3",
38
39
  "vitest": "^4.1.10",
39
- "@zhin.js/schedule-feature": "1.1.15",
40
- "@zhin.js/testing": "1.0.9",
41
- "zhin.js": "1.1.25"
40
+ "@zhin.js/schedule-feature": "1.1.16",
41
+ "@zhin.js/testing": "1.0.11",
42
+ "zhin.js": "1.1.27"
42
43
  },
43
44
  "repository": {
44
45
  "type": "git",
@@ -79,10 +80,10 @@
79
80
  "plugins": []
80
81
  },
81
82
  "peerDependencies": {
82
- "@zhin.js/command": "^1.1.17",
83
- "@zhin.js/middleware": "^1.1.16",
84
- "zhin.js": "^1.1.25",
85
- "@zhin.js/schedule-feature": "^1.1.15"
83
+ "@zhin.js/command": "^1.2.1",
84
+ "@zhin.js/middleware": "^1.1.17",
85
+ "zhin.js": "^1.1.27",
86
+ "@zhin.js/schedule-feature": "^1.1.16"
86
87
  },
87
88
  "peerDependenciesMeta": {
88
89
  "@zhin.js/command": {
@@ -98,6 +99,6 @@
98
99
  "scripts": {
99
100
  "build": "tsc",
100
101
  "clean": "rimraf lib",
101
- "test": "NODE_OPTIONS=--experimental-strip-types vitest run --root ../../.. plugins/games/roulette/tests"
102
+ "test": "vitest run --root ../../.. plugins/games/roulette/tests"
102
103
  }
103
104
  }
package/plugin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
2
  import { defineGamePlugin } from '@zhin.js/game-kit';
3
3
  import { ROULETTE_TABLES, defineHostTables } from "./lib/models.js";
4
- import { rouletteServicesToken } from "./lib/runtime.js";
4
+ import { rouletteFeatureGateStore, rouletteServicesToken } from "./lib/runtime.js";
5
5
  import { createServices, } from "./lib/session-service.js";
6
6
  /**
7
7
  * Plugin Runtime wiring:
@@ -40,4 +40,8 @@ export default defineGamePlugin({
40
40
  createServices: (database) => createServices(database),
41
41
  session: (services) => services.sessions,
42
42
  stale: false,
43
+ setup(context) {
44
+ // ADR 0050 / 0055: the deadline sweep checks the game conversation's switch before announcing.
45
+ rouletteFeatureGateStore.provide(context, { isEnabledFor: target => context.isEnabledFor({ conversation: target }) });
46
+ },
43
47
  });
@@ -0,0 +1,8 @@
1
+ import { defineSchedule } from '@zhin.js/schedule-feature';
2
+ import { DEADLINE_CRON, runDeadlineSweep } from '../../src/deadline-job.js';
3
+
4
+ export default defineSchedule({
5
+ cron: DEADLINE_CRON,
6
+ description: '结束超时未开枪的回合和无人开始的房间',
7
+ execute: (context) => runDeadlineSweep(context, Date.now()),
8
+ });
package/schema.json CHANGED
@@ -2,41 +2,74 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "type": "object",
4
4
  "additionalProperties": false,
5
+ "x-zhin-config": {
6
+ "levels": [
7
+ "global",
8
+ "adapter",
9
+ "endpoint",
10
+ "conversation"
11
+ ]
12
+ },
5
13
  "properties": {
6
14
  "chambers": {
7
15
  "type": "integer",
8
16
  "minimum": 2,
9
17
  "maximum": 12,
10
18
  "default": 6,
11
- "description": "弹巢数量,其中一发是实弹"
19
+ "description": "弹巢数量,其中一发是实弹",
20
+ "x-zhin-config": {
21
+ "levels": [
22
+ "global"
23
+ ]
24
+ }
12
25
  },
13
26
  "maxPlayers": {
14
27
  "type": "integer",
15
28
  "minimum": 2,
16
29
  "maximum": 10,
17
30
  "default": 6,
18
- "description": "单局最多玩家数"
31
+ "description": "单局最多玩家数",
32
+ "x-zhin-config": {
33
+ "levels": [
34
+ "global"
35
+ ]
36
+ }
19
37
  },
20
38
  "turnTimeoutSeconds": {
21
39
  "type": "integer",
22
40
  "minimum": 10,
23
41
  "maximum": 600,
24
42
  "default": 60,
25
- "description": "轮到的玩家超过这个秒数不开枪,判负"
43
+ "description": "轮到的玩家超过这个秒数不开枪,判负",
44
+ "x-zhin-config": {
45
+ "levels": [
46
+ "global"
47
+ ]
48
+ }
26
49
  },
27
50
  "lobbyTimeoutSeconds": {
28
51
  "type": "integer",
29
52
  "minimum": 30,
30
53
  "maximum": 3600,
31
54
  "default": 300,
32
- "description": "开局后超过这个秒数仍未开始,自动解散"
55
+ "description": "开局后超过这个秒数仍未开始,自动解散",
56
+ "x-zhin-config": {
57
+ "levels": [
58
+ "global"
59
+ ]
60
+ }
33
61
  },
34
62
  "muteSeconds": {
35
63
  "type": "integer",
36
64
  "minimum": 10,
37
65
  "maximum": 3600,
38
66
  "default": 60,
39
- "description": "开启禁言惩罚的群里,输家被禁言的秒数(每个群默认关闭)"
67
+ "description": "开启禁言惩罚的群里,输家被禁言的秒数(每个群默认关闭)",
68
+ "x-zhin-config": {
69
+ "levels": [
70
+ "global"
71
+ ]
72
+ }
40
73
  }
41
74
  }
42
75
  }
package/src/config.ts ADDED
@@ -0,0 +1,46 @@
1
+ /** Plugin instance configuration (`schema.json`), with defaults and safe bounds. */
2
+ export interface RouletteConfig {
3
+ /** Chambers in the cylinder; one holds the bullet. */
4
+ readonly chambers: number;
5
+ readonly maxPlayers: number;
6
+ /** The player on turn loses when they do not fire within this time. */
7
+ readonly turnTimeoutSeconds: number;
8
+ /** A lobby that never starts is dissolved after this time. */
9
+ readonly lobbyTimeoutSeconds: number;
10
+ /** Mute length for the loser, used only in groups that enabled the mute penalty. */
11
+ readonly muteSeconds: number;
12
+ }
13
+
14
+ interface IntegerBounds {
15
+ readonly fallback: number;
16
+ readonly min: number;
17
+ readonly max: number;
18
+ }
19
+
20
+ const CONFIG_BOUNDS: Readonly<Record<keyof RouletteConfig, IntegerBounds>> = {
21
+ chambers: { fallback: 6, min: 2, max: 12 },
22
+ maxPlayers: { fallback: 6, min: 2, max: 10 },
23
+ turnTimeoutSeconds: { fallback: 60, min: 10, max: 600 },
24
+ lobbyTimeoutSeconds: { fallback: 300, min: 30, max: 3600 },
25
+ muteSeconds: { fallback: 60, min: 10, max: 3600 },
26
+ };
27
+
28
+ export const DEFAULT_ROULETTE_CONFIG: RouletteConfig = resolveRouletteConfig(undefined);
29
+
30
+ export function resolveRouletteConfig(raw: unknown): RouletteConfig {
31
+ const source = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
32
+ return Object.freeze({
33
+ chambers: readInteger(source.chambers, CONFIG_BOUNDS.chambers),
34
+ maxPlayers: readInteger(source.maxPlayers, CONFIG_BOUNDS.maxPlayers),
35
+ turnTimeoutSeconds: readInteger(source.turnTimeoutSeconds, CONFIG_BOUNDS.turnTimeoutSeconds),
36
+ lobbyTimeoutSeconds: readInteger(source.lobbyTimeoutSeconds, CONFIG_BOUNDS.lobbyTimeoutSeconds),
37
+ muteSeconds: readInteger(source.muteSeconds, CONFIG_BOUNDS.muteSeconds),
38
+ });
39
+ }
40
+
41
+ function readInteger(value: unknown, bounds: IntegerBounds): number {
42
+ if (typeof value !== 'number' || !Number.isInteger(value)) return bounds.fallback;
43
+ if (value < bounds.min) return bounds.min;
44
+ if (value > bounds.max) return bounds.max;
45
+ return value;
46
+ }