dsh-mc-server-ops 0.4.1 → 0.5.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
@@ -66,8 +66,14 @@ dsh plugin add /path/to/dsh-mc-server-ops
66
66
  | `bridge.enabled` | `false` | 是否启用群服互通(游戏聊天 → QQ 群) |
67
67
  | `bridge.mode` | `auto` | `auto` 有玩家在线才转发 / `on` 常开 / `off` 常关 |
68
68
  | `bridge.groups` | `[]` | 转发到哪些群(群 openid) |
69
- | `bridge.events` | `join/leave` 开、`death` 关 | 除聊天外还转发哪些事件 |
70
- | `bridge.coalesceMs` | `3000` | 多条游戏消息合并成一条 QQ 消息的窗口 |
69
+ | `bridge.events` | `join/leave` 关、`death` 开 | 除聊天外还转发哪些事件 |
70
+ | `bridge.coalesceMs` | `3000` | 固定合并窗口(`coalesce.mode=fixed` 时用) |
71
+ | `bridge.coalesce.mode` | `auto` | 合并窗口:`auto` 按最近发言节奏 + 在线人数自动调整 / `fixed` 固定 |
72
+ | `bridge.coalesce.minMs` / `maxMs` | `1000` / `6000` | 自动模式的最短 / 最长等待 |
73
+ | `bridge.coalesce.sampleSize` | `3` | 用最近几条发言算节奏(2–6) |
74
+ | `bridge.coalesce.quietMs` | `20000` | 超过这么久没说话算冷场,直接按最短等待 |
75
+ | `bridge.coalesce.fullPlayers` | `6` | 在线人数达到这个值算「人多」 |
76
+ | `bridge.coalesce.fastMs` | `2000` | 相邻两条发言间隔小于这个值算「话密」 |
71
77
  | `bridge.maxPerDay` | `900` | 每群每天发送上限(官方上限 1000) |
72
78
  | `bridge.appId` / `appSecret` | 空 | 留空自动从本机 qqbot 插件配置读取 |
73
79
 
@@ -80,6 +86,7 @@ dsh-mc-server-ops/
80
86
  └── ops/
81
87
  ├── command-guard.mjs # 静态命令拦截:出网前掐掉“一条命令搞崩整个服”的类型
82
88
  ├── qq-bridge.mjs # 群服互通:读日志 → 直连 QQ 开放平台(不经过 AI)
89
+ ├── coalesce.mjs # 合并窗口计算:最近发言节奏 + 在线人数 → 等多久再发(纯函数)
83
90
  ├── rcon.mjs # 跨平台核心:RCON、进程探测、日志、状态汇总
84
91
  ├── rcon-probe.mjs # 极简 RCON 探测(查在线玩家)
85
92
  ├── adapters/ # 写操作适配器:local(本机脚本)/ panel(Pterodactyl)
@@ -169,14 +176,30 @@ powershell -File <服务器目录>\ops\mcadmin.ps1 -Action owner-add -Arg <openi
169
176
  | `on` | 常开 |
170
177
  | `off` | 常关 |
171
178
 
172
- 转发内容:玩家聊天(始终)、加入 / 离开(默认开)、死亡消息(默认关 —— 文案是本地化的,容易刷屏)。
179
+ 转发内容:玩家聊天(始终)、加入 / 离开(默认关,会刷屏)、死亡消息(默认开)。
180
+
181
+ ### 合并窗口怎么自动调
182
+
183
+ 默认 `auto`:每来一条新消息都重算一次等待时长,两个因子加权——
184
+
185
+ - **最近的发言节奏**(权重 0.6):只用 `quietMs` 内最近 2–3 条发言的相邻间隔。间隔 ≤ `fastMs` 算满活跃,≥ `quietMs` 算冷场,中间线性。
186
+ - **在线人数**(权重 0.4):`在线人数 / fullPlayers`,到满档算 1。
187
+
188
+ 结果夹在 `[minMs, maxMs]`:人少话稀(冷场、单人)基本是 1 秒内就发;人多话密最多攒 6 秒,攒成一条再发。
189
+
190
+ 两个刻意的设计:
191
+
192
+ - **长时间没人说话不会把间隔拖长**:只用「安静窗口内」的相邻间隔算节奏,几小时前的那条发言根本不参与;窗口也没有「距上次发言多久」这类项。
193
+ - **持续刷屏不会无限延后**:等待上限锁在「这一批开始攒」之后的 `maxMs`,到点必发。
194
+
195
+ 状态行会显示当前判定(例如 `合并窗口:2.4s · 活跃度 42% · 最近间隔 3.1s · 在线 2 人`),方便对着调参。
173
196
 
174
197
  实现要点:
175
198
 
176
199
  - **收** — 增量 tail `logs/latest.log`,**按字节切行**(中文是多字节,先转字符串再切会在块边界切坏字),再识别 `<玩家> 内容`、`joined the game`、`left the game`。
177
200
  - **编码** — 服务器的日志是**系统编码**(中文 Windows 上是 GBK),不是 UTF-8。解码器先按 UTF-8 试,出现替换字符 `U+FFFD` 就自动退回 GBK。这一步不做的话,中文在 QQ 里会变成 `��ôţ��`。
178
201
  - **发** — 直接 `POST https://api.bot.qq.com/v2/groups/{openid}/messages`,头是 `Authorization: QQBot <access_token>`;token 用 AppID/AppSecret 换,缓存到过期前 1 分钟。
179
- - **聚合** — `coalesceMs` 窗口内的多条消息合成一条。官方对群主动消息的限制是 **20 条/分钟、每群 1000 条/天**,一条游戏聊天发一条 QQ 会很快撞墙。
202
+ - **聚合** — 多条游戏消息合成一条。默认按「最近发言节奏 + 在线人数」自动定窗口(见上一节),也可以切成固定 `coalesceMs`。官方对群主动消息的限制是 **20 条/分钟、每群 1000 条/天**,一条游戏聊天发一条 QQ 会很快撞墙。
180
203
  - **限流** — `maxPerDay`(默认 900)本地兜底,超了停发,面板状态行会显示原因。
181
204
  - **清洗** — URL 换成 `[链接]`(QQ 会拒收含 URL 的主动消息)、剥掉颜色码 `§x` 和控制字符、单条截断到 900 字。
182
205
  - **防环** — 带 `[群]` / `[QQ]` 前缀的消息不再转发,避免 QQ → 游戏 → QQ 打转。
package/client.js CHANGED
@@ -25,6 +25,7 @@ window.__ModuleLoader__.load({
25
25
  const groupStyle = { border: "1px solid rgba(127,127,127,0.22)", borderRadius: 8, padding: "12px 14px", display: "flex", flexDirection: "column", gap: 12 }
26
26
  const titleStyle = { fontSize: 13, fontWeight: 700, marginBottom: 2 }
27
27
  const buttonStyle = { padding: "6px 14px", borderRadius: 6, border: "1px solid rgba(127,127,127,0.35)", background: "rgba(127,127,127,0.12)", color: "inherit", cursor: "pointer", fontSize: 13 }
28
+ const primaryButtonStyle = { background: "rgba(60,140,255,0.18)", borderColor: "rgba(60,140,255,0.55)", fontWeight: 600 }
28
29
  const statusStyle = { fontSize: 12, opacity: 0.75 }
29
30
 
30
31
  function Field({ label, hint, children }) {
@@ -45,6 +46,24 @@ window.__ModuleLoader__.load({
45
46
  label)
46
47
  }
47
48
 
49
+ function secs(ms) {
50
+ const n = Number(ms)
51
+ return Number.isFinite(n) && n >= 0 ? (n / 1000).toFixed(1) + "s" : "—"
52
+ }
53
+
54
+ // 把桥上报的「当前合并窗口」翻译成一句人话,设置页顶部显示
55
+ function describeCoalesce(c) {
56
+ if (!c) return ""
57
+ if (c.mode === "fixed") {
58
+ return "合并窗口:固定 " + secs(c.waitMs != null ? c.waitMs : c.fixedMs)
59
+ }
60
+ const parts = ["合并窗口:" + (c.waitMs != null ? secs(c.waitMs) : "待定")]
61
+ if (c.score != null) parts.push("活跃度 " + Math.round(c.score * 100) + "%")
62
+ if (c.gapMs != null) parts.push("最近间隔 " + secs(c.gapMs))
63
+ parts.push("在线 " + (c.players || 0) + " 人")
64
+ return parts.join(" · ")
65
+ }
66
+
48
67
  function ConfigPanel() {
49
68
  const [status, setStatus] = react.useState({ loading: true, error: "", saved: "", saving: false })
50
69
  const [form, setForm] = react.useState(null)
@@ -52,7 +71,21 @@ window.__ModuleLoader__.load({
52
71
  const [bridgeState, setBridgeState] = react.useState(null)
53
72
  const [newOwner, setNewOwner] = react.useState("")
54
73
 
55
- react.useEffect(() => { void load() }, [])
74
+ react.useEffect(() => {
75
+ void load()
76
+ // 只刷运行状态(在线人数、当前合并窗口),不动正在编辑的表单
77
+ const timer = setInterval(() => { void refreshState() }, 10000)
78
+ return () => clearInterval(timer)
79
+ }, [])
80
+
81
+ async function refreshState() {
82
+ try {
83
+ const res = await fetch(ENDPOINT, { cache: "no-store", headers: { "x-mc-ops-client": "1" } })
84
+ if (!res.ok) return
85
+ const data = await res.json()
86
+ if (data && data.bridgeState) setBridgeState(data.bridgeState)
87
+ } catch (err) { /* 状态刷不出来不影响编辑 */ }
88
+ }
56
89
 
57
90
  async function load() {
58
91
  try {
@@ -81,11 +114,20 @@ window.__ModuleLoader__.load({
81
114
  appId: (v.bridge || {}).appId || "",
82
115
  appSecret: (v.bridge || {}).appSecret || "",
83
116
  events: {
84
- join: ((v.bridge || {}).events || {}).join !== false,
85
- leave: ((v.bridge || {}).events || {}).leave !== false,
86
- death: ((v.bridge || {}).events || {}).death === true,
117
+ join: ((v.bridge || {}).events || {}).join === true,
118
+ leave: ((v.bridge || {}).events || {}).leave === true,
119
+ death: ((v.bridge || {}).events || {}).death !== false,
87
120
  },
88
121
  coalesceMs: (v.bridge || {}).coalesceMs ?? 3000,
122
+ coalesce: {
123
+ mode: ((v.bridge || {}).coalesce || {}).mode === "fixed" ? "fixed" : "auto",
124
+ minMs: ((v.bridge || {}).coalesce || {}).minMs ?? 1000,
125
+ maxMs: ((v.bridge || {}).coalesce || {}).maxMs ?? 6000,
126
+ sampleSize: ((v.bridge || {}).coalesce || {}).sampleSize ?? 3,
127
+ quietMs: ((v.bridge || {}).coalesce || {}).quietMs ?? 20000,
128
+ fullPlayers: ((v.bridge || {}).coalesce || {}).fullPlayers ?? 6,
129
+ fastMs: ((v.bridge || {}).coalesce || {}).fastMs ?? 2000,
130
+ },
89
131
  maxPerDay: (v.bridge || {}).maxPerDay ?? 900,
90
132
  },
91
133
  vote: {
@@ -135,6 +177,11 @@ window.__ModuleLoader__.load({
135
177
  bridge: Object.assign({}, prev.bridge, { events: Object.assign({}, prev.bridge.events, { [key]: value }) }),
136
178
  }) : prev))
137
179
  }
180
+ function patchBridgeCoalesce(key, value) {
181
+ setForm((prev) => (prev ? Object.assign({}, prev, {
182
+ bridge: Object.assign({}, prev.bridge, { coalesce: Object.assign({}, prev.bridge.coalesce, { [key]: value }) }),
183
+ }) : prev))
184
+ }
138
185
 
139
186
  async function save() {
140
187
  if (!form) return
@@ -147,7 +194,7 @@ window.__ModuleLoader__.load({
147
194
  })
148
195
  const data = await res.json()
149
196
  if (!res.ok) throw new Error(data.error || ("HTTP " + res.status))
150
- setStatus({ loading: false, error: "", saved: "已保存,马上生效", saving: false })
197
+ setStatus({ loading: false, error: "", saved: "已应用,马上生效", saving: false })
151
198
  } catch (err) {
152
199
  setStatus({ loading: false, error: String(err && err.message ? err.message : err), saved: "", saving: false })
153
200
  }
@@ -177,7 +224,17 @@ window.__ModuleLoader__.load({
177
224
  if (status.error && !form) return h("div", { style: { color: "#d9534f", fontSize: 13 } }, "读取失败:" + status.error)
178
225
  if (!form) return null
179
226
 
227
+ // 顶部和底部各放一份,长表单不用滚到底才能应用
228
+ function actions() {
229
+ return h("div", { style: { display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" } },
230
+ h("button", { type: "button", style: Object.assign({}, buttonStyle, primaryButtonStyle), onClick: () => void save(), disabled: status.saving }, status.saving ? "应用中…" : "应用"),
231
+ h("button", { type: "button", style: buttonStyle, onClick: () => void load(), disabled: status.saving }, "重新读取"),
232
+ status.saved ? h("span", { style: Object.assign({}, statusStyle, { color: "#3c9a5f" }) }, status.saved) : null,
233
+ status.error ? h("span", { style: Object.assign({}, statusStyle, { color: "#d9534f" }) }, status.error) : null)
234
+ }
235
+
180
236
  return h("div", { style: box },
237
+ actions(),
181
238
  h("div", null,
182
239
  h("div", { style: titleStyle }, "服主绑定"),
183
240
  h("div", { style: hintStyle }, "填 QQ 号(openid)加服主。不知道自己 ID:在群里 @ 机器人 说「我的 ID 是多少」,它会把你消息开头 [昵称 (ID)] 里那串念给你。"),
@@ -275,11 +332,13 @@ window.__ModuleLoader__.load({
275
332
  ),
276
333
  h("div", { style: groupStyle },
277
334
  bridgeState
278
- ? h("div", { style: Object.assign({}, hintStyle, { color: bridgeState.running ? "#3c9a5f" : "#d9534f" }) },
279
- (bridgeState.running ? "● 运行中" : "○ 未运行")
280
- + " · 在线 " + ((bridgeState.online || []).length) + " 人"
281
- + " · 今日已发 " + (bridgeState.sentToday || 0) + " 条"
282
- + (bridgeState.lastError ? " · ⚠ " + bridgeState.lastError : ""))
335
+ ? h("div", { style: { display: "flex", flexDirection: "column", gap: 3 } },
336
+ h("div", { style: Object.assign({}, hintStyle, { color: bridgeState.running ? "#3c9a5f" : "#d9534f" }) },
337
+ (bridgeState.running ? "● 运行中" : "○ 未运行")
338
+ + " · 在线 " + ((bridgeState.online || []).length) + " 人"
339
+ + " · 今日已发 " + (bridgeState.sentToday || 0) + " 条"
340
+ + (bridgeState.lastError ? " · ⚠ " + bridgeState.lastError : "")),
341
+ bridgeState.coalesce ? h("div", { style: hintStyle }, describeCoalesce(bridgeState.coalesce)) : null)
283
342
  : null,
284
343
  h(Toggle, { label: "启用群服互通", value: form.bridge.enabled, onChange: (x) => patchBridge("enabled", x) }),
285
344
  h(Field, { label: "运行模式", hint: "auto 只有人玩的时候才转发(推荐);on 一直转发;off 完全关闭" },
@@ -289,13 +348,31 @@ window.__ModuleLoader__.load({
289
348
  h("option", { value: "off" }, "常关闭"))),
290
349
  h(Field, { label: "转发到哪些群", hint: "群 openid,逗号分隔。不知道的话在群里 @ 小铜 问" },
291
350
  h(TextInput, { value: form.bridge.groups, placeholder: "FC73DE60… ", onChange: (x) => patchBridge("groups", x) })),
292
- h(Field, { label: "除聊天外还转发", hint: "聊天内容始终转发" },
351
+ h(Field, { label: "除聊天外还转发", hint: "聊天始终转发。进服/退服默认关(会刷屏),死亡消息默认开" },
293
352
  h("div", { style: { display: "flex", gap: 18, flexWrap: "wrap" } },
294
- h(Toggle, { label: "玩家加入", value: form.bridge.events.join, onChange: (x) => patchBridgeEvent("join", x) }),
295
- h(Toggle, { label: "玩家离开", value: form.bridge.events.leave, onChange: (x) => patchBridgeEvent("leave", x) }),
296
- h(Toggle, { label: "死亡消息", value: form.bridge.events.death, onChange: (x) => patchBridgeEvent("death", x) }))),
297
- h(Field, { label: "合并窗口(毫秒)", hint: "这段时间内的多条游戏消息合成一条 QQ 消息,默认 3000" },
298
- h(NumberInput, { value: form.bridge.coalesceMs, onChange: (x) => patchBridge("coalesceMs", x) })),
353
+ h(Toggle, { label: "玩家加入(默认关)", value: form.bridge.events.join, onChange: (x) => patchBridgeEvent("join", x) }),
354
+ h(Toggle, { label: "玩家离开(默认关)", value: form.bridge.events.leave, onChange: (x) => patchBridgeEvent("leave", x) }),
355
+ h(Toggle, { label: "死亡消息(默认开)", value: form.bridge.events.death, onChange: (x) => patchBridgeEvent("death", x) }))),
356
+ h(Field, { label: "合并窗口", hint: "多条游戏消息合成一条再发。自动:人少话稀马上发,人多话密多攒几秒" },
357
+ h("select", { style: inputStyle, value: form.bridge.coalesce.mode, onChange: (e) => patchBridgeCoalesce("mode", e.target.value) },
358
+ h("option", { value: "auto" }, "自动调整(推荐)"),
359
+ h("option", { value: "fixed" }, "固定窗口"))),
360
+ form.bridge.coalesce.mode === "fixed"
361
+ ? h(Field, { label: "固定窗口(毫秒)", hint: "这段时间内的多条消息合成一条,默认 3000" },
362
+ h(NumberInput, { value: form.bridge.coalesceMs, onChange: (x) => patchBridge("coalesceMs", x) }))
363
+ : h("div", { style: { display: "flex", flexDirection: "column", gap: 10 } },
364
+ h(Field, { label: "最短等待(毫秒)", hint: "冷场、人少时按这个来,默认 1000" },
365
+ h(NumberInput, { value: form.bridge.coalesce.minMs, onChange: (x) => patchBridgeCoalesce("minMs", x) })),
366
+ h(Field, { label: "最长等待(毫秒)", hint: "再热闹最多攒这么久就发,默认 6000" },
367
+ h(NumberInput, { value: form.bridge.coalesce.maxMs, onChange: (x) => patchBridgeCoalesce("maxMs", x) })),
368
+ h(Field, { label: "参考最近几条发言", hint: "用最近 2-6 条游戏内发言的间隔算节奏,默认 3" },
369
+ h(NumberInput, { value: form.bridge.coalesce.sampleSize, onChange: (x) => patchBridgeCoalesce("sampleSize", x) })),
370
+ h(Field, { label: "冷场判定(毫秒)", hint: "超过这么久没说话就算冷场,直接按最短等待;半天没人上线也不会把间隔越拖越长。默认 20000" },
371
+ h(NumberInput, { value: form.bridge.coalesce.quietMs, onChange: (x) => patchBridgeCoalesce("quietMs", x) })),
372
+ h(Field, { label: "满档在线人数", hint: "在线人数到这个值算「人多」,默认 6" },
373
+ h(NumberInput, { value: form.bridge.coalesce.fullPlayers, onChange: (x) => patchBridgeCoalesce("fullPlayers", x) })),
374
+ h(Field, { label: "满活跃间隔(毫秒)", hint: "相邻两条发言间隔小于这个值算「话密」,默认 2000" },
375
+ h(NumberInput, { value: form.bridge.coalesce.fastMs, onChange: (x) => patchBridgeCoalesce("fastMs", x) }))),
299
376
  h(Field, { label: "每群每天发送上限", hint: "官方上限 1000 条/天,默认 900 留余量" },
300
377
  h(NumberInput, { value: form.bridge.maxPerDay, onChange: (x) => patchBridge("maxPerDay", x) })),
301
378
  h(Field, { label: "AppID", hint: "留空自动从本机 qqbot 配置读取,一般不用填" },
@@ -318,12 +395,7 @@ window.__ModuleLoader__.load({
318
395
  h(Toggle, { label: "允许玩家游戏内广播(say)", value: form.permissions.say, onChange: (x) => patch("permissions", "say", x) }),
319
396
  h(Toggle, { label: "允许玩家把文件发到群里", value: form.permissions.fileSend, onChange: (x) => patch("permissions", "fileSend", x) }),
320
397
  ),
321
- h("div", { style: { display: "flex", alignItems: "center", gap: 12 } },
322
- h("button", { type: "button", style: buttonStyle, onClick: () => void save(), disabled: status.saving }, status.saving ? "保存中…" : "保存"),
323
- h("button", { type: "button", style: buttonStyle, onClick: () => void load(), disabled: status.saving }, "重新读取"),
324
- status.saved ? h("span", { style: Object.assign({}, statusStyle, { color: "#3c9a5f" }) }, status.saved) : null,
325
- status.error ? h("span", { style: Object.assign({}, statusStyle, { color: "#d9534f" }) }, status.error) : null,
326
- ),
398
+ actions(),
327
399
  )
328
400
  }
329
401
 
package/index.js CHANGED
@@ -272,11 +272,22 @@ export const Config = Schema.object({
272
272
  appId: Schema.string().default('').description('QQ 机器人 AppID;留空自动从本机 qqbot 插件配置里读'),
273
273
  appSecret: Schema.string().default('').description('QQ 机器人 AppSecret;留空自动读'),
274
274
  events: Schema.object({
275
- join: Schema.boolean().default(true).description('转发玩家加入'),
276
- leave: Schema.boolean().default(true).description('转发玩家离开'),
277
- death: Schema.boolean().default(false).description('转发死亡消息(本地化文案,容易刷屏,默认关)'),
275
+ join: Schema.boolean().default(false).description('转发玩家加入(默认关,容易刷屏)'),
276
+ leave: Schema.boolean().default(false).description('转发玩家离开(默认关,容易刷屏)'),
277
+ death: Schema.boolean().default(true).description('转发死亡消息(默认开)'),
278
278
  }).description('除聊天外还要转发哪些事件'),
279
- coalesceMs: Schema.number().default(3000).description('多少毫秒内的多条消息合并成一条 QQ 消息'),
279
+ coalesceMs: Schema.number().default(3000)
280
+ .description('固定合并窗口(毫秒);合并模式选「固定」时用这个值'),
281
+ coalesce: Schema.object({
282
+ mode: Schema.union(['auto', 'fixed']).default('auto')
283
+ .description('合并窗口:auto=按最近发言节奏和在线人数自动调整(默认);fixed=固定用 coalesceMs'),
284
+ minMs: Schema.number().default(1000).description('自动模式最短等待(毫秒),冷场时用'),
285
+ maxMs: Schema.number().default(6000).description('自动模式最长等待(毫秒),最多攒这么久就发'),
286
+ sampleSize: Schema.number().default(3).description('参考最近几条发言算节奏(2-6)'),
287
+ quietMs: Schema.number().default(20000).description('超过这么久没说话就算冷场(毫秒)'),
288
+ fullPlayers: Schema.number().default(6).description('在线人数达到这个值算满档'),
289
+ fastMs: Schema.number().default(2000).description('相邻两条发言间隔小于这个值算满活跃(毫秒)'),
290
+ }).description('合并窗口自动调整:人少话稀就快发,人多话密就多攒一会儿'),
280
291
  maxPerDay: Schema.number().default(900).description('每个群每天最多发几条(官方上限 1000,留余量)'),
281
292
  }).description('群服互通'),
282
293
  })
@@ -341,7 +352,12 @@ export function apply(ctx, config) {
341
352
  panel: Object.assign({ url: '', serverId: '', clientApiKey: '' }, (config && config.panel) || {}),
342
353
  bridge: Object.assign({
343
354
  enabled: false, mode: 'auto', groups: [], appId: '', appSecret: '',
344
- events: { join: true, leave: true, death: false }, coalesceMs: 3000, maxPerDay: 900,
355
+ events: { join: false, leave: false, death: true }, coalesceMs: 3000,
356
+ coalesce: {
357
+ mode: 'auto', minMs: 1000, maxMs: 6000, sampleSize: 3,
358
+ quietMs: 20000, fullPlayers: 6, fastMs: 2000,
359
+ },
360
+ maxPerDay: 900,
345
361
  }, (config && config.bridge) || {}),
346
362
  }
347
363
  const memoryConfig = {
@@ -847,6 +863,8 @@ function readBridgeState() {
847
863
  sentToday: Number(doc.sentToday) || 0,
848
864
  lastError: String(doc.lastError || ''),
849
865
  at: String(doc.at || ''),
866
+ // 自适应合并窗口的当前判定,给设置页显示用
867
+ coalesce: doc.coalesce && typeof doc.coalesce === 'object' ? doc.coalesce : null,
850
868
  }
851
869
  } catch { return null }
852
870
  }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * 合并窗口(coalesce)计算。
3
+ *
4
+ * 目标:人多、话密的时候多攒一会儿再发(少刷屏、省主动消息配额);
5
+ * 人少、话稀的时候尽快发出去(别让一两条消息等半天)。
6
+ *
7
+ * 两个硬约束:
8
+ * 1. 只用「安静窗口内」的相邻两条发言间隔算节奏,长时间没人说话不会被算成“间隔很长”;
9
+ * 2. 结果永远夹在 [minMs, maxMs] 之间,再怎么调也不会出现离奇的超长等待。
10
+ *
11
+ * 纯函数,不碰 IO,方便单独测。
12
+ */
13
+
14
+ export const COALESCE_DEFAULTS = Object.freeze({
15
+ mode: 'auto',
16
+ minMs: 1000,
17
+ maxMs: 6000,
18
+ sampleSize: 3,
19
+ quietMs: 20000,
20
+ fullPlayers: 6,
21
+ fastMs: 2000,
22
+ })
23
+
24
+ /** 自动模式里两个因子各占多少:聊天节奏为主,在线人数为辅。 */
25
+ const CHAT_WEIGHT = 0.6
26
+ const PLAYER_WEIGHT = 0.4
27
+
28
+ const clamp = (value, low, high) => Math.min(high, Math.max(low, value))
29
+
30
+ function num(value, fallback) {
31
+ const n = Number(value)
32
+ return Number.isFinite(n) ? n : fallback
33
+ }
34
+
35
+ /**
36
+ * 把配置里的原始值收敛成一个可用、且自洽的合并配置。
37
+ * @param {object} raw 配置里的 coalesce 对象(可能缺字段、可能是脏数据)
38
+ * @param {number} [legacyFixedMs] 旧版的 bridge.coalesceMs,作为固定窗口的兜底
39
+ */
40
+ export function normalizeCoalesce(raw, legacyFixedMs) {
41
+ const c = raw && typeof raw === 'object' ? raw : {}
42
+ const minMs = clamp(num(c.minMs, COALESCE_DEFAULTS.minMs), 300, 120000)
43
+ const maxMs = clamp(num(c.maxMs, COALESCE_DEFAULTS.maxMs), minMs, 300000)
44
+ return {
45
+ mode: c.mode === 'fixed' ? 'fixed' : 'auto',
46
+ fixedMs: clamp(num(c.fixedMs, num(legacyFixedMs, 3000)), 300, 300000),
47
+ minMs,
48
+ maxMs,
49
+ sampleSize: clamp(Math.round(num(c.sampleSize, COALESCE_DEFAULTS.sampleSize)), 2, 6),
50
+ quietMs: clamp(num(c.quietMs, COALESCE_DEFAULTS.quietMs), 1000, 3600000),
51
+ fullPlayers: clamp(num(c.fullPlayers, COALESCE_DEFAULTS.fullPlayers), 1, 128),
52
+ fastMs: clamp(num(c.fastMs, COALESCE_DEFAULTS.fastMs), 200, 120000),
53
+ }
54
+ }
55
+
56
+ /**
57
+ * 看最近的发言节奏。
58
+ * @param {number[]} recentChatAt 最近几条聊天的接收时间戳(毫秒)
59
+ * @param {number} now 当前时间
60
+ * @returns {{activity:number, gapMs:number|null, samples:number}}
61
+ * activity 0=冷场 1=最快;gapMs 是相邻两条的平均间隔;samples 是真正参与计算的条数。
62
+ */
63
+ export function chatActivity(recentChatAt, now, coalesce) {
64
+ const quietMs = coalesce.quietMs
65
+ const times = (Array.isArray(recentChatAt) ? recentChatAt : [])
66
+ .filter((t) => Number.isFinite(t) && now - t <= quietMs)
67
+ .slice(-coalesce.sampleSize)
68
+ // 一条也算不出间隔,按冷场处理:宁可直接发,也别拖
69
+ if (times.length < 2) return { activity: 0, gapMs: null, samples: times.length }
70
+ const gaps = []
71
+ for (let i = 1; i < times.length; i += 1) gaps.push(times[i] - times[i - 1])
72
+ const gapMs = gaps.reduce((a, b) => a + b, 0) / gaps.length
73
+ // gap <= fastMs 算满活跃,gap >= quietMs 算冷场,中间线性
74
+ const span = Math.max(1, quietMs - coalesce.fastMs)
75
+ const activity = clamp((quietMs - gapMs) / span, 0, 1)
76
+ return { activity, gapMs, samples: times.length }
77
+ }
78
+
79
+ /**
80
+ * 算出这一批消息该等多久再合并发送。
81
+ * @param {{coalesce:object, online?:number, recentChatAt?:number[], now?:number}} input
82
+ * @returns {{waitMs:number, mode:string, activity:number, gapMs:number|null, players:number, score:number}}
83
+ */
84
+ export function computeWaitMs(input) {
85
+ const c = input && input.coalesce ? input.coalesce : normalizeCoalesce()
86
+ const now = Number.isFinite(input && input.now) ? input.now : Date.now()
87
+ const players = Math.max(0, num(input && input.online, 0))
88
+ if (c.mode === 'fixed') {
89
+ return { waitMs: Math.round(c.fixedMs), mode: 'fixed', activity: 0, gapMs: null, players, score: 1 }
90
+ }
91
+ const chat = chatActivity(input && input.recentChatAt, now, c)
92
+ const playerFactor = clamp(players / c.fullPlayers, 0, 1)
93
+ const score = clamp(CHAT_WEIGHT * chat.activity + PLAYER_WEIGHT * playerFactor, 0, 1)
94
+ const waitMs = Math.round(clamp(c.minMs + (c.maxMs - c.minMs) * score, c.minMs, c.maxMs))
95
+ return { waitMs, mode: 'auto', activity: chat.activity, gapMs: chat.gapMs, players, score }
96
+ }
package/ops/qq-bridge.mjs CHANGED
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { closeSync, existsSync, mkdirSync, openSync, readSync, statSync, writeFileSync } from 'node:fs'
13
13
  import { join } from 'node:path'
14
+ import { computeWaitMs, normalizeCoalesce } from './coalesce.mjs'
14
15
 
15
16
  // ─────────────────────────── QQ 开放平台 ───────────────────────────
16
17
 
@@ -149,7 +150,9 @@ export function parseLogLine(line) {
149
150
  hit = /^([A-Za-z0-9_]{1,16}) left the game\.?$/.exec(rest)
150
151
  if (hit) return { type: 'leave', player: hit[1] }
151
152
 
152
- hit = /^([A-Za-z0-9_]{1,16}) (was |drowned|blew up|hit the ground|fell|burned|died|starved|suffocated|withered|killed|slain|walked into|tried to swim|discovered)/.exec(rest)
153
+ // 玩家死亡:原版文案是「<名字> was …」或「<名字> died / drowned / blew up …」。
154
+ // 「was / got」后面排除踢人、封禁这类系统消息,避免误当成死亡刷到群里。
155
+ hit = /^([A-Za-z0-9_]{1,16}) (?:(?:was|got) (?!kicked\b|banned\b|whitelisted\b|muted\b|teleported\b|disconnected\b)|died\b|drowned\b|blew up\b|went up in flames\b|burned\b|froze\b|frozen\b|hit the ground\b|fell\b|starved\b|suffocated\b|withered\b|walked into\b|tried to swim\b|impaled\b|pricked\b|struck\b|doomed\b|squashed\b|obliterated\b|sniped\b|pummelled\b|killed\b|slain\b|shot\b|fireballed\b|poked\b|stung\b)/.exec(rest)
153
156
  if (hit) return { type: 'death', player: hit[1], text: cleanText(rest) }
154
157
 
155
158
  return null
@@ -273,6 +276,10 @@ export function createBridge(deps) {
273
276
  let dayKey = new Date().toISOString().slice(0, 10)
274
277
  let lastError = ''
275
278
  let lastSentAt = ''
279
+ // 自适应合并窗口用:最近几条聊天的到达时间、这一批是什么时候开始攒的、上一次的判定结果
280
+ const recentChatAt = []
281
+ let pendingSince = 0
282
+ let lastWait = null
276
283
  const stats = { chats: 0, joins: 0, leaves: 0, deaths: 0, sent: 0, dropped: 0, suppressed: 0 }
277
284
 
278
285
  function cfg() {
@@ -281,8 +288,9 @@ export function createBridge(deps) {
281
288
  enabled: c.enabled === true,
282
289
  mode: String(c.mode || 'auto'),
283
290
  groups: Array.isArray(c.groups) ? c.groups.map(String).filter(Boolean) : [],
284
- events: Object.assign({ join: true, leave: true, death: false }, c.events || {}),
285
- coalesceMs: Math.max(500, Number(c.coalesceMs) || 3000),
291
+ // 进服/退服默认不转发(会刷屏);死亡消息默认转发
292
+ events: Object.assign({ join: false, leave: false, death: true }, c.events || {}),
293
+ coalesce: normalizeCoalesce(c.coalesce, c.coalesceMs),
286
294
  maxPerDay: Math.max(1, Number(c.maxPerDay) || 900),
287
295
  gamePrefix: String(c.gamePrefix || ''),
288
296
  stripUrls: c.stripUrls !== false,
@@ -302,8 +310,30 @@ export function createBridge(deps) {
302
310
  if (key !== dayKey) { dayKey = key; sentToday = 0 }
303
311
  }
304
312
 
313
+ /**
314
+ * 排下一次合并发送。
315
+ *
316
+ * 每来一条新消息都重算一次:最近聊得越密、在线的人越多,窗口越长;
317
+ * 冷场(quietMs 内没有第二条发言)直接落到 minMs,不会因为“好几小时没人说话”
318
+ * 把间隔算得格外长。窗口上限锁在 pendingSince + maxMs,所以持续刷屏也不会
319
+ * 无限往后拖。
320
+ */
321
+ function schedule(c) {
322
+ if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
323
+ if (!queue.length) return
324
+ const now = Date.now()
325
+ if (!pendingSince) pendingSince = now
326
+ const decision = computeWaitMs({ coalesce: c.coalesce, online: online.size, recentChatAt, now })
327
+ const cap = c.coalesce.mode === 'fixed' ? c.coalesce.fixedMs : c.coalesce.maxMs
328
+ const deadline = Math.min(pendingSince + decision.waitMs, pendingSince + cap)
329
+ lastWait = Object.assign({ at: new Date(now).toISOString(), pendingMs: now - pendingSince }, decision)
330
+ flushTimer = setTimeout(() => { void flush() }, Math.max(0, deadline - now))
331
+ if (flushTimer.unref) flushTimer.unref()
332
+ }
333
+
305
334
  async function flush() {
306
335
  flushTimer = null
336
+ pendingSince = 0
307
337
  const c = cfg()
308
338
  if (!queue.length) return
309
339
  const batch = queue
@@ -344,11 +374,12 @@ export function createBridge(deps) {
344
374
  // 自己发的消息(游戏内回显的 QQ 转发)不该再回环:以 [群] 开头的不转发
345
375
  if (evt.type === 'chat' && /^\[(群|QQ)\]/.test(evt.text)) return
346
376
 
347
- queue.push(evt)
348
- if (!flushTimer) {
349
- flushTimer = setTimeout(() => { void flush() }, c.coalesceMs)
350
- if (flushTimer.unref) flushTimer.unref()
377
+ if (evt.type === 'chat') {
378
+ recentChatAt.push(Date.now())
379
+ if (recentChatAt.length > c.coalesce.sampleSize) recentChatAt.shift()
351
380
  }
381
+ queue.push(evt)
382
+ schedule(c)
352
383
  }
353
384
 
354
385
  async function seedOnline() {
@@ -378,18 +409,36 @@ export function createBridge(deps) {
378
409
  if (tail) tail.stop()
379
410
  if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
380
411
  queue = []
412
+ pendingSince = 0
413
+ recentChatAt.length = 0
381
414
  },
382
415
  isRunning: () => running,
383
416
  status() {
417
+ const c = cfg()
384
418
  return {
385
419
  running,
386
- mode: cfg().mode,
420
+ mode: c.mode,
387
421
  online: [...online],
388
422
  queued: queue.length,
389
423
  sentToday,
390
424
  stats: Object.assign({}, stats),
391
425
  lastError,
392
426
  lastSentAt,
427
+ coalesce: {
428
+ mode: c.coalesce.mode,
429
+ fixedMs: c.coalesce.fixedMs,
430
+ minMs: c.coalesce.minMs,
431
+ maxMs: c.coalesce.maxMs,
432
+ sampleSize: c.coalesce.sampleSize,
433
+ quietMs: c.coalesce.quietMs,
434
+ fullPlayers: c.coalesce.fullPlayers,
435
+ players: online.size,
436
+ pending: queue.length > 0,
437
+ waitMs: lastWait ? lastWait.waitMs : null,
438
+ activity: lastWait ? lastWait.activity : null,
439
+ gapMs: lastWait ? lastWait.gapMs : null,
440
+ score: lastWait ? lastWait.score : null,
441
+ },
393
442
  }
394
443
  },
395
444
  /** 只用于测试/调试:直接喂一条事件 */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mc-server-ops",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "在 DeepSeek Harness 里托管 Minecraft 服务器的插件:状态/启停/日志/白名单/投票授权,静态命令拦截,本地/Pterodactyl 可插拔适配器,游戏聊天直通 QQ 群(不经过 AI、不耗 token),并把人设注入 QQ 会话。需要先安装 QQ 机器人插件。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -23,7 +23,7 @@
23
23
  ],
24
24
  "scripts": {
25
25
  "build": "npm run check",
26
- "check": "node --check index.js && node --check client.js && node --check ops/rcon.mjs && node --check ops/command-guard.mjs && node --check ops/adapters/index.mjs && node --check ops/adapters/local.mjs && node --check ops/adapters/pterodactyl.mjs && node --check ops/qq-bridge.mjs && node --check ops/rcon-probe.mjs",
26
+ "check": "node --check index.js && node --check client.js && node --check ops/coalesce.mjs && node --check ops/rcon.mjs && node --check ops/command-guard.mjs && node --check ops/adapters/index.mjs && node --check ops/adapters/local.mjs && node --check ops/adapters/pterodactyl.mjs && node --check ops/qq-bridge.mjs && node --check ops/rcon-probe.mjs",
27
27
  "prepublishOnly": "npm run check"
28
28
  },
29
29
  "keywords": [