koishi-plugin-prism 0.2.0 → 0.3.1

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/lib/index.js CHANGED
@@ -3,44 +3,26 @@ 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.PrismSocket = exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
6
+ exports.PrismSocket = exports.PrismBotClientError = exports.Config = exports.version = exports.name = exports.HaWatcher = void 0;
7
7
  exports.apply = apply;
8
8
  exports.applyPrismKoishiPlugin = applyPrismKoishiPlugin;
9
9
  exports.platformSocketUrl = platformSocketUrl;
10
10
  exports.humanReadableBotError = humanReadableBotError;
11
- exports.resolveMahjongTableConfigs = resolveMahjongTableConfigs;
12
11
  const display_time_js_1 = require("./display-time.js");
12
+ const ha_watch_js_1 = require("./ha-watch.js");
13
13
  const koishi_1 = require("koishi");
14
14
  const package_json_1 = __importDefault(require("../package.json"));
15
+ var ha_watch_js_2 = require("./ha-watch.js");
16
+ Object.defineProperty(exports, "HaWatcher", { enumerable: true, get: function () { return ha_watch_js_2.HaWatcher; } });
15
17
  exports.name = "prism";
16
18
  exports.version = package_json_1.default.version;
19
+ // Only how to reach the shop is configured here. Everything else (staff, door,
20
+ // tables, read-only mode, reminders, watching) is the bot's own settings on its
21
+ // resource page in PRiSM, read from the platform when the bot connects.
17
22
  exports.Config = koishi_1.Schema.object({
18
- autoRegister: koishi_1.Schema.boolean().default(true).description("是否自动注册"),
19
- shopCode: koishi_1.Schema.string().required().description("统一平台店铺编号"),
20
23
  baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
21
- integrationToken: koishi_1.Schema.string().role("secret").description("集成 API Token"),
22
- currencyName: koishi_1.Schema.string().default("猫粮").description("代币名称"),
23
- defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备名或别名"),
24
- defaultScanProvider: koishi_1.Schema.string().default("aime").description("默认刷卡提供商"),
25
- loginPricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("默认入场绑定的计费策略ID"),
26
- loginSessionLabel: koishi_1.Schema.string().default("音游区间").description("默认入场场次标签 (防重复入场)"),
27
- enableStaffCommands: koishi_1.Schema.boolean().default(false).description("是否启用管理员指令"),
28
- staffUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("允许执行管理员指令的平台身份列表(如 onebot:123456、telegram:123456)"),
29
- powerCommandsAdminOnly: koishi_1.Schema.boolean().default(false).description("关机是否仅允许管理员使用;开机始终仅已入场玩家可用"),
30
- playerCommands: koishi_1.Schema.union([
31
- koishi_1.Schema.const("all").description("全部:玩家可以在 Bot 里入场、结账、上下桌和操作设备"),
32
- koishi_1.Schema.const("readonly").description("只读:玩家只能绑定身份、查询和兑换;入场、结账、上下桌和设备操作仅管理员可用"),
33
- ]).default("all").description("玩家可用的命令"),
34
- readOnlyNotice: koishi_1.Schema.string().default("请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作").description("只读模式下玩家使用受限命令时的回复"),
35
- logoutNotifyUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("结账账单私聊通知的平台身份列表(如 onebot:123456)"),
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 为不提醒)"),
38
- mahjongTableConfigs: koishi_1.Schema.array(koishi_1.Schema.object({
39
- displayName: koishi_1.Schema.string().required().description("桌位显示名称和 session 标签"),
40
- aliases: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("命令别名(至少一个),例如 a、四麻A"),
41
- pricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("开局时绑定的计费方案 ID"),
42
- })).default([]).description("麻将桌配置"),
43
- mahjongTableSize: koishi_1.Schema.number().default(4).description("麻将桌人数限制"),
24
+ shopCode: koishi_1.Schema.string().description("可选:店铺编号。接入凭据已经指明店铺,无需填写;旧配置仍认。"),
25
+ integrationToken: koishi_1.Schema.string().role("secret").required().description("集成 API Token;其余设置在 PRiSM 商户工作台 → 资源 → 这个 Bot → Bot 设置"),
44
26
  });
45
27
  function apply(ctx, config) {
46
28
  applyPrismKoishiPlugin(ctx, config);
@@ -62,7 +44,7 @@ class PrismBotClientError extends Error {
62
44
  exports.PrismBotClientError = PrismBotClientError;
63
45
  const USAGE = {
64
46
  mahjong_join: "/上桌 <桌号>",
65
- mahjong_leave: "/下桌",
47
+ mahjong_leave: "/下桌 [桌号]",
66
48
  mahjong_list: "/麻将列表",
67
49
  api_benchmark: "/api测速 [次数]",
68
50
  ws_benchmark: "/ws测速 [次数]",
@@ -72,50 +54,53 @@ const USAGE = {
72
54
  prism_coin: "/prism coin <设备名或别名> [数量]",
73
55
  prism_scan: "/prism scan <设备名或别名>",
74
56
  prism_redeem: "/prism redeem <兑换码>",
75
- list: "/list",
57
+ list: "/list [资源或方案]",
76
58
  show: "/show [设备ID]",
77
59
  };
78
60
  function applyPrismKoishiPlugin(ctx, config) {
79
61
  const service = new PrismKoishiService(ctx, config);
80
- const wrap = (handler) => async (context, ...args) => {
62
+ const wrap = (handler, gate = {}) => async (context, ...args) => {
63
+ const quoted = (message) => context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
81
64
  try {
82
- const message = await handler(context, ...args);
83
- return context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
65
+ if (!gate.offline) {
66
+ // A disabled bot, or one that cannot read its settings, answers nothing else.
67
+ const bot = await service.config();
68
+ if (gate.effect && bot.settings.playerCommands === "readonly" && !service.isStaff(bot, await service.sender(context))) {
69
+ return quoted(bot.settings.readOnlyNotice || DEFAULT_READ_ONLY_NOTICE);
70
+ }
71
+ if (gate.billed && !bot.billingEnabled)
72
+ return quoted(BILLING_DISABLED_NOTICE);
73
+ }
74
+ return quoted(await handler(context, ...args));
84
75
  }
85
76
  catch (error) {
86
- const message = service.handleCommandError(error);
87
- return context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
77
+ return quoted(service.handleCommandError(error));
88
78
  }
89
79
  };
80
+ const effect = (handler, gate = {}) => wrap(handler, { ...gate, effect: true });
81
+ const billed = { billed: true };
90
82
  const bind = wrap(async (context, code) => service.bind(await service.sender(context), code));
91
83
  ctx.command("bind <code:string>", "绑定网页登录账号到当前平台身份").action(bind);
92
84
  // Instructions already handed to players may still say prism.bind.
93
85
  ctx.command("prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)").action(bind);
94
- // In read-only mode a player may look things up and redeem, but anything that
95
- // starts billing, settles a bill or drives a device is left to staff.
96
- const effect = (handler) => wrap(async (context, ...args) => {
97
- if (config.playerCommands === "readonly" && !matchesPlatformIdentity(config.staffUserIds ?? [], await service.sender(context))) {
98
- return config.readOnlyNotice || "请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作";
99
- }
100
- return handler(context, ...args);
101
- });
102
- ctx.command("login [target:user]", "开启玩家计费场次").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot)));
103
- ctx.command("入场 [target:user]", "入场").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot)));
104
- ctx.command("mahjong <tableId>", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
105
- ctx.command("上桌 [tableId]", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
106
- ctx.command("下桌", "离开当前所在麻将桌").action(effect(async (context) => service.mahjongLeave(await service.sender(context))));
107
- ctx.command("麻将列表", "查看麻将机状态与别名").action(wrap(async () => service.listMahjongTables()));
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)));
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)));
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)));
86
+ ctx.command("login [target:user]", "开启玩家计费场次").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot), billed));
87
+ ctx.command("入场 [target:user]", "入场").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot), billed));
88
+ ctx.command("mahjong <tableId>", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId), billed));
89
+ ctx.command("上桌 [tableId]", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId), billed));
90
+ ctx.command("下桌 [tableId]", "离开当前所在麻将桌").action(effect(async (context, tableId) => service.mahjongLeave(await service.sender(context), tableId), billed));
91
+ ctx.command("麻将列表", "查看麻将机状态与别名").action(wrap(async () => service.listMahjongTables(), billed));
92
+ 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), billed));
93
+ ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot), billed));
94
+ ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot), billed));
111
95
  ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
112
96
  ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkWs(await service.sender(context), count)));
113
- ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions()));
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)));
115
- ctx.command("list", "查看当前在线玩家列表").action(wrap(async (context) => service.listActiveSessions(await service.sender(context))));
97
+ // The Bot's own version stays visible while the platform is out of reach.
98
+ ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions(), { offline: true }));
99
+ ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot), billed));
100
+ ctx.command("list [name:text]", "查看在店玩家,或某个资源、某个计费方案上的玩家").action(wrap(async (context, name) => service.listActiveSessions(await service.sender(context), name), billed));
116
101
  ctx.command("show [deviceId]", "查看设备电源状态").action(wrap(async (context, deviceId) => service.listDeviceStates(deviceId)));
117
- ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot)));
118
- ctx.command("lock", "向默认门锁设备发送开门指令").action(effect(async (context) => service.lock(await service.sender(context))));
102
+ ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot), billed));
103
+ ctx.command("lock", "向本店门锁发送开门指令").action(effect(async (context) => service.lock(await service.sender(context))));
119
104
  ctx.command("on <deviceRef>", "请求启动指定设备电源").action(effect(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
120
105
  ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(effect(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
121
106
  // Not limited by read-only mode: it never switches anything on, and the
@@ -123,12 +108,14 @@ function applyPrismKoishiPlugin(ctx, config) {
123
108
  ctx.command("keep <deviceRef>", "延迟闲置设备的自动关机").action(wrap(async (context, deviceRef) => service.keep(await service.sender(context), deviceRef)));
124
109
  ctx.command("coin <deviceRef> [count]", "请求向指定设备投币").action(effect(async (context, deviceRef, count) => service.coin(await service.sender(context), deviceRef, count)));
125
110
  ctx.command("scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡").action(effect(async (context, deviceRef) => service.scan(await service.sender(context), deviceRef)));
126
- ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
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)));
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)));
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)));
111
+ ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code), billed));
112
+ 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), billed));
113
+ 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), billed));
114
+ 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), billed));
130
115
  ctx.on?.("dispose", () => service.dispose());
131
116
  }
117
+ const DEFAULT_READ_ONLY_NOTICE = "请扫描店内二维码或碰 NFC,在网页或 App Clip 里入场、结账和操作设备。";
118
+ const BILLING_DISABLED_NOTICE = "本店未启用计费";
132
119
  /* --------------------------- platform connection --------------------------- */
133
120
  const SOCKET_OPEN = 1;
134
121
  const REQUEST_TIMEOUT_MS = 30_000;
@@ -148,6 +135,7 @@ class PrismSocket {
148
135
  hello;
149
136
  onEvent;
150
137
  logger;
138
+ hooks;
151
139
  socket = null;
152
140
  pending = new Map();
153
141
  retryMs = FIRST_RETRY_MS;
@@ -156,19 +144,53 @@ class PrismSocket {
156
144
  lastHeard = 0;
157
145
  stopped = false;
158
146
  sequence = 0;
147
+ /** Bumped by every hello being prepared, so only the newest one is sent. */
148
+ greeting = 0;
159
149
  pongWaiters = [];
160
- constructor(open, url, token, hello, onEvent, logger) {
150
+ constructor(open,
151
+ /** Resolved at each connection: the shop is learned from the credential first. */
152
+ url, token,
153
+ /**
154
+ * What to say in hello, read afresh each time: the bot's settings live on
155
+ * the platform, so they are fetched over this connection before it is
156
+ * sent. Null when they could not be read.
157
+ */
158
+ hello, onEvent, logger,
159
+ /**
160
+ * `onWatch`: the platform asked this bot to watch Home Assistant, or with null to stop.
161
+ * `onClose`: the connection is gone, and with it the platform's idea of what this bot watches.
162
+ */
163
+ hooks) {
161
164
  this.open = open;
162
165
  this.url = url;
163
166
  this.token = token;
164
167
  this.hello = hello;
165
168
  this.onEvent = onEvent;
166
169
  this.logger = logger;
170
+ this.hooks = hooks;
171
+ }
172
+ /** Send a frame if the connection is up; a report made while it is down is dropped, as the platform has forgotten the watch by then. */
173
+ send(frame) {
174
+ const socket = this.socket;
175
+ if (!socket || socket.readyState !== SOCKET_OPEN)
176
+ return;
177
+ try {
178
+ socket.send(JSON.stringify(frame));
179
+ }
180
+ catch {
181
+ // The connection went between the check and the send.
182
+ }
167
183
  }
168
184
  start() {
169
185
  this.stopped = false;
170
186
  this.connect();
171
187
  }
188
+ /** Connect again with what the platform has just told us, such as the shop. */
189
+ reconnect() {
190
+ this.socket?.close(1000, "shop known");
191
+ this.socket = null;
192
+ this.connect();
193
+ }
172
194
  stop() {
173
195
  this.stopped = true;
174
196
  if (this.retryTimer)
@@ -182,7 +204,7 @@ class PrismSocket {
182
204
  connect() {
183
205
  let socket;
184
206
  try {
185
- socket = this.open(this.url, { Authorization: `Bearer ${this.token}` });
207
+ socket = this.open(typeof this.url === "function" ? this.url() : this.url, { Authorization: `Bearer ${this.token}` });
186
208
  }
187
209
  catch (error) {
188
210
  this.logger?.warn("PRiSM connection failed", error);
@@ -191,9 +213,8 @@ class PrismSocket {
191
213
  }
192
214
  this.socket = socket;
193
215
  socket.addEventListener("open", () => {
194
- this.retryMs = FIRST_RETRY_MS;
195
216
  this.lastHeard = Date.now();
196
- socket.send(JSON.stringify({ type: "hello", ...this.hello }));
217
+ void this.greet(socket, true);
197
218
  if (this.pingTimer)
198
219
  clearInterval(this.pingTimer);
199
220
  this.pingTimer = setInterval(() => {
@@ -212,10 +233,39 @@ class PrismSocket {
212
233
  if (this.pingTimer)
213
234
  clearInterval(this.pingTimer);
214
235
  this.failPending();
236
+ // The platform forgets what this bot watches with the connection; it is asked again after hello.
237
+ this.hooks?.onClose();
215
238
  this.reconnectLater();
216
239
  });
217
240
  socket.addEventListener("error", (error) => this.logger?.warn("PRiSM connection error", error?.message ?? error));
218
241
  }
242
+ /**
243
+ * Read the bot's settings and say hello with them: on connecting, and again
244
+ * when the platform says they changed. A connection that cannot read them
245
+ * at all is closed and tried again later, without resetting the backoff, so
246
+ * a platform that keeps failing is not asked every second.
247
+ */
248
+ async greet(socket, connecting) {
249
+ const greeting = ++this.greeting;
250
+ let hello = null;
251
+ try {
252
+ hello = await this.hello();
253
+ }
254
+ catch (error) {
255
+ this.logger?.warn("PRiSM bot settings unavailable", error);
256
+ }
257
+ // A newer hello is on its way, or this connection is already gone.
258
+ if (greeting !== this.greeting || this.socket !== socket)
259
+ return;
260
+ if (!hello) {
261
+ if (connecting)
262
+ socket.close(4000, "settings unavailable");
263
+ return;
264
+ }
265
+ if (connecting)
266
+ this.retryMs = FIRST_RETRY_MS;
267
+ this.send({ type: "hello", ...hello });
268
+ }
219
269
  reconnectLater() {
220
270
  if (this.stopped)
221
271
  return;
@@ -260,6 +310,21 @@ class PrismSocket {
260
310
  this.logger?.warn("PRiSM event handling failed", error);
261
311
  }
262
312
  }
313
+ else if (frame?.type === "config.changed") {
314
+ // The bot's settings, staff, door or tables changed: read them again and say hello with them.
315
+ if (this.socket)
316
+ void this.greet(this.socket, false);
317
+ }
318
+ else if (frame?.type === "ha.watch" || frame?.type === "ha.unwatch") {
319
+ // A watch that cannot be read is as good as none: the platform has nothing for this bot to watch.
320
+ const watch = frame.type === "ha.watch" ? (0, ha_watch_js_1.parseWatch)(frame.watch) : null;
321
+ try {
322
+ this.hooks?.onWatch(watch);
323
+ }
324
+ catch (error) {
325
+ this.logger?.warn("PRiSM Home Assistant watch failed", error);
326
+ }
327
+ }
263
328
  }
264
329
  /** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
265
330
  ping() {
@@ -326,10 +391,13 @@ function serverLine(timings) {
326
391
  return [];
327
392
  return [`服务端处理:平均 ${Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)} ms`];
328
393
  }
329
- /** The platform connection URL for a shop. */
330
- function platformSocketUrl(baseUrl, shopCode) {
394
+ /**
395
+ * The platform connection URL. The credential names the shop, as a device's
396
+ * token names its machine at `/io/ws`, so nothing identifying is in the path.
397
+ */
398
+ function platformSocketUrl(baseUrl) {
331
399
  const base = baseUrl.trim().replace(/\/+$/, "").replace(/^http/i, "ws");
332
- return `${base}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/ws`;
400
+ return `${base}/integration/ws`;
333
401
  }
334
402
  /* ----------------------------- api client ---------------------------------- */
335
403
  class PrismApiClient {
@@ -363,15 +431,19 @@ class PrismApiClient {
363
431
  provider: identity.provider,
364
432
  subject: identity.subject,
365
433
  },
366
- ...(identity.autoRegister === undefined ? {} : { autoRegister: identity.autoRegister }),
367
434
  ...(identity.displayName === undefined ? {} : { displayName: identity.displayName }),
368
435
  };
369
436
  }
437
+ /** The shop this credential belongs to, read before the shop code is known. */
438
+ setShopCode(code) { if (this.http)
439
+ this.http.shopCode = code; }
440
+ /** The bot's own settings and what it needs to know about the shop. */
441
+ async getBotConfig() {
442
+ return this.request("GET", "/rpc/integration/bot", {});
443
+ }
444
+ /** Always the register route: whether a new player is created is the shop's own switch. */
370
445
  async resolveOrRegisterIdentity(identity) {
371
- const endpoint = identity.autoRegister
372
- ? "/rpc/integration/players/by-identity/register"
373
- : "/rpc/integration/players/by-identity/resolve";
374
- const result = await this.request("POST", endpoint, {
446
+ const result = await this.request("POST", "/rpc/integration/players/by-identity/register", {
375
447
  body: this.identityBody(identity),
376
448
  });
377
449
  return result.player;
@@ -379,20 +451,25 @@ class PrismApiClient {
379
451
  async getVersion() {
380
452
  return this.request("GET", "version", {});
381
453
  }
382
- async startSessionByIdentity(identity, body) {
454
+ /** Admit a player into the shop's default plan; `created` is false when it was already billing. */
455
+ async startSessionByIdentity(identity) {
383
456
  return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
384
- body: {
385
- ...this.identityBody(identity),
386
- ...(body ?? {}),
387
- },
457
+ body: { ...this.identityBody(identity), entry: true },
388
458
  });
389
459
  }
390
- async stopSessionByIdentity(identity, sessionId) {
391
- return this.request("POST", "/rpc/integration/players/by-identity/sessions/:sessionId/stop", {
392
- params: { sessionId },
393
- body: this.identityBody(identity),
460
+ /** Seat or unseat a player; `table` is a table id, name or alias. */
461
+ async mahjongByIdentity(identity, table, action) {
462
+ return this.request("POST", "/rpc/integration/players/by-identity/mahjong", {
463
+ body: { ...this.identityBody(identity), table, action },
394
464
  });
395
465
  }
466
+ async listMahjongTables() {
467
+ return this.request("GET", "/rpc/integration/mahjong-tables", {});
468
+ }
469
+ /** Who is in the shop, each once at their place; with a name, one resource or one plan. */
470
+ async roster(name) {
471
+ return this.request("GET", "/rpc/integration/roster", name ? { query: { name } } : {});
472
+ }
396
473
  async getWalletByIdentity(identity) {
397
474
  return this.request("POST", "/rpc/integration/players/by-identity/wallet", {
398
475
  body: this.identityBody(identity),
@@ -412,6 +489,8 @@ class PrismApiClient {
412
489
  if (!this.http)
413
490
  throw new PrismBotClientError("HTTP 测速不可用", "HTTP_UNAVAILABLE", 0, {});
414
491
  const { post, baseUrl, shopCode, token } = this.http;
492
+ if (!shopCode)
493
+ throw new PrismBotClientError("店铺尚未读取", "SHOP_UNKNOWN", 0, {});
415
494
  const url = `${baseUrl.trim().replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/players/by-identity/wallet`;
416
495
  const startedAt = performance.now();
417
496
  const response = await post(url, { authorization: `Bearer ${token}`, "content-type": "application/json" }, this.identityBody(identity));
@@ -488,11 +567,6 @@ class PrismApiClient {
488
567
  async listDeviceStates() {
489
568
  return this.request("GET", "/rpc/integration/device-states", {});
490
569
  }
491
- async adjustAssetsByIdentity(identity, adjustments) {
492
- return this.request("POST", "/rpc/integration/players/by-identity/assets/adjustments", {
493
- body: { ...this.identityBody(identity), adjustments },
494
- });
495
- }
496
570
  async adjustWalletByIdentity(identity, amount, reason) {
497
571
  return this.request("POST", "/rpc/integration/players/by-identity/wallet/adjustment", {
498
572
  body: { ...this.identityBody(identity), amount, reason },
@@ -506,37 +580,52 @@ class PrismApiClient {
506
580
  }
507
581
  class PrismKoishiService {
508
582
  ctx;
509
- config;
510
- mahjongTables = new Map();
583
+ options;
511
584
  logoutInFlight = new Map();
512
585
  client;
513
586
  logger;
514
587
  socket = null;
515
- constructor(ctx, config) {
588
+ watcher = null;
589
+ /** The bot's settings as last read; null until read, and again once the shop disables the bot. */
590
+ bot = null;
591
+ /** The read in flight, shared by commands arriving together. */
592
+ reading = null;
593
+ reads = 0;
594
+ /** Whether the settings let this bot watch Home Assistant. */
595
+ watching = false;
596
+ constructor(ctx, options) {
516
597
  this.ctx = ctx;
517
- this.config = config;
598
+ this.options = options;
518
599
  this.logger = ctx.logger?.("prism");
519
- if (config.client) {
520
- this.client = config.client;
600
+ if (options.client) {
601
+ this.client = options.client;
521
602
  return;
522
603
  }
523
- if (!config.shopCode || !config.baseUrl || !config.integrationToken) {
524
- throw new Error("PRiSM Koishi plugin requires 'shopCode', 'baseUrl' and 'integrationToken'.");
604
+ if (!options.baseUrl || !options.integrationToken) {
605
+ throw new Error("PRiSM Koishi plugin requires 'baseUrl' and 'integrationToken'.");
525
606
  }
526
- const open = config.socket ?? ((url, headers) => {
607
+ const open = options.socket ?? ((url, headers) => {
527
608
  const http = ctx.http;
528
609
  if (!http?.ws)
529
610
  throw new Error("Koishi http service with WebSocket support is required.");
530
611
  return http.ws(url, { headers });
531
612
  });
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) => {
613
+ // Home Assistant is reached the way the platform is, unless a test stands in for the platform and
614
+ // says nothing about Home Assistant: then there is no watching to offer.
615
+ const haOpen = options.haSocket ?? (options.socket ? null : open);
616
+ if (haOpen)
617
+ this.watcher = new ha_watch_js_1.HaWatcher(haOpen, (frame) => this.socket?.send(frame), this.logger);
618
+ this.socket = new PrismSocket(open, platformSocketUrl(options.baseUrl), options.integrationToken, () => this.hello(), (event) => {
536
619
  if (event.event === "idle.reminder")
537
620
  void this.remindIdle(event.data);
538
- }, this.logger);
539
- const post = config.httpPost ?? (async (url, headers, body) => {
621
+ }, this.logger, this.watcher
622
+ ? {
623
+ // Only a bot whose settings allow it watches, whatever the platform asks.
624
+ onWatch: (watch) => (watch && this.watching ? this.watcher.watch(watch) : this.watcher.stop()),
625
+ onClose: () => this.watcher.stop(),
626
+ }
627
+ : undefined);
628
+ const post = options.httpPost ?? (async (url, headers, body) => {
540
629
  const http = ctx.http;
541
630
  if (typeof http !== "function")
542
631
  throw new PrismBotClientError("HTTP 测速需要 Koishi 的 http 服务", "HTTP_UNAVAILABLE", 0, {});
@@ -545,12 +634,77 @@ class PrismKoishiService {
545
634
  });
546
635
  return { status: response.status, headers: response.headers, data: response.data };
547
636
  });
548
- this.client = new PrismApiClient(this.socket, { post, baseUrl: config.baseUrl, shopCode: config.shopCode, token: config.integrationToken });
637
+ this.client = new PrismApiClient(this.socket, { post, baseUrl: options.baseUrl, token: options.integrationToken, ...(options.shopCode ? { shopCode: options.shopCode } : {}) });
549
638
  this.socket.start();
550
639
  }
551
640
  dispose() {
641
+ this.watcher?.stop();
552
642
  this.socket?.stop();
553
643
  }
644
+ /** The bot's settings, read from the platform the first time they are needed. */
645
+ async config() {
646
+ return this.bot ?? this.reading ?? this.readConfig();
647
+ }
648
+ /** Read the settings afresh. A disabled bot forgets the ones it had, so each command asks again. */
649
+ readConfig() {
650
+ // Only the newest read may settle what the bot knows; an older one answering late is stale.
651
+ const read = ++this.reads;
652
+ this.reading = (async () => {
653
+ try {
654
+ const bot = parseBotConfig(await this.client.getBotConfig());
655
+ if (read === this.reads) {
656
+ this.bot = bot;
657
+ if (bot.shop?.code)
658
+ this.client.setShopCode(bot.shop.code);
659
+ }
660
+ return bot;
661
+ }
662
+ catch (error) {
663
+ if (read === this.reads && error instanceof PrismBotClientError && error.code === "BOT_DISABLED")
664
+ this.bot = null;
665
+ throw error;
666
+ }
667
+ finally {
668
+ if (read === this.reads)
669
+ this.reading = null;
670
+ }
671
+ })();
672
+ return this.reading;
673
+ }
674
+ /**
675
+ * What this bot says in hello, from settings read just now. A disabled bot
676
+ * offers nothing: no watching and no reminders.
677
+ */
678
+ async hello() {
679
+ let bot;
680
+ try {
681
+ bot = await this.readConfig();
682
+ }
683
+ catch (error) {
684
+ if (!(error instanceof PrismBotClientError && error.code === "BOT_DISABLED"))
685
+ throw error;
686
+ this.watching = false;
687
+ this.watcher?.stop();
688
+ return {};
689
+ }
690
+ const { settings } = bot;
691
+ // Watching is the platform's to schedule: every bot that can offers, and the
692
+ // hub picks among them. A bot with no Home Assistant connection cannot.
693
+ this.watching = this.watcher !== null;
694
+ if (!this.watching)
695
+ this.watcher?.stop();
696
+ return {
697
+ name: bot.bot.name,
698
+ // Saying so is what makes the platform consider this bot for the watch.
699
+ ...(this.watching ? { ha: true } : {}),
700
+ // Without anywhere to send it, the platform need not plan a reminder.
701
+ ...(settings.idleChannelIds.length && settings.idleReminderMinutes > 0 ? { reminderLeadSeconds: settings.idleReminderMinutes * 60 } : {}),
702
+ };
703
+ }
704
+ /** Whether the sender is one of the shop's staff on this platform. */
705
+ isStaff(bot, sender) {
706
+ return bot.staff.some((identity) => identity.provider === sender.provider && identity.subject === sender.id);
707
+ }
554
708
  async bind(sender, code) {
555
709
  try {
556
710
  await this.client.confirmPlatformBinding(code, sender.provider, sender.id);
@@ -564,10 +718,10 @@ class PrismKoishiService {
564
718
  }
565
719
  /** Tell the configured channels a power-off is coming. Short: they can read a device name. */
566
720
  async remindIdle(reminder) {
567
- const channels = this.config.idleNotifyChannelIds ?? [];
721
+ const channels = this.bot?.settings.idleChannelIds ?? [];
568
722
  if (!channels.length || typeof this.ctx.broadcast !== "function")
569
723
  return;
570
- const now = (this.config.now?.() ?? new Date()).getTime();
724
+ const now = (this.options.now?.() ?? new Date()).getTime();
571
725
  const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
572
726
  const names = reminder.devices.map((device) => device.name).join("、");
573
727
  const message = reminder.reason === "shop_empty"
@@ -597,20 +751,20 @@ class PrismKoishiService {
597
751
  catch { }
598
752
  return { id, name, provider };
599
753
  }
600
- async register(sender) {
601
- await this.client.resolveOrRegisterIdentity(this.identity(sender));
602
- return "注册成功";
603
- }
604
754
  async loginForTarget(actor, targetSubject, bot) {
605
755
  return this.withTarget(actor, targetSubject, async (sender, isTargeted) => {
606
- await this.client.startSessionByIdentity(this.identity(sender), this.loginSessionBody());
607
- return isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender)} 入场成功` : "✅ 入场成功";
756
+ const result = (await this.client.startSessionByIdentity(this.identity(sender)));
757
+ // Already in: the player had this session before, and the plan says where.
758
+ if (result?.created === false) {
759
+ const where = typeof result.planName === "string" && result.planName ? `「${result.planName}」` : "场";
760
+ return isTargeted ? `用户 ${formatPlayerReference(sender)} 已在${where}中,无需重复入场` : `您已在${where}中,无需重复入场`;
761
+ }
762
+ // Starting the plan may end one it cannot bill together with.
763
+ const stopped = Array.isArray(result?.billing?.stopped) ? result.billing.stopped.filter((name) => typeof name === "string" && name) : [];
764
+ const ended = stopped.length ? `\n结束方案:${stopped.join("、")}` : "";
765
+ return (isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender)} 入场成功` : "✅ 入场成功") + ended;
608
766
  }, bot);
609
767
  }
610
- async login(sender) {
611
- await this.client.startSessionByIdentity(this.identity(sender), this.loginSessionBody());
612
- return "✅ 入场成功";
613
- }
614
768
  async withTarget(actor, targetSubject, action, bot) {
615
769
  const target = await this.targetSender(actor, targetSubject, bot);
616
770
  if (typeof target === "string")
@@ -624,7 +778,7 @@ class PrismKoishiService {
624
778
  return "金额必须大于 0";
625
779
  const isAddition = direction === 1;
626
780
  await this.client.adjustWalletByIdentity(this.identity(sender), amount * direction, isAddition ? "Koishi 管理员增加余额" : "Koishi 管理员扣除余额");
627
- return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${this.config.currencyName}`;
781
+ return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${(await this.config()).currencyName}`;
628
782
  }, bot);
629
783
  }
630
784
  async overwriteTargetCheckout(actor, targetSubject, rawAmount, rawReason, bot) {
@@ -634,124 +788,95 @@ class PrismKoishiService {
634
788
  return "金额必须为非负数";
635
789
  const reason = cleanText(rawReason) || "管理员调价";
636
790
  const result = (await this.client.checkoutWithOverrideByIdentity(this.identity(sender), total, reason));
637
- const playerId = String(result.playerSettlement.playerId);
638
- if (playerId)
639
- this.removeMahjongPlayer(playerId);
640
791
  return this.formatAndNotifyCheckout(result, sender, "✅ 覆盖结账成功 · 结算账单", bot);
641
792
  }, bot);
642
793
  }
643
- async mahjongJoin(sender, rawTableId) {
644
- const tableId = cleanText(rawTableId);
645
- if (!tableId)
794
+ /**
795
+ * Seat the player at a table. The platform opens the table (starting
796
+ * everyone's billing) once it fills, so a player need not enter first.
797
+ */
798
+ async mahjongJoin(sender, rawTableRef) {
799
+ const tableRef = cleanText(rawTableRef);
800
+ if (!tableRef)
646
801
  return "请指定麻将桌,例如 /上桌 a;可先使用 /麻将列表 查看可用桌位。";
647
- const tableConfig = this.mahjongTableConfigs().get(tableId);
648
- if (!tableConfig)
649
- return `未找到麻将桌「${tableId}」。可先使用 /麻将列表 查看可用桌位。`;
650
- const tableKey = tableConfig.tableId;
651
- const tableSubject = tableConfig.displayName || `${tableKey} 桌`;
652
- const player = await this.resolvePlayer(sender);
653
- const playerId = String(player.id ?? "");
654
- const activeResult = (await this.client.listActiveSessions());
655
- const activeSessions = (activeResult.sessions ?? []);
656
- this.syncMahjongTableStates(activeSessions);
657
- if (!this.hasEntrySession(playerId, activeSessions)) {
658
- return "请先入场后再上桌。";
659
- }
660
- const existing = this.mahjongTableForPlayer(playerId);
661
- if (existing)
662
- return `你已经在 ${existing},无需重复上桌。`;
663
- const state = this.mahjongTables.get(tableKey) ?? { waiting: [], activeSessions: {} };
664
- this.mahjongTables.set(tableKey, state);
665
- const activeCount = Object.keys(state.activeSessions).length;
666
- const tableSize = this.config.mahjongTableSize ?? 4;
667
- if (activeCount >= tableSize) {
668
- return `「${tableSubject}」正在游玩中(${activeCount}/${tableSize}),请等待本局结束后再上桌。`;
669
- }
670
- if (activeCount > 0) {
671
- const label = tableConfig.displayName;
672
- const result = (await this.client.startSessionByIdentity(this.identity(sender), {
673
- pricingConfigIds: tableConfig.pricingConfigIds,
674
- label,
675
- entry: false,
676
- }));
677
- const session = (result?.session ?? {});
678
- const sessionId = String(session.id ?? "");
679
- if (sessionId) {
680
- state.activeSessions[playerId] = sessionId;
681
- }
682
- return `已加入 ${tableSubject},补位成功,麻将计费已开始。当前 ${activeCount + 1}/${tableSize} 人。`;
802
+ const table = findMahjongTable((await this.config()).mahjongTables, tableRef);
803
+ if (!table)
804
+ return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
805
+ let state;
806
+ try {
807
+ state = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "join")).mahjong;
683
808
  }
684
- state.waiting.push({
685
- playerId,
686
- senderId: sender.id,
687
- displayName: sender.name || playerId,
688
- identity: this.identity(sender),
689
- });
690
- if (state.waiting.length < tableSize) {
691
- return `已加入 ${tableSubject},当前 ${state.waiting.length}/${tableSize} 人。`;
692
- }
693
- const seats = state.waiting.slice(0, tableSize);
694
- state.waiting = state.waiting.slice(tableSize);
695
- const label = tableConfig.displayName;
696
- for (const seat of seats) {
697
- const result = (await this.client.startSessionByIdentity(seat.identity, {
698
- pricingConfigIds: tableConfig.pricingConfigIds,
699
- label,
700
- entry: false,
701
- }));
702
- const session = (result?.session ?? {});
703
- const sessionId = String(session.id ?? "");
704
- if (sessionId)
705
- state.activeSessions[seat.playerId] = sessionId;
706
- }
707
- return `${tableSubject}已满,麻将计费已开始。`;
708
- }
709
- async mahjongLeave(sender) {
710
- const activeResult = (await this.client.listActiveSessions());
711
- this.syncMahjongTableStates((activeResult.sessions ?? []));
712
- const player = await this.resolvePlayer(sender);
713
- const playerId = String(player.id ?? "");
714
- const tableKey = this.mahjongTableForPlayer(playerId);
715
- if (!tableKey)
716
- return "你当前未在任何麻将桌上。";
717
- const tableConfig = uniqueMahjongConfigs(this.mahjongTableConfigs()).find((table) => table.tableId === tableKey);
718
- const tableSubject = tableConfig?.displayName || tableKey;
719
- const state = this.mahjongTables.get(tableKey);
720
- if (!state)
721
- return "你当前未在任何麻将桌上。";
722
- const waitingBefore = state.waiting.length;
723
- state.waiting = state.waiting.filter((seat) => seat.playerId !== playerId);
724
- if (state.waiting.length !== waitingBefore) {
725
- return `已离开 ${tableSubject},当前 ${state.waiting.length}/${this.config.mahjongTableSize ?? 4} 人。`;
726
- }
727
- const sessionId = state.activeSessions[playerId];
728
- if (!sessionId)
729
- return "你当前未在任何麻将桌上。";
730
- // Do not show an available seat while the backend session is still running.
731
- // Failed stop requests must preserve the table state for safe retry.
732
- await this.client.stopSessionByIdentity(this.identity(sender), sessionId);
733
- delete state.activeSessions[playerId];
734
- const remainingCount = Object.keys(state.activeSessions).length;
735
- const tableSize = this.config.mahjongTableSize ?? 4;
736
- return `已离开 ${tableSubject},麻将计费已停止。当前还剩 ${remainingCount}/${tableSize} 人。`;
809
+ catch (error) {
810
+ if (!(error instanceof PrismBotClientError))
811
+ throw error;
812
+ if (error.code === "MAHJONG_TABLE_NOT_FOUND")
813
+ return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
814
+ if (error.code === "MAHJONG_TABLE_FULL")
815
+ return `「${table.name}」已满桌,请等待本局结束后再上桌。`;
816
+ if (error.code === "MAHJONG_ALREADY_SEATED")
817
+ return "你已经在另一张麻将桌上,请先 /下桌。";
818
+ const message = platformMessage(error);
819
+ if (message)
820
+ return `上桌失败,${message}`;
821
+ throw error;
822
+ }
823
+ const seated = state.seats.length;
824
+ const mine = state.seats.find((seat) => seat.mine);
825
+ if (mine?.playing)
826
+ return `已加入 ${table.name},麻将计费已开始。当前 ${seated}/${state.capacity} 人。`;
827
+ return `已加入 ${table.name},当前 ${seated}/${state.capacity} 人,满 ${state.capacity} 人开始计费。`;
828
+ }
829
+ /** Leave the table the player sits at, or the one named. */
830
+ async mahjongLeave(sender, rawTableRef) {
831
+ const tableRef = cleanText(rawTableRef);
832
+ const named = tableRef ? findMahjongTable((await this.config()).mahjongTables, tableRef) : null;
833
+ if (tableRef && !named)
834
+ return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
835
+ const [listing, player] = await Promise.all([this.client.listMahjongTables(), this.resolvePlayer(sender)]);
836
+ const playerId = String(player?.id ?? "");
837
+ const tables = (listing?.tables ?? []);
838
+ const table = tables.find((candidate) => (!named || candidate.id === named.id) && candidate.seats.some((seat) => seat.playerId === playerId));
839
+ if (!table?.id)
840
+ return named ? `你当前不在 ${named.name}。` : "你当前未在任何麻将桌上。";
841
+ const name = table.name || named?.name || table.id;
842
+ const wasPlaying = table.seats.some((seat) => seat.playerId === playerId && seat.playing);
843
+ let result;
844
+ try {
845
+ result = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "leave"));
846
+ }
847
+ catch (error) {
848
+ if (!(error instanceof PrismBotClientError))
849
+ throw error;
850
+ if (error.code === "MAHJONG_TABLE_NOT_FOUND")
851
+ return "你当前未在任何麻将桌上。";
852
+ const message = platformMessage(error);
853
+ if (message)
854
+ return `下桌失败,${message}`;
855
+ throw error;
856
+ }
857
+ const state = result.mahjong;
858
+ // Getting up does not check out: what still bills is said, so leaving the shop means /logout.
859
+ const remaining = Array.isArray(result.billing?.remaining)
860
+ ? result.billing.remaining.filter((plan) => typeof plan === "string" && plan)
861
+ : [];
862
+ return `已离开 ${name}${wasPlaying ? ",麻将计费已停止" : ""}。当前还剩 ${state.seats.length}/${state.capacity} 人。`
863
+ + (remaining.length ? `\n仍在计费:${remaining.join("、")}` : "");
737
864
  }
738
865
  async listMahjongTables() {
739
- const activeResult = (await this.client.listActiveSessions());
740
- this.syncMahjongTableStates((activeResult.sessions ?? []));
741
- const tableSize = this.config.mahjongTableSize ?? 4;
742
- const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
866
+ const result = (await this.client.listMahjongTables());
867
+ const tables = (result?.tables ?? []);
743
868
  if (tables.length === 0)
744
869
  return "当前没有配置任何麻将机。";
745
870
  const lines = [`🀄️ 麻将机列表(${tables.length} 台)`];
746
871
  for (const table of tables) {
747
- const state = this.mahjongTables.get(table.tableId) ?? { waiting: [], activeSessions: {} };
748
- const activeCount = Object.keys(state.activeSessions).length;
749
- const waitingCount = state.waiting.length;
872
+ const playing = table.seats.filter((seat) => seat.playing).length;
873
+ const waiting = table.seats.length - playing;
750
874
  const statuses = [
751
- ...(activeCount > 0 ? [`游玩中 ${activeCount}/${tableSize}`] : []),
752
- ...(waitingCount > 0 ? [`等位 ${waitingCount}/${tableSize}`] : []),
875
+ ...(playing > 0 ? [`游玩中 ${playing}/${table.capacity}`] : []),
876
+ ...(waiting > 0 ? [`等位 ${waiting}/${table.capacity}`] : []),
753
877
  ];
754
- lines.push(`- ${table.displayName}|别名:${table.aliases.length > 0 ? table.aliases.join("、") : "无"}|${statuses.join(";") || "空闲"}`);
878
+ const aliases = table.aliases ?? [];
879
+ lines.push(`- ${table.name}|别名:${aliases.length > 0 ? aliases.join("、") : "无"}|${statuses.join(";") || "空闲"}`);
755
880
  }
756
881
  return lines.join("\n");
757
882
  }
@@ -778,9 +903,6 @@ class PrismKoishiService {
778
903
  }
779
904
  async performLogout(sender, bot) {
780
905
  const result = (await this.client.confirmCheckoutByIdentity(this.identity(sender), false));
781
- const playerId = String(result.playerSettlement.playerId);
782
- if (playerId)
783
- this.removeMahjongPlayer(playerId);
784
906
  return this.formatAndNotifyCheckout(result, sender, "✅ 退场成功 · 结算账单", bot);
785
907
  }
786
908
  async formatAndNotifyCheckout(result, sender, title, bot) {
@@ -825,21 +947,18 @@ class PrismKoishiService {
825
947
  wallet: result.wallet,
826
948
  };
827
949
  const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
828
- const recipients = [...new Set([...(this.config.staffUserIds ?? []), ...(this.config.logoutNotifyUserIds ?? [])])];
829
- const channelIds = recipients.flatMap(identity => {
830
- if (identity.startsWith(`${sender.provider}:`))
831
- return [`private:${identity.slice(sender.provider.length + 1)}`];
832
- if (sender.provider === "onebot" && (!identity.includes(":") || identity.startsWith("private:")))
833
- return [identity.startsWith("private:") ? identity : `private:${identity}`];
834
- return [];
835
- });
950
+ // Staff reachable through this adapter get the receipt privately, when the bot's settings say so.
951
+ const config = await this.config();
952
+ const channelIds = config.settings.receiptsToStaff
953
+ ? [...new Set(config.staff.filter((identity) => identity.provider === sender.provider).map((identity) => `private:${identity.subject}`))]
954
+ : [];
836
955
  if (channelIds.length > 0 && bot?.broadcast)
837
956
  await bot.broadcast(channelIds, receipt);
838
957
  return receipt;
839
958
  }
840
959
  async wallet(sender) {
841
960
  const result = (await this.client.getWalletByIdentity(this.identity(sender)));
842
- return formatWallet(result.wallet, this.config.currencyName);
961
+ return formatWallet(result.wallet, (await this.config()).currencyName);
843
962
  }
844
963
  /**
845
964
  * The wallet query over plain HTTP. The first request usually has to open a
@@ -902,13 +1021,17 @@ class PrismKoishiService {
902
1021
  }
903
1022
  async history(sender) {
904
1023
  const result = (await this.client.getSessionHistoryByIdentity(this.identity(sender)));
905
- return formatHistory(result.sessions, this.config.currencyName);
1024
+ return formatHistory(result.sessions, (await this.config()).currencyName);
906
1025
  }
1026
+ /** Open the door the bot's settings name. */
907
1027
  async lock(sender) {
1028
+ const door = (await this.config()).door;
1029
+ if (!door)
1030
+ return "🔑 本店还没有设置 Bot 开的门";
908
1031
  try {
909
1032
  const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
910
1033
  type: "door.open",
911
- target: { kind: "facility", ref: this.config.defaultDoorDeviceId },
1034
+ target: { kind: "facility", ref: door.id },
912
1035
  });
913
1036
  const failure = this.getCommandFailureMessage(result);
914
1037
  if (failure) {
@@ -973,7 +1096,7 @@ class PrismKoishiService {
973
1096
  try {
974
1097
  const result = await this.client.requestScanByIdentity(this.identity(sender), {
975
1098
  deviceRef,
976
- provider: this.config.defaultScanProvider || "aime",
1099
+ provider: "aime",
977
1100
  });
978
1101
  const failure = deviceCommandFailureReason(result);
979
1102
  if (failure) {
@@ -998,31 +1121,41 @@ class PrismKoishiService {
998
1121
  return "兑换成功,但没有获得任何物品。";
999
1122
  return ["✅ 兑换成功!您获得了以下物品:", ...grantedAssets.map(formatRedeemedItem)].join("\n");
1000
1123
  }
1001
- async listActiveSessions(sender) {
1002
- const result = (await this.client.listActiveSessions());
1003
- const sessions = (result?.sessions ?? []);
1004
- this.syncMahjongTableStates(sessions);
1005
- const tableByLabel = new Map(uniqueMahjongConfigs(this.mahjongTableConfigs()).map((table) => [
1006
- mahjongSessionLabel(table),
1007
- table,
1008
- ]));
1009
- const players = groupSessionsByPlayer(sessions);
1010
- const groups = await this.buildPlayerGroups(players, tableByLabel, sender.provider);
1011
- this.mergeWaitingSeats(groups);
1012
- const tables = result.mahjongTables;
1013
- if (!tables)
1014
- return formatPlayerGroups(groups, this.config.mahjongTableSize ?? 4);
1015
- const seated = new Set(tables.flatMap(table => table.players.map(player => player.id)));
1016
- for (const group of groups.groups)
1017
- group.players = group.players.filter(player => !seated.has(player.playerId));
1018
- return [
1019
- formatPlayerGroups(groups, this.config.mahjongTableSize ?? 4, new Set([
1020
- ...seated, ...groups.groups.flatMap(group => group.players.map(player => player.playerId)),
1021
- ]).size),
1022
- ...tables.map(table => `
1023
- ${table.name}(${table.players.length}/${table.capacity}):
1024
- ${table.players.map(player => player.name).join("、")}`),
1025
- ].filter(Boolean).join("\n");
1124
+ /**
1125
+ * Who is in the shop, as the platform lists them: every player playing or
1126
+ * billing, each once, at the resource they occupy (with its head count and
1127
+ * capacity) or their most specific plan. With a name, everyone on that
1128
+ * resource or billing that plan.
1129
+ */
1130
+ async listActiveSessions(sender, name) {
1131
+ const wanted = cleanText(name);
1132
+ let roster;
1133
+ try {
1134
+ roster = (await this.client.roster(wanted || undefined));
1135
+ }
1136
+ catch (error) {
1137
+ if (wanted && error instanceof PrismBotClientError && error.code === "ROSTER_TARGET_NOT_FOUND")
1138
+ return `找不到「${wanted}」`;
1139
+ throw error;
1140
+ }
1141
+ const groups = [];
1142
+ for (const group of roster.groups ?? []) {
1143
+ const players = [];
1144
+ for (const member of group.members ?? []) {
1145
+ const player = {
1146
+ playerId: member.playerId,
1147
+ sessions: [{ playerDisplayName: member.displayName ?? undefined, identities: member.identities ?? [] }],
1148
+ };
1149
+ player.displayName = await this.displayNameForPlayer(player, sender.provider);
1150
+ players.push(player);
1151
+ }
1152
+ groups.push({ label: group.name, ...(group.kind === "resource" ? { capacity: group.capacity } : {}), players });
1153
+ }
1154
+ const [only] = groups;
1155
+ if (wanted && only && !only.players.length) {
1156
+ return only.capacity !== undefined ? `${only.label} ( 0/${only.capacity} )` : `${only.label} ( 0人 )`;
1157
+ }
1158
+ return formatPlayerGroups(groups);
1026
1159
  }
1027
1160
  async listDeviceStates(rawAlias) {
1028
1161
  const alias = cleanText(rawAlias);
@@ -1062,8 +1195,9 @@ ${table.players.map(player => player.name).join("、")}`),
1062
1195
  /* ---------------------------- helpers ---------------------------------- */
1063
1196
  async power(sender, deviceRef, state) {
1064
1197
  const operation = state === "on" ? "启动" : "关闭";
1065
- const staffOverride = state === "off" && this.config.powerCommandsAdminOnly === true;
1066
- if (staffOverride && !matchesPlatformIdentity(this.config.staffUserIds ?? [], sender)) {
1198
+ const config = await this.config();
1199
+ const staffOverride = state === "off" && config.settings.powerOffStaffOnly;
1200
+ if (staffOverride && !this.isStaff(config, sender)) {
1067
1201
  return `${operation}失败,权限不足`;
1068
1202
  }
1069
1203
  try {
@@ -1085,18 +1219,20 @@ ${table.players.map(player => player.name).join("、")}`),
1085
1219
  return `${operation}失败,${powerFailureReason(error)}`;
1086
1220
  }
1087
1221
  }
1222
+ /** Whether the action failed; the message itself is logged, never shown as it is. */
1088
1223
  getCommandFailureMessage(result) {
1089
1224
  const action = result?.action;
1090
- if (action?.status === "expired" || action?.status === "rejected") {
1225
+ // `pending` here is an unanswered request (a timeout): it counts as not done.
1226
+ if (action?.status === "expired" || action?.status === "rejected" || action?.status === "pending") {
1091
1227
  return action.payload?.executorFailure?.message || "命令执行被拒绝或超时";
1092
1228
  }
1093
1229
  return null;
1094
1230
  }
1095
1231
  async resolvePlatformName(subject, provider) {
1096
- if (!this.config.resolveDisplayName)
1232
+ if (!this.options.resolveDisplayName)
1097
1233
  return null;
1098
1234
  try {
1099
- return (await this.config.resolveDisplayName(subject, provider)) ?? null;
1235
+ return (await this.options.resolveDisplayName(subject, provider)) ?? null;
1100
1236
  }
1101
1237
  catch {
1102
1238
  return null;
@@ -1119,50 +1255,6 @@ ${table.players.map(player => player.name).join("、")}`),
1119
1255
  || player.playerId
1120
1256
  || "未知玩家";
1121
1257
  }
1122
- async buildPlayerGroups(players, tableByLabel, provider) {
1123
- const groups = { groups: [] };
1124
- const groupByLabel = new Map();
1125
- const musicLabel = this.config.loginSessionLabel?.trim() || "音游区间";
1126
- for (const player of players.values()) {
1127
- player.displayName = await this.displayNameForPlayer(player, provider);
1128
- const nonMusic = player.sessions.filter((session) => Boolean(session.label) && session.label !== "entry" && session.label !== musicLabel);
1129
- const source = nonMusic.length > 0 ? nonMusic : player.sessions;
1130
- const selected = source.reduce((latest, session) => !latest || sessionStartedAt(session) > sessionStartedAt(latest) ? session : latest, undefined);
1131
- const label = selected?.label === "entry" ? musicLabel : selected?.label || musicLabel;
1132
- let group = groupByLabel.get(label);
1133
- if (!group) {
1134
- group = { label, table: tableByLabel.get(label), players: [] };
1135
- groupByLabel.set(label, group);
1136
- groups.groups.push(group);
1137
- }
1138
- group.players.push(player);
1139
- }
1140
- return groups;
1141
- }
1142
- mergeWaitingSeats(groups) {
1143
- for (const [tableId, state] of this.mahjongTables) {
1144
- const table = uniqueMahjongConfigs(this.mahjongTableConfigs()).find((candidate) => candidate.tableId === tableId);
1145
- if (!table)
1146
- continue;
1147
- const label = mahjongSessionLabel(table);
1148
- let group = groups.groups.find((candidate) => candidate.label === label);
1149
- if (!group) {
1150
- group = { label, table, players: [] };
1151
- groups.groups.push(group);
1152
- }
1153
- for (const seat of state.waiting) {
1154
- if (group.players.some((player) => player.playerId === seat.playerId))
1155
- continue;
1156
- const existing = groups.groups.flatMap((candidate) => candidate.players)
1157
- .find((player) => player.playerId === seat.playerId);
1158
- for (const candidate of groups.groups) {
1159
- if (candidate !== group)
1160
- candidate.players = candidate.players.filter((player) => player.playerId !== seat.playerId);
1161
- }
1162
- group.players.push(existing ?? { playerId: seat.playerId, sessions: [], displayName: seat.displayName });
1163
- }
1164
- }
1165
- }
1166
1258
  async resolvePlayerDisplay(sender, playerId) {
1167
1259
  if (!sender)
1168
1260
  return playerId || "未知玩家";
@@ -1172,67 +1264,13 @@ ${table.players.map(player => player.name).join("、")}`),
1172
1264
  || "未知昵称";
1173
1265
  return `玩家:${name}(${sender.provider}:${sender.id})`;
1174
1266
  }
1175
- mahjongTableForPlayer(playerId) {
1176
- for (const [tableId, state] of this.mahjongTables) {
1177
- if (state.activeSessions[playerId])
1178
- return tableId;
1179
- if (state.waiting.some((seat) => seat.playerId === playerId))
1180
- return tableId;
1181
- }
1182
- return null;
1183
- }
1184
- removeMahjongPlayer(playerId) {
1185
- for (const state of this.mahjongTables.values()) {
1186
- delete state.activeSessions[playerId];
1187
- state.waiting = state.waiting.filter((seat) => seat.playerId !== playerId);
1188
- }
1189
- }
1190
- mahjongTableConfigs() {
1191
- return resolveMahjongTableConfigs(this.config.mahjongTableConfigs ?? []);
1192
- }
1193
- syncMahjongTableStates(sessions) {
1194
- const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
1195
- const tableByLabel = new Map(tables.map((table) => [
1196
- mahjongSessionLabel(table),
1197
- table,
1198
- ]));
1199
- // All playerIds that still have at least one active session in the backend.
1200
- // Used to evict waiting seats for players who have fully checked out externally.
1201
- const allActivePlayerIds = new Set(sessions.map((s) => String(s.playerId ?? "")).filter(Boolean));
1202
- const activeByTable = new Map();
1203
- for (const session of sessions) {
1204
- const table = tableByLabel.get(session.label ?? "");
1205
- const playerId = String(session.playerId ?? "");
1206
- const sessionId = String(session.id ?? "");
1207
- if (!table || !playerId || !sessionId)
1208
- continue;
1209
- const active = activeByTable.get(table.tableId) ?? {};
1210
- active[playerId] = sessionId;
1211
- activeByTable.set(table.tableId, active);
1212
- }
1213
- for (const table of tables) {
1214
- const state = this.mahjongTables.get(table.tableId) ?? { waiting: [], activeSessions: {} };
1215
- state.activeSessions = activeByTable.get(table.tableId) ?? {};
1216
- // Remove seats that have been promoted to active, or whose players have
1217
- // fully left the backend (no entry session remaining — orphan eviction).
1218
- state.waiting = state.waiting.filter((seat) => !state.activeSessions[seat.playerId] && allActivePlayerIds.has(seat.playerId));
1219
- if (state.waiting.length > 0 || Object.keys(state.activeSessions).length > 0 || this.mahjongTables.has(table.tableId)) {
1220
- this.mahjongTables.set(table.tableId, state);
1221
- }
1222
- }
1223
- }
1224
1267
  async resolvePlayer(sender) {
1225
1268
  return (await this.client.resolveOrRegisterIdentity(this.identity(sender)));
1226
1269
  }
1227
- hasEntrySession(playerId, sessions) {
1228
- const label = this.config.loginSessionLabel?.trim();
1229
- return sessions.some((session) => session.playerId === playerId && (session.label === "entry" || (label ? session.label === label : true)));
1230
- }
1231
1270
  identity(sender) {
1232
1271
  return {
1233
1272
  provider: sender.provider,
1234
1273
  subject: sender.id,
1235
- autoRegister: this.config.autoRegister,
1236
1274
  displayName: sender.name || `${sender.provider} ${sender.id}`,
1237
1275
  };
1238
1276
  }
@@ -1247,9 +1285,12 @@ ${table.players.map(player => player.name).join("、")}`),
1247
1285
  return "请在目标平台使用该命令";
1248
1286
  if (!subject)
1249
1287
  return "无法获取目标平台身份";
1250
- const denied = this.targetStaffDenied(actor);
1251
- if (denied)
1252
- return denied;
1288
+ // Acting for another player is for staff, and only when the bot's settings allow it.
1289
+ const config = await this.config();
1290
+ if (!config.settings.staffCommands)
1291
+ return "员工命令未启用";
1292
+ if (!this.isStaff(config, actor))
1293
+ return "权限不足";
1253
1294
  try {
1254
1295
  const user = await bot?.getUser?.(subject);
1255
1296
  return { id: subject, name: user?.name || subject, provider };
@@ -1258,35 +1299,8 @@ ${table.players.map(player => player.name).join("、")}`),
1258
1299
  return { id: subject, name: subject, provider };
1259
1300
  }
1260
1301
  }
1261
- loginSessionBody() {
1262
- const pricingConfigIds = (this.config.loginPricingConfigIds ?? [])
1263
- .map((id) => id.trim())
1264
- .filter(Boolean);
1265
- const label = this.config.loginSessionLabel?.trim();
1266
- return {
1267
- entry: true,
1268
- ...(pricingConfigIds.length === 0 ? {} : { pricingConfigIds }),
1269
- ...(label ? { label } : {}),
1270
- };
1271
- }
1272
- staffDenied(sender) {
1273
- if (!this.config.enableStaffCommands)
1274
- return "员工命令未启用";
1275
- const allowed = this.config.staffUserIds ?? [];
1276
- if (allowed.length > 0 && !matchesPlatformIdentity(allowed, sender))
1277
- return "权限不足";
1278
- return null;
1279
- }
1280
- targetStaffDenied(sender) {
1281
- if (!this.config.enableStaffCommands)
1282
- return "员工命令未启用";
1283
- const allowed = this.config.staffUserIds ?? [];
1284
- if (!matchesPlatformIdentity(allowed, sender))
1285
- return "权限不足";
1286
- return null;
1287
- }
1288
1302
  async formatCheckoutPreview(result, sender, title = "【结算账单】", isPreview) {
1289
- const currency = this.config.currencyName;
1303
+ const currency = (await this.config()).currencyName;
1290
1304
  const preview = result.settlementPreview;
1291
1305
  const playerId = preview.playerId;
1292
1306
  const subtotal = preview.subtotal;
@@ -1313,12 +1327,12 @@ ${table.players.map(player => player.name).join("、")}`),
1313
1327
  const validEnds = sessionPreviews.map(s => s.endedAt || (s.status === "active" ? preview.previewedAt : null)).filter(value => (0, display_time_js_1.parseDateTime)(value));
1314
1328
  if (validStarts.length > 0) {
1315
1329
  const overallStart = validStarts.reduce((a, b) => Date.parse(a) < Date.parse(b) ? a : b);
1316
- const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.config).toISOString();
1330
+ const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.options).toISOString();
1317
1331
  const offsets = [...new Set([(0, display_time_js_1.apiOffsetLabel)(overallStart), (0, display_time_js_1.apiOffsetLabel)(overallEnd)])].join(" / ");
1318
1332
  lines.push(`⏰ 游玩时间:${(0, display_time_js_1.formatHM)(overallStart)}–${(0, display_time_js_1.formatHM)(overallEnd)}(${offsets})`);
1319
1333
  }
1320
1334
  for (const sPrev of sessionPreviews) {
1321
- const label = sPrev?.label === "entry" ? this.config.loginSessionLabel?.trim() || "音游区间" : sPrev?.label || "计时区间";
1335
+ const label = sPrev?.label === "entry" ? DEFAULT_PLAN_LABEL : sPrev?.label || "计时区间";
1322
1336
  const startDt = (0, display_time_js_1.parseDateTime)(sPrev?.startedAt);
1323
1337
  const endDt = sessionDisplayEnd(sPrev, previewedAt);
1324
1338
  const status = sPrev?.status ?? "active";
@@ -1396,8 +1410,9 @@ ${table.players.map(player => player.name).join("、")}`),
1396
1410
  handleCommandError(error) {
1397
1411
  this.logCommandError(error);
1398
1412
  if (error instanceof PrismBotClientError) {
1399
- if (error.code?.startsWith("LOCATION_") && this.config.shopCode && this.config.baseUrl) {
1400
- return `请在网页完成到店校验:${this.config.baseUrl.replace(/\/+$/, "")}/t/${encodeURIComponent(this.config.shopCode)}`;
1413
+ const shopCode = this.options.shopCode ?? this.bot?.shop?.code;
1414
+ if (error.code?.startsWith("LOCATION_") && shopCode && this.options.baseUrl) {
1415
+ return `请在网页完成到店校验:${this.options.baseUrl.replace(/\/+$/, "")}/t/${encodeURIComponent(shopCode)}`;
1401
1416
  }
1402
1417
  return humanReadableBotError(error);
1403
1418
  }
@@ -1416,9 +1431,10 @@ ${table.players.map(player => player.name).join("、")}`),
1416
1431
  function humanReadableBotError(error) {
1417
1432
  if (error.code === "INVALID_PLATFORM_IDENTITY")
1418
1433
  return error.message;
1419
- if (error.code === "DUPLICATE_SESSION_LABEL") {
1420
- return "❌ 您已经处于入场状态,请勿重复发送入场命令。";
1421
- }
1434
+ if (error.code === "BOT_DISABLED")
1435
+ return "Bot 已被店铺停用";
1436
+ if (error.code === "BILLING_DISABLED")
1437
+ return BILLING_DISABLED_NOTICE;
1422
1438
  if (error.code === "PLAYER_HAS_NO_UNSETTLED_SESSIONS") {
1423
1439
  return "您当前没有未结算的账单,无需结账。";
1424
1440
  }
@@ -1456,7 +1472,10 @@ function powerFailureReason(error) {
1456
1472
  return "玩家未入场";
1457
1473
  if (error.code === "PLAYER_IDENTITY_NOT_FOUND")
1458
1474
  return "玩家未注册";
1459
- return "请稍后再试";
1475
+ if (error.code === "BILLING_DISABLED")
1476
+ return BILLING_DISABLED_NOTICE;
1477
+ if (error.code === "DEVICE_NOT_FOUND")
1478
+ return "没有这个设备";
1460
1479
  }
1461
1480
  return "请稍后再试";
1462
1481
  }
@@ -1471,18 +1490,27 @@ function deviceActionFailureReason(error) {
1471
1490
  return "玩家未绑定 Aime 卡";
1472
1491
  if (error.code === "COIN_COMMAND_COOLDOWN_ACTIVE")
1473
1492
  return "投币冷却中,请稍后再试";
1493
+ if (error.code === "BILLING_DISABLED")
1494
+ return BILLING_DISABLED_NOTICE;
1474
1495
  return "请稍后再试";
1475
1496
  }
1497
+ /**
1498
+ * What a player may be told about a device that would not act. Only facts about
1499
+ * the device itself — whether it exists, is connected, is off, answered — never
1500
+ * how the shop configured it or what went wrong inside the platform.
1501
+ */
1502
+ const DEVICE_REASONS = [
1503
+ [/设备不存在|没有找到这个资源/, "没有这个设备"],
1504
+ [/机台未在线|没有在线客户端|设备未连接|直连中继尚未配置/, "设备未连接"],
1505
+ [/设备已关机/, "设备已关机"],
1506
+ [/设备未响应|机台未响应/, "设备没有响应"],
1507
+ ];
1476
1508
  function deviceCommandFailureReason(result) {
1477
1509
  const action = result?.action;
1478
- if (!action || (action.status !== "expired" && action.status !== "rejected"))
1510
+ if (!action || (action.status !== "expired" && action.status !== "rejected" && action.status !== "pending"))
1479
1511
  return null;
1480
1512
  const message = cleanText(action.payload?.executorFailure?.message);
1481
- if (message.includes("没有在线客户端"))
1482
- return "设备未连接";
1483
- if (message.includes("设备配置不存在"))
1484
- return "设备未配置";
1485
- return "请稍后再试";
1513
+ return DEVICE_REASONS.find(([pattern]) => pattern.test(message))?.[1] ?? "操作没有完成,请找店员";
1486
1514
  }
1487
1515
  function deviceCommandLabel(result) {
1488
1516
  return cleanText(result?.action?.payload?.deviceLabel);
@@ -1508,52 +1536,65 @@ function normalizeDeviceState(value) {
1508
1536
  }
1509
1537
  return raw;
1510
1538
  }
1511
- function resolveMahjongTableConfigs(structured) {
1512
- const tables = new Map();
1513
- for (const input of structured) {
1514
- const displayName = cleanText(input.displayName);
1515
- const tableId = displayName;
1516
- const aliases = [...new Set((input.aliases ?? []).map(cleanText).filter(Boolean))];
1517
- const pricingConfigIds = (input.pricingConfigIds ?? []).map(cleanText).filter(Boolean);
1518
- if (!tableId || !displayName || pricingConfigIds.length === 0)
1519
- continue;
1520
- const table = { tableId, displayName, aliases, pricingConfigIds };
1521
- for (const alias of aliases)
1522
- tables.set(alias, table);
1523
- }
1524
- return tables;
1525
- }
1526
- function uniqueMahjongConfigs(tables) {
1527
- return [...new Map([...tables.values()].map((table) => [table.tableId, table])).values()];
1528
- }
1529
- function mahjongSessionLabel(table) {
1530
- return table.displayName;
1539
+ /** The table a player named, by id, name or alias, as the platform matches it. */
1540
+ function findMahjongTable(tables, ref) {
1541
+ const target = ref.trim().toLowerCase();
1542
+ return tables.find((table) => [table.id, table.name, ...table.aliases].some((value) => cleanText(value).toLowerCase() === target)) ?? null;
1531
1543
  }
1532
- function groupSessionsByPlayer(sessions) {
1533
- const players = new Map();
1534
- for (const session of sessions) {
1535
- const playerId = session.playerId || findSubjectForSession(session, "") || "";
1536
- if (!playerId)
1537
- continue;
1538
- const player = players.get(playerId) ?? { playerId, sessions: [] };
1539
- player.sessions.push(session);
1540
- players.set(playerId, player);
1541
- }
1542
- return players;
1544
+ /** The platform's own message for a refusal, when it gave one; never the fallback naming an HTTP status. */
1545
+ function platformMessage(error) {
1546
+ if (error.status < 400 || error.status >= 500)
1547
+ return null;
1548
+ const message = error.body?.error?.message;
1549
+ return typeof message === "string" && message.trim() ? message.trim() : null;
1543
1550
  }
1544
- function sessionStartedAt(session) {
1545
- const value = Date.parse(session.startedAt ?? "");
1546
- return Number.isFinite(value) ? value : 0;
1551
+ /**
1552
+ * The bot's settings as the platform sent them. Anything missing takes the
1553
+ * platform's own default, so a newer setting an older platform lacks does no harm.
1554
+ */
1555
+ function parseBotConfig(value) {
1556
+ const record = (value && typeof value === "object" ? value : {});
1557
+ const settings = (record.settings ?? {});
1558
+ const strings = (list) => (Array.isArray(list) ? list : []).map(cleanText).filter(Boolean);
1559
+ return {
1560
+ bot: { id: cleanText(record.bot?.id), name: cleanText(record.bot?.name) || "Bot" },
1561
+ settings: {
1562
+ playerCommands: settings.playerCommands === "readonly" ? "readonly" : "all",
1563
+ readOnlyNotice: cleanText(settings.readOnlyNotice),
1564
+ staffCommands: settings.staffCommands !== false,
1565
+ powerOffStaffOnly: settings.powerOffStaffOnly === true,
1566
+ receiptsToStaff: settings.receiptsToStaff === true,
1567
+ idleChannelIds: strings(settings.idleChannelIds),
1568
+ idleReminderMinutes: Math.max(0, Number(settings.idleReminderMinutes ?? 5) || 0),
1569
+ },
1570
+ billingEnabled: record.billingEnabled !== false,
1571
+ currencyName: cleanText(record.currencyName) || "余额",
1572
+ staff: (Array.isArray(record.staff) ? record.staff : [])
1573
+ .map((identity) => ({ provider: cleanText(identity?.provider).toLowerCase(), subject: cleanText(identity?.subject) }))
1574
+ .filter((identity) => identity.provider && identity.subject),
1575
+ door: record.door?.id ? { id: cleanText(record.door.id), name: cleanText(record.door.name) } : null,
1576
+ mahjongTables: (Array.isArray(record.mahjongTables) ? record.mahjongTables : [])
1577
+ .filter((table) => cleanText(table?.id))
1578
+ .map((table) => ({
1579
+ id: cleanText(table.id),
1580
+ name: cleanText(table.name) || cleanText(table.id),
1581
+ aliases: strings(table.aliases),
1582
+ capacity: Number(table.capacity) || 4,
1583
+ })),
1584
+ };
1547
1585
  }
1548
- function formatPlayerGroups(groups, tableSize, totalPlayers) {
1549
- const populatedGroups = groups.groups.filter((group) => group.players.length > 0);
1550
- const total = totalPlayers ?? new Set(populatedGroups.flatMap((group) => group.players.map((player) => player.playerId))).size;
1586
+ /** What the shop's default plan is called when the platform gives no plan name. */
1587
+ const DEFAULT_PLAN_LABEL = "入场计费";
1588
+ function formatPlayerGroups(groups) {
1589
+ const populatedGroups = groups.filter((group) => group.players.length > 0);
1590
+ // Each person is in exactly one group.
1591
+ const total = populatedGroups.reduce((sum, group) => sum + group.players.length, 0);
1551
1592
  if (total === 0)
1552
1593
  return "🫥 窝里目前没有玩家呢";
1553
1594
  const lines = [`[总计 ${total} 人]`];
1554
1595
  for (const group of populatedGroups) {
1555
- const heading = group.table
1556
- ? `${group.table.displayName} ( ${group.players.length}/${tableSize} )`
1596
+ const heading = group.capacity !== undefined
1597
+ ? `${group.label} ( ${group.players.length}/${group.capacity} )`
1557
1598
  : `${group.label} ( ${group.players.length}人 )`;
1558
1599
  lines.push(`\n${heading}:\n${formatPlayerNames(group.players)}`);
1559
1600
  }
@@ -1587,11 +1628,6 @@ function formatReleaseVersion(value) {
1587
1628
  const revision = cleanText(record.revision);
1588
1629
  return !revision || revision === "unknown" ? release : `${release} (${revision})`;
1589
1630
  }
1590
- function matchesPlatformIdentity(identities, sender) {
1591
- return identities.includes(`${sender.provider}:${sender.id}`)
1592
- // Legacy unqualified staff lists belong to the original adapter only.
1593
- || (sender.provider === "onebot" && identities.includes(sender.id));
1594
- }
1595
1631
  function formatPlayerReference(sender) {
1596
1632
  const name = sender.name && sender.name !== sender.id ? sender.name : "未知昵称";
1597
1633
  return `${name}(${sender.provider}:${sender.id})`;
@@ -1664,12 +1700,6 @@ function sessionDisplayEnd(session, previewedAt) {
1664
1700
  function now(config) {
1665
1701
  return config?.now ? config.now() : new Date();
1666
1702
  }
1667
- function minDate(dates) {
1668
- return dates.reduce((acc, d) => (d.getTime() < acc.getTime() ? d : acc), dates[0]);
1669
- }
1670
- function maxDate(dates) {
1671
- return dates.reduce((acc, d) => (d.getTime() > acc.getTime() ? d : acc), dates[0]);
1672
- }
1673
1703
  function formatInventoryItem(row) {
1674
1704
  let line = `- ${row.assetName || row.assetCode || "资产"} (x${formatNumber(row.quantity)})`;
1675
1705
  if (row.expiresAt)