koishi-plugin-prism 0.1.41 → 0.2.0

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/README.md CHANGED
@@ -22,7 +22,7 @@
22
22
  | 配置项 | 类型 | 默认值 | 描述 |
23
23
  | :--- | :---: | :---: | :--- |
24
24
  | `baseUrl` | `string` | - | **必填**。PRiSM Next Server 的访问基准 URL(如 `https://prism-mmw.neri.moe`)。 |
25
- | `shopCode` | `string` | - | 统一平台的店铺公开编号;单店兼容部署留空。 |
25
+ | `shopCode` | `string` | - | **必填**。统一平台的店铺公开编号。 |
26
26
  | `integrationToken` | `string` | - | **必填**。从 PRiSM 网页后台生成的 Integration API 令牌。 |
27
27
  | `autoRegister` | `boolean` | `true` | 当玩家未注册时,是否在首次操作(如入场/查钱包)时自动在 PRiSM 中创建新玩家。 |
28
28
  | `loginPricingConfigIds` | `string[]` | `[]` | 默认入场计费规则 ID 列表。 |
@@ -34,14 +34,16 @@
34
34
  | `enableStaffCommands` | `boolean` | `false` | 是否开启管理员快捷指令。 |
35
35
  | `staffUserIds` | `string[]` | `[]` | 允许执行管理员快捷指令的平台身份(如 `onebot:114514`、`telegram:114514`)白名单。空列表不授予目标用户操作权限。 |
36
36
  | `powerCommandsAdminOnly` | `boolean` | `false` | 关机是否仅允许 `staffUserIds` 中的管理员使用。`/on` 始终只允许已入场玩家使用。 |
37
- | `playerCommands` | `"all" \| "readonly"` | `"all"` | 玩家可用的命令。`readonly` 时玩家只能绑定身份(`bind`)、查询(`wallet`、`billing`、`history`、`items`、`list`、`show`、`麻将列表`、`versions`、`api测速`)和兑换(`redeem`);入场、结账、上下桌和设备操作(`login`/`入场`、`logout`、`mahjong`/`上桌`/`下桌`、`lock`、`on`、`off`、`coin`、`scan`)只有 `staffUserIds` 中的管理员能用,包括替其他玩家操作。适合让 Bot 只负责身份绑定与查询、入场结账都在网页或 App Clip 里完成的店。 |
37
+ | `playerCommands` | `"all" \| "readonly"` | `"all"` | 玩家可用的命令。`readonly` 时玩家只能绑定身份(`bind`)、查询(`wallet`、`billing`、`history`、`items`、`list`、`show`、`麻将列表`、`versions`、`api测速`、`ws测速`)和兑换(`redeem`);入场、结账、上下桌和设备操作(`login`/`入场`、`logout`、`mahjong`/`上桌`/`下桌`、`lock`、`on`、`off`、`coin`、`scan`)只有 `staffUserIds` 中的管理员能用,包括替其他玩家操作。适合让 Bot 只负责身份绑定与查询、入场结账都在网页或 App Clip 里完成的店。 |
38
38
  | `readOnlyNotice` | `string` | `请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作` | 只读模式下玩家使用受限命令时 Bot 的回复。 |
39
39
  | `logoutNotifyUserIds` | `string[]` | `[]` | 结账成功后额外私聊完整账单的平台身份。通知收件人为该列表与 `staffUserIds` 的去重并集。 |
40
+ | `idleNotifyChannelIds` | `string[]` | `[]` | 闲置自动关机的提醒发到哪里。群写 `onebot:群号`,私聊写 `onebot:private:QQ号`(Koishi 的 `平台:频道` 格式)。留空则不提醒。 |
41
+ | `idleReminderMinutes` | `number` | `5` | 自动关机前几分钟提醒,0 为不提醒。 |
40
42
  | `mahjongTableConfigs` | `object[]` | `[]` | 推荐的结构化麻将桌列表。每项填写显示名称、命令别名列表与计费方案 ID 列表。显示名称同时作为内部桌位锚点与 session 标签。 |
41
43
 
42
44
  ### 统一平台
43
45
 
44
- 配置 `baseUrl`、`shopCode` 和本店的 Integration 令牌后,插件调用 `/api/v1/shops/:shopCode/integration`;单店兼容部署调用 `/api/v1/integration`。
46
+ 配置 `baseUrl`、`shopCode` 和本店的 Integration 令牌后,插件与 PRiSM 只保持**一条 WebSocket 连接**(`/api/v1/shops/:shopCode/integration/ws`),所有命令都作为请求帧走这条连接,平台也通过它推送闲置关机提醒。连接断开时命令直接回复「操作失败,暂时连不上服务器。」,不排队、不自动重发;插件在后台自动重连。需要 Koishi 的 `http` 服务(`ctx.http.ws`)。不再支持不填 `shopCode` 的单店兼容部署。
45
47
 
46
48
  玩家在网页取得验证码后,向任意已接入的店铺 Bot 发送 `bind 验证码`(旧命令 `prism.bind` 仍可用)。店家可以在 PRiSM「设置 → Bot 与接入」改写玩家看到的绑定提示。所有命令从消息的 `session.platform` 和 `session.userId` 读取身份,发送 `{ code, provider, subject }`,不接受手填或代填身份;`provider` 配置已移除。例如同一实例的 OneBot 和 Telegram 消息分别使用 `onebot:114514` 和 `telegram:114514`。群/私聊过滤交给 Koishi。网页账号可以跨店使用,平台验证、玩家和余额按店铺隔离;同一网页账号追加平台绑定时复用同一个玩家。
47
49
 
@@ -86,13 +88,15 @@ pricingConfigIds: [pricing-mahjong-a]
86
88
  * `lock` - 为默认 TTLock 门锁生成一个 8 位随机临时密码(有效期 3 分钟)并回复密码。
87
89
  * `on <deviceRef>` - 使用后台设备名称、别名或 `all` 请求启动电源;仅已通过 `login`/`入场` 开启活跃计费 session 的玩家可用。不接受 Home Assistant entity ID,成功回复使用后端返回的设备名称。
88
90
  * `off <deviceRef>` - 使用后台设备名称、别名或 `all` 请求关闭电源;与 `/on` 一样仅允许已入场玩家使用,不接受 Home Assistant entity ID,`all` 显示为“所有设备”。
91
+ * `keep <设备名或别名>` - 延迟闲置设备的自动关机。只对开着的设备有效,永远不会把设备开起来;需要玩家已入场。只读模式(`readonly`)下玩家也能用。
89
92
  * `coin <设备名或别名> [count]` - 请求向后台配置的 Hinata IO 设备投币;需要玩家已入场。
90
93
  * `scan <设备名或别名>` - 使用当前玩家后台绑定的 Aime 卡向设备刷卡,不在群聊中输入或显示卡号。
91
94
  * `redeem <code>` - 兑换礼物码。
92
95
  * `mahjong <tableId>` / `上桌 [tableId]` - 加入指定麻将桌;`/上桌` 未提供桌号时会引导查看 `/麻将列表`。仅允许已通过 `login`/`入场` 开启默认入场会话的玩家使用。支持在桌位未满但已开局时进行中途补位(即直接开始计费上桌)。
93
96
  * `下桌` - 自动离开当前所在麻将桌,下桌后会停止计费,并显示该麻将桌的剩余游玩人数。
94
97
  * `麻将列表` - 查看已配置机器的桌名、命令别名,以及空闲、等位或游玩中状态。
95
- * `api测速 [次数]` - 连续查询自己的钱包,显示 Bot 到 PRiSM API 的最小、平均与最大延迟(默认 3 次,最多 10 次)。
98
+ * `api测速 [次数]` - 走 HTTP 连续查询自己的钱包:首次(含建立连接)单独列出,之后显示最小、平均与最大延迟,并给出服务端处理时间和经过的 Cloudflare 节点(默认 5 次,最多 10 次)。
99
+ * `ws测速 [次数]` - 走 Bot 的 WebSocket 连接:心跳往返(纯网络)和同样的钱包查询,并给出服务端处理时间(默认 5 次,最多 10 次)。两者对比可以看出延迟在网络还是在服务端,以及长连接能省下多少。
96
100
  * `versions` - 显示当前 Bot npm 包版本和后端发布版本;后端不可达时仍会显示 Bot 版本。
97
101
 
98
102
  Bot 版本直接读取本 npm 包的 `package.json`,后端版本读取无需认证的 `GET /version`。插件发布遵循 SemVer;修复使用 patch、兼容新增功能使用 minor、不兼容改动使用 major,发布前通过 `npm version <patch|minor|major>` 自动更新包版本。
@@ -123,17 +127,18 @@ Bot 版本直接读取本 npm 包的 `package.json`,后端版本读取无需
123
127
 
124
128
  ### 提交检查
125
129
 
126
- `main` 和 PR 均运行独立的 GitHub Actions `checks`:Bun 类型检查、Bot 命令回归测试与 TypeScript 编译。麻将上桌/下桌与多平台退场去重使用模拟适配器测试,不对线上店铺写入。代码合并后仍需发布新 npm 版本,并确认运行中的 Koishi 实例已经升级;只有合并源码不会自动更新 Bot。
130
+ `main` 和 PR 均运行独立的 GitHub Actions `checks`:Bun 类型检查、Bot 命令回归测试与 TypeScript 编译。麻将上桌/下桌与多平台退场去重使用模拟适配器测试,不对线上店铺写入。发布新 npm 版本后,还要确认运行中的 Koishi 实例已经升级。
127
131
 
128
132
  ### CI 自动发布
129
133
 
130
- 发布使用 GitHub Actions 的 npm Trusted Publishing。修改版本后推送带 `v` 前缀且与 `package.json` 一致的标签即可自动测试、构建并发布:
134
+ 发布使用 GitHub Actions 的 npm Trusted Publishing。合并到 `main` 时,如果 `package.json` 的版本在 npm 上还不存在,就自动测试、构建、发布,并打上 `v<版本>` 标签;版本没变则跳过。所以发版只需在 PR 里改版本号:
131
135
 
132
136
  ```bash
133
- npm version patch
134
- git push origin main --follow-tags
137
+ npm version minor --no-git-tag-version
135
138
  ```
136
139
 
140
+ 也可以推送与 `package.json` 一致的 `v` 标签,或在 Actions 里手动运行 `Publish to npm`。
141
+
137
142
  首次使用前,在 npm 包设置的 Trusted Publisher 中选择 GitHub Actions,填写仓库 `nerimoe/koishi-plugin-prism` 和工作流文件名 `publish.yml`,并允许 `npm publish`。
138
143
 
139
144
  ## 📄 开源协议
@@ -152,6 +157,10 @@ git push origin main --follow-tags
152
157
 
153
158
  支持统一平台店铺 API、平台身份 绑定和麻将查人统计;兼容新版入场标签,修复已入场玩家无法通过 Bot 上桌的问题。
154
159
 
160
+ ### 0.2.0
161
+
162
+ 与 PRiSM 改为一条 WebSocket 连接通信,不再发 HTTP 请求;连接断开时命令直接失败。移除单店兼容模式(`shopCode` 必填)和插件自己的无人自动关机(`powerOffInterval`),改由 PRiSM 后台的「闲置自动关机」负责;新增 `idleNotifyChannelIds`、`idleReminderMinutes` 接收关机提醒,以及 `keep` 命令延迟关机。需要配套支持 `/integration/ws` 的 PRiSM。
163
+
155
164
  ### 0.1.41
156
165
 
157
166
  移除手填平台标识;使用消息适配器身份完成绑定、计费和设备指令。支持同实例多适配器,绑定采用 `provider:subject`,员工权限和账单通知按平台隔离。需配套新版 PRiSM 的 `platform-binding` 接口;旧身份由店主主动转换。
package/lib/index.d.ts CHANGED
@@ -33,7 +33,10 @@ export type PrismKoishiPluginConfig = {
33
33
  logoutNotifyUserIds?: string[];
34
34
  mahjongTableConfigs?: MahjongTableConfigInput[];
35
35
  mahjongTableSize?: number;
36
- powerOffInterval?: number;
36
+ /** Channels (`platform:channelId`) told before an idle power-off. */
37
+ idleNotifyChannelIds?: string[];
38
+ /** How many minutes before an idle power-off to tell them; 0 for never. */
39
+ idleReminderMinutes?: number;
37
40
  /**
38
41
  * Used by /list to resolve player display names from the chat platform.
39
42
  * For Koishi, this maps an adapter subject and provider to a nickname (e.g. the
@@ -47,7 +50,31 @@ export type PrismKoishiPluginConfig = {
47
50
  baseUrl?: string;
48
51
  integrationToken?: string;
49
52
  client?: any;
53
+ /** Opens the platform connection; defaults to Koishi's `ctx.http.ws`. Mainly for tests. */
54
+ socket?: SocketFactory;
55
+ /** Plain HTTP POST, used only by `api测速`; defaults to Koishi's `ctx.http`. Mainly for tests. */
56
+ httpPost?: HttpPost;
50
57
  };
58
+ /** A plain HTTP POST answering with its status, headers and decoded body. */
59
+ export type HttpPost = (url: string, headers: Record<string, string>, body: unknown) => Promise<{
60
+ status: number;
61
+ headers: Headers;
62
+ data: any;
63
+ }>;
64
+ /** One timed call: the whole round trip, the server's own share when it says, and the Cloudflare edge it went through. */
65
+ export type Timing = {
66
+ ms: number;
67
+ serverMs: number | null;
68
+ colo?: string | null;
69
+ };
70
+ /** The parts of a WebSocket the plugin uses; both `ws` and browser sockets fit. */
71
+ export type SocketLike = {
72
+ readonly readyState: number;
73
+ send(data: string): void;
74
+ close(code?: number, reason?: string): void;
75
+ addEventListener(type: "open" | "message" | "close" | "error", listener: (event: any) => void): void;
76
+ };
77
+ export type SocketFactory = (url: string, headers: Record<string, string>) => SocketLike;
51
78
  export type KoishiCommandRegistration = {
52
79
  description: string;
53
80
  action: (context: KoishiActionContext, ...args: string[]) => Promise<string> | string;
@@ -57,10 +84,12 @@ export type KoishiCommandBuilder = {
57
84
  };
58
85
  export type KoishiLikeContext = {
59
86
  command(name: string, description: string): KoishiCommandBuilder;
60
- setInterval?(handler: () => Promise<void> | void, intervalMs: number): void;
61
87
  logger?(name: string): {
62
88
  warn(...args: unknown[]): void;
63
89
  };
90
+ /** Send to channels as `platform:channelId`. */
91
+ broadcast?(channels: string[], content: string): Promise<unknown>;
92
+ on?(event: "dispose", listener: () => void): void;
64
93
  };
65
94
  export type KoishiActionContext = {
66
95
  session: {
@@ -81,6 +110,57 @@ export type KoishiActionContext = {
81
110
  };
82
111
  };
83
112
  export declare function applyPrismKoishiPlugin(ctx: KoishiLikeContext, config: PrismKoishiPluginConfig): void;
113
+ type PlatformEvent = {
114
+ event: string;
115
+ data: unknown;
116
+ };
117
+ /**
118
+ * The one connection to PRiSM. Requests go out as frames and are matched to
119
+ * their replies by id; the platform also pushes events down it. While it is
120
+ * down a request fails at once: queueing a checkout or a top-up to run later
121
+ * would make players repeat it, and a resend could run it twice.
122
+ */
123
+ export declare class PrismSocket {
124
+ private readonly open;
125
+ private readonly url;
126
+ private readonly token;
127
+ private readonly hello;
128
+ private readonly onEvent;
129
+ private readonly logger?;
130
+ private socket;
131
+ private readonly pending;
132
+ private retryMs;
133
+ private retryTimer;
134
+ private pingTimer;
135
+ private lastHeard;
136
+ private stopped;
137
+ private sequence;
138
+ private readonly pongWaiters;
139
+ constructor(open: SocketFactory, url: string, token: string, hello: Record<string, unknown>, onEvent: (event: PlatformEvent) => void, logger?: {
140
+ warn(...args: unknown[]): void;
141
+ } | undefined);
142
+ start(): void;
143
+ stop(): void;
144
+ private connect;
145
+ private reconnectLater;
146
+ private failPending;
147
+ private receive;
148
+ /** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
149
+ ping(): Promise<number>;
150
+ request(frame: {
151
+ method: "GET" | "POST" | "PUT";
152
+ path: string;
153
+ query?: Record<string, unknown>;
154
+ body?: unknown;
155
+ }): Promise<SocketReply>;
156
+ }
157
+ type SocketReply = {
158
+ status: number;
159
+ body: any;
160
+ serverMs?: number | null;
161
+ };
162
+ /** The platform connection URL for a shop. */
163
+ export declare function platformSocketUrl(baseUrl: string, shopCode: string): string;
84
164
  export type Sender = {
85
165
  id: string;
86
166
  name: string;
package/lib/index.js CHANGED
@@ -3,9 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
6
+ exports.PrismSocket = exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
7
7
  exports.apply = apply;
8
8
  exports.applyPrismKoishiPlugin = applyPrismKoishiPlugin;
9
+ exports.platformSocketUrl = platformSocketUrl;
9
10
  exports.humanReadableBotError = humanReadableBotError;
10
11
  exports.resolveMahjongTableConfigs = resolveMahjongTableConfigs;
11
12
  const display_time_js_1 = require("./display-time.js");
@@ -15,8 +16,8 @@ exports.name = "prism";
15
16
  exports.version = package_json_1.default.version;
16
17
  exports.Config = koishi_1.Schema.object({
17
18
  autoRegister: koishi_1.Schema.boolean().default(true).description("是否自动注册"),
18
- shopCode: koishi_1.Schema.string().description("统一平台店铺编号(单店兼容模式留空)"),
19
- baseUrl: koishi_1.Schema.string().description("PRiSM 后端 API Base URL"),
19
+ shopCode: koishi_1.Schema.string().required().description("统一平台店铺编号"),
20
+ baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
20
21
  integrationToken: koishi_1.Schema.string().role("secret").description("集成 API Token"),
21
22
  currencyName: koishi_1.Schema.string().default("猫粮").description("代币名称"),
22
23
  defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备名或别名"),
@@ -32,7 +33,8 @@ exports.Config = koishi_1.Schema.object({
32
33
  ]).default("all").description("玩家可用的命令"),
33
34
  readOnlyNotice: koishi_1.Schema.string().default("请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作").description("只读模式下玩家使用受限命令时的回复"),
34
35
  logoutNotifyUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("结账账单私聊通知的平台身份列表(如 onebot:123456)"),
35
- powerOffInterval: koishi_1.Schema.number().default(0).description("无人自动关机等待秒数 (0为禁用)"),
36
+ idleNotifyChannelIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("闲置自动关机的提醒发到哪里:群写 onebot:群号,私聊写 onebot:private:QQ号"),
37
+ idleReminderMinutes: koishi_1.Schema.number().min(0).max(120).default(5).description("自动关机前几分钟提醒(0 为不提醒)"),
36
38
  mahjongTableConfigs: koishi_1.Schema.array(koishi_1.Schema.object({
37
39
  displayName: koishi_1.Schema.string().required().description("桌位显示名称和 session 标签"),
38
40
  aliases: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("命令别名(至少一个),例如 a、四麻A"),
@@ -63,8 +65,10 @@ const USAGE = {
63
65
  mahjong_leave: "/下桌",
64
66
  mahjong_list: "/麻将列表",
65
67
  api_benchmark: "/api测速 [次数]",
68
+ ws_benchmark: "/ws测速 [次数]",
66
69
  prism_on: "/prism on <设备名|别名|all>",
67
70
  prism_off: "/prism off <设备名|别名|all>",
71
+ prism_keep: "/keep <设备名或别名>",
68
72
  prism_coin: "/prism coin <设备名或别名> [数量]",
69
73
  prism_scan: "/prism scan <设备名或别名>",
70
74
  prism_redeem: "/prism redeem <兑换码>",
@@ -83,17 +87,7 @@ function applyPrismKoishiPlugin(ctx, config) {
83
87
  return context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
84
88
  }
85
89
  };
86
- const bind = wrap(async (context, code) => {
87
- const sender = await service.sender(context);
88
- if (!config.shopCode || !config.baseUrl || !config.integrationToken)
89
- return "请店家配置统一平台店铺编号与 Bot 凭据";
90
- const response = await fetch(`${config.baseUrl.replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(config.shopCode)}/integration/platform-binding/confirm`, {
91
- method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${config.integrationToken}` },
92
- body: JSON.stringify({ code, provider: sender.provider, subject: sender.id }),
93
- });
94
- const body = await response.json();
95
- return response.ok ? "绑定成功,请返回网页继续操作" : body.error?.message ?? "绑定失败,请重新生成验证码";
96
- });
90
+ const bind = wrap(async (context, code) => service.bind(await service.sender(context), code));
97
91
  ctx.command("bind <code:string>", "绑定网页登录账号到当前平台身份").action(bind);
98
92
  // Instructions already handed to players may still say prism.bind.
99
93
  ctx.command("prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)").action(bind);
@@ -114,7 +108,8 @@ function applyPrismKoishiPlugin(ctx, config) {
114
108
  ctx.command("logout [target:user]", "结算玩家计费场次").action(effect(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.logout(sender, context.session?.bot), context.session?.bot)));
115
109
  ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot)));
116
110
  ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot)));
117
- ctx.command("api测速 [count:number]", "测试 Bot 到 PRiSM API 的钱包查询延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
111
+ ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
112
+ ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkWs(await service.sender(context), count)));
118
113
  ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions()));
119
114
  ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot)));
120
115
  ctx.command("list", "查看当前在线玩家列表").action(wrap(async (context) => service.listActiveSessions(await service.sender(context))));
@@ -123,76 +118,244 @@ function applyPrismKoishiPlugin(ctx, config) {
123
118
  ctx.command("lock", "向默认门锁设备发送开门指令").action(effect(async (context) => service.lock(await service.sender(context))));
124
119
  ctx.command("on <deviceRef>", "请求启动指定设备电源").action(effect(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
125
120
  ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(effect(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
121
+ // Not limited by read-only mode: it never switches anything on, and the
122
+ // platform only accepts it from an entered player for a device that is on.
123
+ ctx.command("keep <deviceRef>", "延迟闲置设备的自动关机").action(wrap(async (context, deviceRef) => service.keep(await service.sender(context), deviceRef)));
126
124
  ctx.command("coin <deviceRef> [count]", "请求向指定设备投币").action(effect(async (context, deviceRef, count) => service.coin(await service.sender(context), deviceRef, count)));
127
125
  ctx.command("scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡").action(effect(async (context, deviceRef) => service.scan(await service.sender(context), deviceRef)));
128
126
  ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
129
127
  ctx.command("add <target:user> <amount:number>", "增加玩家余额").action(wrap(async (context, target, amount) => service.adjustTargetBalance(await service.sender(context), target, amount, 1, context.session?.bot)));
130
128
  ctx.command("del <target:user> <amount:number>", "扣除玩家余额").action(wrap(async (context, target, amount) => service.adjustTargetBalance(await service.sender(context), target, amount, -1, context.session?.bot)));
131
129
  ctx.command("overwrite <target:user> <amount:number> [reason:text]", "覆盖结账金额并立即结账").action(wrap(async (context, target, amount, reason) => service.overwriteTargetCheckout(await service.sender(context), target, amount, reason, context.session?.bot)));
132
- const intervalMs = (config.powerOffInterval ?? 0) * 1000;
133
- if (intervalMs > 0 && typeof ctx.setInterval === "function") {
134
- ctx.setInterval(() => {
135
- service.autoPowerOffLoop().catch(() => {
136
- /* swallow */
137
- });
138
- }, intervalMs);
139
- }
130
+ ctx.on?.("dispose", () => service.dispose());
140
131
  }
141
- /* ----------------------------- api client ---------------------------------- */
142
- class PrismApiClient {
143
- http;
144
- config;
145
- constructor(http, config) {
146
- this.http = http;
147
- this.config = config;
148
- }
149
- get headers() {
150
- return {
151
- "Content-Type": "application/json",
152
- };
132
+ /* --------------------------- platform connection --------------------------- */
133
+ const SOCKET_OPEN = 1;
134
+ const REQUEST_TIMEOUT_MS = 30_000;
135
+ const PING_MS = 30_000;
136
+ const FIRST_RETRY_MS = 1000;
137
+ const MAX_RETRY_MS = 30_000;
138
+ /**
139
+ * The one connection to PRiSM. Requests go out as frames and are matched to
140
+ * their replies by id; the platform also pushes events down it. While it is
141
+ * down a request fails at once: queueing a checkout or a top-up to run later
142
+ * would make players repeat it, and a resend could run it twice.
143
+ */
144
+ class PrismSocket {
145
+ open;
146
+ url;
147
+ token;
148
+ hello;
149
+ onEvent;
150
+ logger;
151
+ socket = null;
152
+ pending = new Map();
153
+ retryMs = FIRST_RETRY_MS;
154
+ retryTimer = null;
155
+ pingTimer = null;
156
+ lastHeard = 0;
157
+ stopped = false;
158
+ sequence = 0;
159
+ pongWaiters = [];
160
+ constructor(open, url, token, hello, onEvent, logger) {
161
+ this.open = open;
162
+ this.url = url;
163
+ this.token = token;
164
+ this.hello = hello;
165
+ this.onEvent = onEvent;
166
+ this.logger = logger;
167
+ }
168
+ start() {
169
+ this.stopped = false;
170
+ this.connect();
171
+ }
172
+ stop() {
173
+ this.stopped = true;
174
+ if (this.retryTimer)
175
+ clearTimeout(this.retryTimer);
176
+ if (this.pingTimer)
177
+ clearInterval(this.pingTimer);
178
+ this.socket?.close(1000, "dispose");
179
+ this.socket = null;
180
+ this.failPending();
181
+ }
182
+ connect() {
183
+ let socket;
184
+ try {
185
+ socket = this.open(this.url, { Authorization: `Bearer ${this.token}` });
186
+ }
187
+ catch (error) {
188
+ this.logger?.warn("PRiSM connection failed", error);
189
+ this.reconnectLater();
190
+ return;
191
+ }
192
+ this.socket = socket;
193
+ socket.addEventListener("open", () => {
194
+ this.retryMs = FIRST_RETRY_MS;
195
+ this.lastHeard = Date.now();
196
+ socket.send(JSON.stringify({ type: "hello", ...this.hello }));
197
+ if (this.pingTimer)
198
+ clearInterval(this.pingTimer);
199
+ this.pingTimer = setInterval(() => {
200
+ // Two missed pings: the connection is gone even if no close arrived.
201
+ if (Date.now() - this.lastHeard > PING_MS * 2)
202
+ socket.close(4000, "silent");
203
+ else if (socket.readyState === SOCKET_OPEN)
204
+ socket.send("ping");
205
+ }, PING_MS);
206
+ });
207
+ socket.addEventListener("message", (event) => this.receive(String(event?.data ?? "")));
208
+ socket.addEventListener("close", () => {
209
+ if (this.socket !== socket)
210
+ return;
211
+ this.socket = null;
212
+ if (this.pingTimer)
213
+ clearInterval(this.pingTimer);
214
+ this.failPending();
215
+ this.reconnectLater();
216
+ });
217
+ socket.addEventListener("error", (error) => this.logger?.warn("PRiSM connection error", error?.message ?? error));
153
218
  }
154
- async request(method, path, options) {
155
- let url = path.replace(/^\/rpc\//, this.config.shopCode ? `/api/v1/shops/${encodeURIComponent(this.config.shopCode)}/` : "/api/v1/");
156
- if (options.params) {
157
- for (const [key, value] of Object.entries(options.params)) {
158
- url = url.replace(`:${key}`, encodeURIComponent(String(value)));
159
- }
219
+ reconnectLater() {
220
+ if (this.stopped)
221
+ return;
222
+ if (this.retryTimer)
223
+ clearTimeout(this.retryTimer);
224
+ this.retryTimer = setTimeout(() => this.connect(), this.retryMs);
225
+ this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);
226
+ }
227
+ failPending() {
228
+ for (const [, waiter] of this.pending) {
229
+ clearTimeout(waiter.timer);
230
+ waiter.reject(unreachable());
160
231
  }
161
- const fullUrl = `${this.config.baseUrl.replace(/\/+$/, "")}${url}`;
162
- const headers = {
163
- ...this.headers,
164
- };
165
- if (options.token) {
166
- headers["Authorization"] = `Bearer ${options.token}`;
232
+ this.pending.clear();
233
+ }
234
+ receive(raw) {
235
+ this.lastHeard = Date.now();
236
+ if (raw === "pong") {
237
+ this.pongWaiters.shift()?.();
238
+ return;
167
239
  }
240
+ let frame;
168
241
  try {
169
- const config = { headers, params: options.query };
170
- let response;
171
- if (method === "GET") {
172
- response = await this.http.get(fullUrl, config);
173
- }
174
- else if (method === "POST") {
175
- response = await this.http.post(fullUrl, options.body ?? {}, config);
176
- }
177
- else if (method === "PUT") {
178
- response = await this.http.put(fullUrl, options.body ?? {}, config);
242
+ frame = JSON.parse(raw);
243
+ }
244
+ catch {
245
+ return;
246
+ }
247
+ if (frame?.type === "response" && typeof frame.id === "string") {
248
+ const waiter = this.pending.get(frame.id);
249
+ if (!waiter)
250
+ return;
251
+ this.pending.delete(frame.id);
252
+ clearTimeout(waiter.timer);
253
+ waiter.resolve({ status: Number(frame.status) || 500, body: frame.body, serverMs: typeof frame.serverMs === "number" ? frame.serverMs : null });
254
+ }
255
+ else if (frame?.type === "event" && typeof frame.event === "string") {
256
+ try {
257
+ this.onEvent({ event: frame.event, data: frame.data });
179
258
  }
180
- else {
181
- throw new Error(`Unsupported method ${method}`);
259
+ catch (error) {
260
+ this.logger?.warn("PRiSM event handling failed", error);
182
261
  }
183
- return response && typeof response === "object" && Object.hasOwn(response, "data") ? response.data : response;
184
262
  }
185
- catch (error) {
186
- if (error?.response) {
187
- const body = error.response.data ?? {};
188
- const err = typeof body === "object" && body !== null && typeof body.error === "object"
189
- ? body.error
190
- : {};
191
- const status = Number(error.response.status) || 500;
192
- throw new PrismBotClientError(typeof err.message === "string" ? err.message : `Backend request failed with HTTP ${status}.`, typeof err.code === "string" ? err.code : `HTTP_${status}`, status, body, error);
263
+ }
264
+ /** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
265
+ ping() {
266
+ const socket = this.socket;
267
+ if (!socket || socket.readyState !== SOCKET_OPEN)
268
+ return Promise.reject(unreachable());
269
+ return new Promise((resolve, reject) => {
270
+ const startedAt = performance.now();
271
+ const timer = setTimeout(() => {
272
+ const index = this.pongWaiters.indexOf(answered);
273
+ if (index >= 0)
274
+ this.pongWaiters.splice(index, 1);
275
+ reject(new PrismBotClientError("服务器没有及时回应", "API_TIMEOUT", 0, {}));
276
+ }, REQUEST_TIMEOUT_MS);
277
+ const answered = () => {
278
+ clearTimeout(timer);
279
+ resolve(performance.now() - startedAt);
280
+ };
281
+ this.pongWaiters.push(answered);
282
+ socket.send("ping");
283
+ });
284
+ }
285
+ request(frame) {
286
+ const socket = this.socket;
287
+ if (!socket || socket.readyState !== SOCKET_OPEN)
288
+ return Promise.reject(unreachable());
289
+ const id = `${Date.now().toString(36)}-${(this.sequence++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
290
+ return new Promise((resolve, reject) => {
291
+ const timer = setTimeout(() => {
292
+ this.pending.delete(id);
293
+ reject(new PrismBotClientError("服务器没有及时回应,请稍后确认结果", "API_TIMEOUT", 0, {}));
294
+ }, REQUEST_TIMEOUT_MS);
295
+ this.pending.set(id, { resolve, reject, timer });
296
+ try {
297
+ socket.send(JSON.stringify({ type: "request", id, ...frame }));
298
+ }
299
+ catch {
300
+ clearTimeout(timer);
301
+ this.pending.delete(id);
302
+ reject(unreachable());
193
303
  }
194
- throw new PrismBotClientError("Unable to reach PRiSM backend.", "API_UNREACHABLE", 0, {}, error);
304
+ });
305
+ }
306
+ }
307
+ exports.PrismSocket = PrismSocket;
308
+ function unreachable() {
309
+ return new PrismBotClientError("暂时连不上服务器", "API_UNREACHABLE", 0, {});
310
+ }
311
+ function replyError(status, body) {
312
+ const err = body && typeof body === "object" && typeof body.error === "object" ? body.error : {};
313
+ return new PrismBotClientError(typeof err.message === "string" ? err.message : `Backend request failed with HTTP ${status}.`, typeof err.code === "string" ? err.code : `HTTP_${status}`, status, body ?? {});
314
+ }
315
+ function benchmarkCount(raw) {
316
+ const count = raw == null || raw === "" ? 5 : Number(raw);
317
+ return Number.isInteger(count) && count >= 1 && count <= 10 ? count : null;
318
+ }
319
+ function spread(samples) {
320
+ const average = samples.reduce((sum, sample) => sum + sample, 0) / samples.length;
321
+ return `最小 ${Math.round(Math.min(...samples))} / 平均 ${Math.round(average)} / 最大 ${Math.round(Math.max(...samples))} ms`;
322
+ }
323
+ function serverLine(timings) {
324
+ const known = timings.map((timing) => timing.serverMs).filter((value) => value !== null);
325
+ if (!known.length)
326
+ return [];
327
+ return [`服务端处理:平均 ${Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)} ms`];
328
+ }
329
+ /** The platform connection URL for a shop. */
330
+ function platformSocketUrl(baseUrl, shopCode) {
331
+ const base = baseUrl.trim().replace(/\/+$/, "").replace(/^http/i, "ws");
332
+ return `${base}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/ws`;
333
+ }
334
+ /* ----------------------------- api client ---------------------------------- */
335
+ class PrismApiClient {
336
+ socket;
337
+ http;
338
+ constructor(socket, http) {
339
+ this.socket = socket;
340
+ this.http = http;
341
+ }
342
+ async request(method, path, options) {
343
+ let target = path.replace(/^\/rpc\//, "");
344
+ for (const [key, value] of Object.entries(options.params ?? {})) {
345
+ target = target.replace(`:${key}`, encodeURIComponent(String(value)));
195
346
  }
347
+ const { status, body } = await this.socket.request({
348
+ method,
349
+ path: target,
350
+ ...(options.query ? { query: options.query } : {}),
351
+ ...(method === "GET" ? {} : { body: options.body ?? {} }),
352
+ });
353
+ if (status >= 400)
354
+ throw replyError(status, body);
355
+ return body && typeof body === "object" && Object.hasOwn(body, "data") ? body.data : body;
356
+ }
357
+ confirmPlatformBinding(code, provider, subject) {
358
+ return this.request("POST", "/rpc/integration/platform-binding/confirm", { body: { code, provider, subject } });
196
359
  }
197
360
  identityBody(identity) {
198
361
  return {
@@ -209,17 +372,15 @@ class PrismApiClient {
209
372
  ? "/rpc/integration/players/by-identity/register"
210
373
  : "/rpc/integration/players/by-identity/resolve";
211
374
  const result = await this.request("POST", endpoint, {
212
- token: this.config.integrationToken,
213
375
  body: this.identityBody(identity),
214
376
  });
215
377
  return result.player;
216
378
  }
217
379
  async getVersion() {
218
- return this.request("GET", "/version", {});
380
+ return this.request("GET", "version", {});
219
381
  }
220
382
  async startSessionByIdentity(identity, body) {
221
383
  return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
222
- token: this.config.integrationToken,
223
384
  body: {
224
385
  ...this.identityBody(identity),
225
386
  ...(body ?? {}),
@@ -228,44 +389,63 @@ class PrismApiClient {
228
389
  }
229
390
  async stopSessionByIdentity(identity, sessionId) {
230
391
  return this.request("POST", "/rpc/integration/players/by-identity/sessions/:sessionId/stop", {
231
- token: this.config.integrationToken,
232
392
  params: { sessionId },
233
393
  body: this.identityBody(identity),
234
394
  });
235
395
  }
236
396
  async getWalletByIdentity(identity) {
237
397
  return this.request("POST", "/rpc/integration/players/by-identity/wallet", {
238
- token: this.config.integrationToken,
239
398
  body: this.identityBody(identity),
240
399
  });
241
400
  }
401
+ /** The wallet query over the platform connection, timed. */
402
+ async timeWalletOverSocket(identity) {
403
+ const startedAt = performance.now();
404
+ const reply = await this.socket.request({ method: "POST", path: "integration/players/by-identity/wallet", body: this.identityBody(identity) });
405
+ const ms = performance.now() - startedAt;
406
+ if (reply.status >= 400)
407
+ throw replyError(reply.status, reply.body);
408
+ return { ms, serverMs: reply.serverMs ?? null };
409
+ }
410
+ /** The same wallet query as a plain HTTP request, the way the Bot used to call, timed. */
411
+ async timeWalletOverHttp(identity) {
412
+ if (!this.http)
413
+ throw new PrismBotClientError("HTTP 测速不可用", "HTTP_UNAVAILABLE", 0, {});
414
+ const { post, baseUrl, shopCode, token } = this.http;
415
+ const url = `${baseUrl.trim().replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/players/by-identity/wallet`;
416
+ const startedAt = performance.now();
417
+ const response = await post(url, { authorization: `Bearer ${token}`, "content-type": "application/json" }, this.identityBody(identity));
418
+ const ms = performance.now() - startedAt;
419
+ if (response.status >= 400)
420
+ throw replyError(response.status, response.data);
421
+ const server = Number.parseFloat(response.headers.get("x-response-time") ?? "");
422
+ return { ms, serverMs: Number.isFinite(server) ? server : null, colo: response.headers.get("cf-ray")?.split("-").pop() ?? null };
423
+ }
424
+ pingSocket() {
425
+ return this.socket.ping();
426
+ }
242
427
  async getAssetsByIdentity(identity) {
243
428
  return this.request("POST", "/rpc/integration/players/by-identity/assets", {
244
- token: this.config.integrationToken,
245
429
  body: this.identityBody(identity),
246
430
  });
247
431
  }
248
432
  async getSessionHistoryByIdentity(identity) {
249
433
  return this.request("POST", "/rpc/integration/players/by-identity/history", {
250
- token: this.config.integrationToken,
251
434
  body: this.identityBody(identity),
252
435
  });
253
436
  }
254
437
  async previewCheckoutByIdentity(identity) {
255
438
  return this.request("POST", "/rpc/integration/players/by-identity/checkout/preview", {
256
- token: this.config.integrationToken,
257
439
  body: this.identityBody(identity),
258
440
  });
259
441
  }
260
442
  async confirmCheckoutByIdentity(identity, closeSessionsBeforeBalanceCheck = true) {
261
443
  return this.request("POST", "/rpc/integration/players/by-identity/checkout/confirm", {
262
- token: this.config.integrationToken,
263
444
  body: { ...this.identityBody(identity), closeSessionsBeforeBalanceCheck },
264
445
  });
265
446
  }
266
447
  async redeemCodeByIdentity(identity, code) {
267
448
  return this.request("POST", "/rpc/integration/players/by-identity/redeem", {
268
- token: this.config.integrationToken,
269
449
  body: {
270
450
  ...this.identityBody(identity),
271
451
  code,
@@ -274,7 +454,6 @@ class PrismApiClient {
274
454
  }
275
455
  async requestDeviceCommandByIdentity(identity, command, options) {
276
456
  return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
277
- token: this.config.integrationToken,
278
457
  body: {
279
458
  ...this.identityBody(identity),
280
459
  ...(options?.staffOverride ? { staffOverride: true } : {}),
@@ -288,7 +467,6 @@ class PrismApiClient {
288
467
  }
289
468
  async requestScanByIdentity(identity, scan) {
290
469
  return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
291
- token: this.config.integrationToken,
292
470
  body: {
293
471
  ...this.identityBody(identity),
294
472
  target: {
@@ -305,79 +483,101 @@ class PrismApiClient {
305
483
  });
306
484
  }
307
485
  async listActiveSessions() {
308
- return this.request("GET", "/rpc/integration/sessions/active", {
309
- token: this.config.integrationToken,
310
- });
486
+ return this.request("GET", "/rpc/integration/sessions/active", {});
311
487
  }
312
488
  async listDeviceStates() {
313
- return this.request("GET", "/rpc/integration/device-states", {
314
- token: this.config.integrationToken,
315
- });
489
+ return this.request("GET", "/rpc/integration/device-states", {});
316
490
  }
317
491
  async adjustAssetsByIdentity(identity, adjustments) {
318
492
  return this.request("POST", "/rpc/integration/players/by-identity/assets/adjustments", {
319
- token: this.config.integrationToken,
320
493
  body: { ...this.identityBody(identity), adjustments },
321
494
  });
322
495
  }
323
496
  async adjustWalletByIdentity(identity, amount, reason) {
324
497
  return this.request("POST", "/rpc/integration/players/by-identity/wallet/adjustment", {
325
- token: this.config.integrationToken,
326
498
  body: { ...this.identityBody(identity), amount, reason },
327
499
  });
328
500
  }
329
501
  async checkoutWithOverrideByIdentity(identity, total, reason) {
330
502
  return this.request("POST", "/rpc/integration/players/by-identity/checkout/override", {
331
- token: this.config.integrationToken,
332
503
  body: { ...this.identityBody(identity), total, reason },
333
504
  });
334
505
  }
335
506
  }
336
- /* ------------------------------- service ----------------------------------- */
337
507
  class PrismKoishiService {
508
+ ctx;
338
509
  config;
339
510
  mahjongTables = new Map();
340
511
  logoutInFlight = new Map();
341
512
  client;
342
513
  logger;
514
+ socket = null;
343
515
  constructor(ctx, config) {
516
+ this.ctx = ctx;
344
517
  this.config = config;
345
518
  this.logger = ctx.logger?.("prism");
346
519
  if (config.client) {
347
520
  this.client = config.client;
521
+ return;
348
522
  }
349
- else {
350
- if (!config.baseUrl) {
351
- throw new Error("PRiSM Koishi plugin requires either 'client' or 'baseUrl' in config.");
352
- }
353
- if (!config.integrationToken) {
354
- throw new Error("PRiSM Koishi plugin requires 'integrationToken' in config when 'client' is not provided.");
355
- }
356
- const http = ctx.http ?? {
357
- async get(url, c) {
358
- const res = await fetch(url, { method: "GET", headers: c.headers });
359
- if (!res.ok)
360
- throw { response: { data: await res.json(), status: res.status } };
361
- return res.json();
362
- },
363
- async post(url, body, c) {
364
- const res = await fetch(url, { method: "POST", headers: c.headers, body: JSON.stringify(body) });
365
- if (!res.ok)
366
- throw { response: { data: await res.json(), status: res.status } };
367
- return res.json();
368
- },
369
- async put(url, body, c) {
370
- const res = await fetch(url, { method: "PUT", headers: c.headers, body: JSON.stringify(body) });
371
- if (!res.ok)
372
- throw { response: { data: await res.json(), status: res.status } };
373
- return res.json();
374
- }
375
- };
376
- this.client = new PrismApiClient(http, {
377
- baseUrl: config.baseUrl,
378
- shopCode: config.shopCode,
379
- integrationToken: config.integrationToken,
523
+ if (!config.shopCode || !config.baseUrl || !config.integrationToken) {
524
+ throw new Error("PRiSM Koishi plugin requires 'shopCode', 'baseUrl' and 'integrationToken'.");
525
+ }
526
+ const open = config.socket ?? ((url, headers) => {
527
+ const http = ctx.http;
528
+ if (!http?.ws)
529
+ throw new Error("Koishi http service with WebSocket support is required.");
530
+ return http.ws(url, { headers });
531
+ });
532
+ const lead = Math.max(0, config.idleReminderMinutes ?? 5);
533
+ this.socket = new PrismSocket(open, platformSocketUrl(config.baseUrl, config.shopCode), config.integrationToken,
534
+ // Without anywhere to send it, the platform need not plan a reminder.
535
+ lead > 0 && (config.idleNotifyChannelIds ?? []).length ? { reminderLeadSeconds: lead * 60 } : {}, (event) => {
536
+ if (event.event === "idle.reminder")
537
+ void this.remindIdle(event.data);
538
+ }, this.logger);
539
+ const post = config.httpPost ?? (async (url, headers, body) => {
540
+ const http = ctx.http;
541
+ if (typeof http !== "function")
542
+ throw new PrismBotClientError("HTTP 测速需要 Koishi 的 http 服务", "HTTP_UNAVAILABLE", 0, {});
543
+ const response = await http(url, {
544
+ method: "POST", headers, data: body, keepAlive: true, timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true,
380
545
  });
546
+ return { status: response.status, headers: response.headers, data: response.data };
547
+ });
548
+ this.client = new PrismApiClient(this.socket, { post, baseUrl: config.baseUrl, shopCode: config.shopCode, token: config.integrationToken });
549
+ this.socket.start();
550
+ }
551
+ dispose() {
552
+ this.socket?.stop();
553
+ }
554
+ async bind(sender, code) {
555
+ try {
556
+ await this.client.confirmPlatformBinding(code, sender.provider, sender.id);
557
+ return "绑定成功,请返回网页继续操作";
558
+ }
559
+ catch (error) {
560
+ if (error instanceof PrismBotClientError && error.status > 0)
561
+ return error.message || "绑定失败,请重新生成验证码";
562
+ throw error;
563
+ }
564
+ }
565
+ /** Tell the configured channels a power-off is coming. Short: they can read a device name. */
566
+ async remindIdle(reminder) {
567
+ const channels = this.config.idleNotifyChannelIds ?? [];
568
+ if (!channels.length || typeof this.ctx.broadcast !== "function")
569
+ return;
570
+ const now = (this.config.now?.() ?? new Date()).getTime();
571
+ const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
572
+ const names = reminder.devices.map((device) => device.name).join("、");
573
+ const message = reminder.reason === "shop_empty"
574
+ ? `店里没人,${minutes} 分钟后全部关机`
575
+ : `${names} 闲置中,${minutes} 分钟后关机。已入场的玩家发送 keep 设备名 可以延迟`;
576
+ try {
577
+ await this.ctx.broadcast(channels, message);
578
+ }
579
+ catch (error) {
580
+ this.logger?.warn("PRiSM idle reminder failed", error);
381
581
  }
382
582
  }
383
583
  async sender(context) {
@@ -641,24 +841,42 @@ class PrismKoishiService {
641
841
  const result = (await this.client.getWalletByIdentity(this.identity(sender)));
642
842
  return formatWallet(result.wallet, this.config.currencyName);
643
843
  }
844
+ /**
845
+ * The wallet query over plain HTTP. The first request usually has to open a
846
+ * connection (DNS, TCP, TLS), so it is reported apart from the reused ones.
847
+ */
644
848
  async benchmarkApi(sender, rawCount) {
645
- const count = rawCount == null || rawCount === "" ? 3 : Number(rawCount);
646
- if (!Number.isInteger(count) || count < 1 || count > 10)
849
+ const count = benchmarkCount(rawCount);
850
+ if (count === null)
647
851
  return "次数须为 1 到 10 的整数。";
648
- const samples = [];
649
- for (let index = 0; index < count; index++) {
650
- const startedAt = performance.now();
651
- await this.client.getWalletByIdentity(this.identity(sender));
652
- samples.push(performance.now() - startedAt);
653
- }
654
- const min = Math.min(...samples);
655
- const max = Math.max(...samples);
656
- const average = samples.reduce((sum, sample) => sum + sample, 0) / samples.length;
852
+ const timings = [];
853
+ for (let index = 0; index < count; index++)
854
+ timings.push(await this.client.timeWalletOverHttp(this.identity(sender)));
855
+ const [first, ...rest] = timings;
657
856
  return [
658
- `📡 PRiSM API 测速(钱包查询,${count} 次)`,
659
- `最小:${formatNumber(min)} ms`,
660
- `平均:${formatNumber(average)} ms`,
661
- `最大:${formatNumber(max)} ms`,
857
+ `📡 API 测速(HTTP,钱包查询 ${count} 次)`,
858
+ `首次:${Math.round(first.ms)} ms(含建立连接)`,
859
+ ...(rest.length ? [`之后:${spread(rest.map((timing) => timing.ms))}`] : []),
860
+ ...serverLine(timings),
861
+ ...(first.colo ? [`节点:${first.colo}`] : []),
862
+ ].join("\n");
863
+ }
864
+ /** Heartbeats (the network alone) and the same wallet query over the platform connection. */
865
+ async benchmarkWs(sender, rawCount) {
866
+ const count = benchmarkCount(rawCount);
867
+ if (count === null)
868
+ return "次数须为 1 到 10 的整数。";
869
+ const pings = [];
870
+ for (let index = 0; index < count; index++)
871
+ pings.push(await this.client.pingSocket());
872
+ const timings = [];
873
+ for (let index = 0; index < count; index++)
874
+ timings.push(await this.client.timeWalletOverSocket(this.identity(sender)));
875
+ return [
876
+ `📡 WS 测速(${count} 次)`,
877
+ `心跳:${spread(pings)}`,
878
+ `钱包查询:${spread(timings.map((timing) => timing.ms))}`,
879
+ ...serverLine(timings),
662
880
  ].join("\n");
663
881
  }
664
882
  async versions() {
@@ -823,27 +1041,29 @@ ${table.players.map(player => player.name).join("、")}`),
823
1041
  .map((d) => `${d.label || d.deviceId}: ${normalizeDeviceState(d.state)}`)
824
1042
  .join("\n");
825
1043
  }
826
- async autoPowerOffLoop() {
827
- const interval = this.config.powerOffInterval ?? 0;
828
- if (interval <= 0)
829
- return;
830
- const result = (await this.client.listActiveSessions());
831
- const sessions = (result?.sessions ?? []);
832
- if (sessions.length > 0)
833
- return;
834
- const statesResult = (await this.client.listDeviceStates());
835
- const states = (statesResult?.deviceStates ?? []);
836
- const anyOn = states.some((d) => normalizeDeviceState(d.state) === "on");
837
- if (!anyOn)
838
- return;
839
- const dummySender = { id: "system", name: "system", provider: "system" };
840
- await this.power(dummySender, "all", "off", true);
1044
+ /** Keep a running device from being switched off as idle; never switches one on. */
1045
+ async keep(sender, deviceRef) {
1046
+ try {
1047
+ const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
1048
+ type: "power.keep",
1049
+ target: { kind: "facility", ref: deviceRef },
1050
+ });
1051
+ if (this.getCommandFailureMessage(result)) {
1052
+ this.logDeviceCommandFailure(result);
1053
+ return `延迟失败,${deviceCommandFailureReason(result)}`;
1054
+ }
1055
+ return `✅ ${result.action.payload.deviceLabel} 已延迟关机`;
1056
+ }
1057
+ catch (error) {
1058
+ this.logCommandError(error);
1059
+ return `延迟失败,${powerFailureReason(error)}`;
1060
+ }
841
1061
  }
842
1062
  /* ---------------------------- helpers ---------------------------------- */
843
- async power(sender, deviceRef, state, systemOverride = false) {
1063
+ async power(sender, deviceRef, state) {
844
1064
  const operation = state === "on" ? "启动" : "关闭";
845
- const staffOverride = systemOverride || (state === "off" && this.config.powerCommandsAdminOnly === true);
846
- if (!systemOverride && staffOverride && !matchesPlatformIdentity(this.config.staffUserIds ?? [], sender)) {
1065
+ const staffOverride = state === "off" && this.config.powerCommandsAdminOnly === true;
1066
+ if (staffOverride && !matchesPlatformIdentity(this.config.staffUserIds ?? [], sender)) {
847
1067
  return `${operation}失败,权限不足`;
848
1068
  }
849
1069
  try {
@@ -1214,7 +1434,9 @@ function humanReadableBotError(error) {
1214
1434
  if (error.code === "INSUFFICIENT_BALANCE") {
1215
1435
  return "余额不足,暂时不能结账。请先充值,或由店员在后台改价后再结账。";
1216
1436
  }
1217
- if (error.code === "API_UNREACHABLE" || error.code === "NETWORK_ERROR" || error.code === "HTTP_0") {
1437
+ if (error.code === "API_UNREACHABLE")
1438
+ return "操作失败,暂时连不上服务器。";
1439
+ if (error.code === "NETWORK_ERROR" || error.code === "HTTP_0") {
1218
1440
  return genericCommandFailure();
1219
1441
  }
1220
1442
  if (error.code === "API_TIMEOUT") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-prism",
3
- "version": "0.1.41",
3
+ "version": "0.2.0",
4
4
  "description": "PRiSM Next 计费与设备管理系统的 Koishi 机器人集成插件",
5
5
  "main": "./lib/index.js",
6
6
  "exports": {