dsh-mc-server-ops 0.5.4 → 0.6.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.
Files changed (4) hide show
  1. package/README.md +28 -8
  2. package/client.js +2 -2
  3. package/index.js +266 -11
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  **在 QQ 群里管理 Minecraft 服务器。** 服主不用开电脑、不用记命令——群里发一句话,就能查状态、启停服务器、绑白名单、投票授权;游戏聊天还能直通 QQ 群,不经过 AI、不耗 token。
9
9
 
10
- > 当前版本 **0.5.2** · 更新于 **2026-11-07** · 以本页和 [npm](https://www.npmjs.com/package/dsh-mc-server-ops) 为准
10
+ > 当前版本 **0.6.0** · 更新于 **2026-11-08** · 以本页和 [npm](https://www.npmjs.com/package/dsh-mc-server-ops) 为准
11
11
 
12
12
  ## 它解决什么问题
13
13
 
@@ -36,7 +36,7 @@
36
36
  - **配方**:`kubejs` 脚本备份 / 重载
37
37
  - **授权**:动受保护区域(world、ops\data、白名单)要 2 位群友投票;**凑满 2 票之前任何人反对就作废**
38
38
  - **人设**:默认「小铜」,名字和语气都能在设置里改
39
- - **游戏内 AI**:装上配套 Forge mod 后,玩家在游戏里 `/ai <内容>` 就能和「小铜」对话(只监听 `127.0.0.1`,按玩家 UUID 复用独立会话)
39
+ - **游戏内 AI**:装上配套 Forge mod 后,玩家在游戏里 `/ai <内容>` 就能和「小铜」对话(只监听 `127.0.0.1`,按玩家 UUID 复用独立会话);mod 1.1.0 起还能带截图/文件附件
40
40
 
41
41
  ## 安装
42
42
 
@@ -61,8 +61,8 @@ dsh plugin add /path/to/dsh-mc-server-ops
61
61
  设置面板最上面有一条更新栏,**强制开启、没有开关**:
62
62
 
63
63
  ```
64
- 当前版本号为 0.5.1 [检查更新]
65
- [新版本 v0.6.0] [检查更新]
64
+ 当前版本号为 0.6.0 [检查更新]
65
+ [新版本 v0.7.0] [检查更新]
66
66
  ```
67
67
 
68
68
  - 面板一打开就自动查一次,**npm 优先**(`registry.npmjs.org/<包名>/latest`),npm 不通才问 GitHub 的 `releases/latest`。
@@ -96,7 +96,7 @@ dsh plugin add /path/to/dsh-mc-server-ops
96
96
  | `vote.protectedPaths` | `world, ops/data, whitelist` | 改动这些位置需要群友投票放行 |
97
97
  | `bridge.enabled` | `true` | 是否启用群服互通(游戏聊天 → QQ 群) |
98
98
  | `bridge.mode` | `auto` | `auto` 有玩家在线才转发 / `on` 常开 / `off` 常关 |
99
- | `bridge.groups` | `[]` | 转发到哪些群(群 openid) |
99
+ | `bridge.groups` | `[]` | 转发到哪些群(群 openid);留空 = 自动用上次记住/最近捕获的群,重装插件不会哑 |
100
100
  | `bridge.events` | 三项都关 | 除聊天外还转发哪些事件(进出服和死亡默认不转,防刷屏) |
101
101
  | `bridge.coalesceMs` | `3000` | 固定合并窗口(`coalesce.mode=fixed` 时用) |
102
102
  | `bridge.coalesce.mode` | `auto` | 合并窗口:`auto` 按最近发言节奏 + 在线人数自动调整 / `fixed` 固定 |
@@ -242,17 +242,33 @@ powershell -File <服务器目录>\ops\mcadmin.ps1 -Action owner-add -Arg <openi
242
242
 
243
243
  群 openid 不知道怎么办:官方没有「列出机器人加入的群」的稳定接口(`/v2/users/@me/groups` 直接 404),只能从一条真实的群消息里抓一次。详细过程写在 [docs/qq-bridge.md](https://github.com/mogutofu/dsh-mc-server-ops/blob/main/docs/qq-bridge.md)。
244
244
 
245
+ 插件会自动记住用过的群:正常转发过一次后,群 openid 会存到 `ops/data/bridge-groups.json`;`bridge.groups` 留空或因为重装插件被重置时,自动用上次记住的群,再退回最近捕获的群(`ops/data/qq-keys.txt`),所以**重装/升级插件不会再让群服互通断掉**。状态和日志里会标出来源(`config` / `remembered` / `captured`)。
246
+
245
247
  ## 游戏内 AI 对话(/ai)
246
248
 
247
- 配套 Forge mod:[mogutofu/dsh-mc-ai-chat](https://github.com/mogutofu/dsh-mc-ai-chat)(服务端 Forge 1.20.1-47.x)。玩家在游戏里输入 `/ai 你好`,mod 会把请求 POST 到本机 `127.0.0.1:8765/mc-ai`,插件开一个 agent 回合,再把回复贴回玩家聊天栏。
249
+ 配套 Forge mod:[mogutofu/dsh-mc-ai-chat](https://github.com/mogutofu/dsh-mc-ai-chat)(服务端 Forge 1.20.1-47.x)。玩家在游戏里输入 `/ai 你好`,mod 会把请求 POST 到本机 `127.0.0.1:8765/mc-ai`,插件开一个 agent 回合,再把回复贴回玩家聊天栏。mod **1.1.0** 起还支持附件:`/ai screenshot` 截游戏画面、`/ai file <路径>` 读玩家本机的文件。
248
250
 
249
251
  | 项 | 说明 |
250
252
  | --- | --- |
251
253
  | 监听 | 只听 `127.0.0.1`,公网进不来;端口默认 8765 |
252
254
  | 会话 | 每个玩家 UUID 一个会话 `mc-ai:<uuid>`,上下文连续;不是本机界面会话,按「群友」权限管 |
253
- | 协议 | `POST /mc-ai`,请求 JSON `{"player":"名字","uuid":"UUID","text":"内容"}` → 回复 `{"ok":true,"reply":"…"}`;HTTP 200 也可能是 `ok:false`,以 `ok` 字段为准 |
255
+ | 协议 | `POST /mc-ai`,请求 JSON `{"player":"名字","uuid":"UUID","text":"内容","attachments":[…]}`(`attachments` 可省略,旧请求完全兼容)→ 回复 `{"ok":true,"reply":"…"}`;HTTP 200 也可能是 `ok:false`,以 `ok` 字段为准 |
256
+ | 附件 | 一次最多 1 个;元素 `{kind:"image"\|"file", name, mediaType, data}`,`data` 必须是**规范 base64**(不能带空白/换行)。图片 `mediaType` 只接受 `image/png` / `image/jpeg` / `image/webp` / `image/gif`,解码后 ≤ 8MB;文件 ≤ 16MB;单次请求总大小 ≤ 24MB |
254
257
  | 配置 | `ai.enabled` / `ai.port` / `ai.timeoutSeconds`,改完立刻生效 |
255
- | 排障 | 回复「(小铜没说话)」通常是 agent 没拿到可用的模型路由:检查 DSH 的默认模型(`agentDefaultModel`)是否指向有效 provider;`<服务器目录>\ops\data\mc-ai.log` 会记录每次请求和真实错误 |
258
+ | 排障 | 回复「(小铜没说话)」通常是 agent 没拿到可用的模型路由:检查 DSH 的默认模型(`agentDefaultModel`)是否指向有效 provider;`<服务器目录>\ops\data\mc-ai.log` 会记录每次请求和真实错误(带附件时还会记概要,如 `[att 1 image/png 230KB]`) |
259
+
260
+ 附件怎么走:
261
+
262
+ - **图片**:mod 把截图/图片读成 base64 发过来 → 插件解码校验后交给 DSH 的 `attachments.saveImages()` 归一化存储 → 消息里放 `{type:"image", attachment:<ref>}`,模型直接看图。所选模型要支持图片输入(默认的 `deepseek-flash` 支持)。
263
+ - **文件**:文本类小文件(≤100KB、UTF-8 可解码)直接把内容**内联**进消息文本块,模型当场就能看到,不依赖 agent 的文件工具;大文件或二进制才存进 DSH 的附件存储(`attachments.saveFile()`)→ 消息里放 `{type:"file", attachment:<ref>}` → DSH 发请求前把文件块投影成一段带**只读保存路径**的文本,agent 需要内容时自己用 `read` 等文件工具去读。
264
+ - **校验失败不建回合**:坏 base64、不支持的图片类型、超过大小限制都返回 HTTP 200 + `{"ok":false,"error":"中文原因"}`,服务不崩;文本请求的行为和旧版一致。
265
+
266
+ **附件安全说明:**
267
+
268
+ - 入口只监听 `127.0.0.1`,外网连不上,能发请求的只有本机的 mod。
269
+ - 附件会**真的落进 DSH home 的附件存储**(默认 `C:\Users\<用户>\.dsh\attachments\v1\`,按内容 sha256 去重),目前**不会自动删除**,时间长了要自己清理。
270
+ - 玩家在游戏里发的截图、本机文件会经 mod 上传给 AI:模型能看到图片内容,agent 能读文件内容(文本类小文件会直接内联进消息发给模型)——让玩家知道自己发的是什么。大文件只会在附件存储里留一份只读副本,不会写回玩家给的路径。
271
+ - 附件请求和文本请求走同一个每玩家串行队列,且 mod 侧默认每玩家 5 秒冷却,不会并发插队刷屏。
256
272
 
257
273
  游戏内玩家和群友一样受权限守卫限制:只读查询可以,写文件、执行命令需要服主授权;mod 侧默认每玩家 5 秒冷却,避免刷屏。
258
274
 
@@ -262,6 +278,7 @@ powershell -File <服务器目录>\ops\mcadmin.ps1 -Action owner-add -Arg <openi
262
278
  - 服主名单在 `owners.json`,只通过本机面板或命令行修改,不经过 QQ 聊天。
263
279
  - 玩家默认只能读文件、跑只读命令;写文件、执行命令、联网下载需要服主授权(`ops.grantHours`)。
264
280
  - 发文件到群里时,`server.properties`、`ops\data\*`、密钥类文件一律拦截。
281
+ - 游戏内 `/ai` 的附件入口只听 `127.0.0.1`,单次最多 1 个,且限制类型和大小(图片 ≤ 8MB、文件 ≤ 16MB、总 ≤ 24MB);附件会存进 DSH home 的 attachments 存储、目前不会自动删除,文件只留只读副本,不写回玩家给的路径。
265
282
  - 设置面板的读写接口要求自定义请求头(浏览器会先发预检),跨站页面伪造不了;只改配置,不碰存档。
266
283
  - `export-data` / `import-data` 仅服主可用;导入时会拒绝含 `..` 或绝对路径的压缩包条目(防 zip slip)。
267
284
  - `cmd`(op/ban/kick 这类后台指令)在插件层就拦下非服主,不依赖脚本再判一次。
@@ -344,6 +361,9 @@ Paper / Spigot / Purpur / Folia / Leaves、Forge / NeoForge / Fabric / Quilt、A
344
361
  **游戏内 /ai 需要什么?**
345
362
  这个插件 + 配套的 Forge mod [dsh-mc-ai-chat](https://github.com/mogutofu/dsh-mc-ai-chat),服务端装 mod 后重启即可。`/ai` 会创建 agent 会话、调用 DSH 的模型,按模型计费;玩家和群友受同一套权限守卫,不能借它绕过服务器管理规则。
346
363
 
364
+ **游戏内 /ai 能发图片和文件吗?**
365
+ 能,需要 mod 1.1.0:`/ai screenshot` 发当前游戏截图,`/ai file <路径>` 发玩家本机文件(1.1.0 一次最多 1 个附件)。图片会直接给模型看,文件落到 DSH 的附件存储后由 agent 自己读取;两条路都按上面的大小/类型限制校验,模型和 agent 因此能看到你发的内容。
366
+
347
367
  ## License
348
368
 
349
369
  MIT
package/client.js CHANGED
@@ -415,8 +415,8 @@ window.__ModuleLoader__.load({
415
415
  h("option", { value: "auto" }, "有玩家时开启(默认)"),
416
416
  h("option", { value: "on" }, "常开启"),
417
417
  h("option", { value: "off" }, "常关闭"))),
418
- h(Field, { label: "转发到哪些群", hint: "群 openid,逗号分隔。不知道的话在群里 @ 小铜 问" },
419
- h(TextInput, { value: form.bridge.groups, placeholder: "FC73DE60… ", onChange: (x) => patchBridge("groups", x) })),
418
+ h(Field, { label: "转发到哪些群", hint: "群 openid,逗号分隔。不知道的话在群里 @ 小铜 问;留空 = 自动用上次记住的群,重装插件不会丢" },
419
+ h(TextInput, { value: form.bridge.groups, placeholder: "留空 = 自动(上次记住的群)", onChange: (x) => patchBridge("groups", x) })),
420
420
  h(Field, { label: "除聊天外还转发", hint: "聊天始终转发。进服/退服默认关(会刷屏),死亡消息默认开" },
421
421
  h("div", { style: { display: "flex", gap: 18, flexWrap: "wrap" } },
422
422
  h(Toggle, { label: "玩家加入(默认关)", value: form.bridge.events.join, onChange: (x) => patchBridgeEvent("join", x) }),
package/index.js CHANGED
@@ -188,7 +188,7 @@ const DESCRIPTION = [
188
188
  '- vote-status:查看投票进度(可带编号)',
189
189
  '- export-data:把 ops\\data(绑定、投票、服主名单、口令)打成 zip,arg 为目标路径,仅服主',
190
190
  '- import-data:从 zip 恢复 ops\\data,arg 为 zip 路径,仅服主',
191
- '- bridge-groups:列出机器人加入的 QQ 群(群名 + 群 openid),配置群服互通时用来填 groups,仅服主',
191
+ '- bridge-groups:列出机器人加入的 QQ 群(群名 + 群 openid),配置群服互通时用来填 groups;QQ 接口列不出来时回退到本地记录/最近捕获的群,仅服主',
192
192
  '',
193
193
  '玩家可以改服务器目录下除敏感区(ops\\data、world、白名单、eula、jar/exe/dll、密钥)之外的文件:kubejs 配方、config/defaultconfigs 配置、server.properties 等,write/edit 直接放行;改之前先备份,改完按需 reload。',
194
194
  '玩家不能改 kubejs 目录以外的任何文件。',
@@ -204,6 +204,124 @@ const DESCRIPTION = [
204
204
  '私聊没有该标记时请让对方到群里操作。权限由脚本按 owners.json 校验,玩家传服主 ID 也会被识别行为日志记录。',
205
205
  ].join('\n')
206
206
 
207
+ // ── /mc-ai 附件(配套 mod 1.1.0)──
208
+ // mod 一次请求最多带 1 个附件;图片只接受这几种 mediaType,大小都按解码后的原始字节算。
209
+ const MC_AI_MAX_ATTACHMENTS = 1
210
+ const MC_AI_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif']
211
+ const MC_AI_IMAGE_MAX_BYTES = 8 * 1024 * 1024
212
+ const MC_AI_FILE_MAX_BYTES = 16 * 1024 * 1024
213
+ const MC_AI_TOTAL_MAX_BYTES = 24 * 1024 * 1024
214
+ // 请求体上限:24MB 原始字节编码成 base64 约 32MB,再留 JSON 和字段名的余量。
215
+ const MC_AI_MAX_BODY_BYTES = 40 * 1024 * 1024
216
+ // 文本类小文件直接内联进消息,不依赖 agent 有没有文件工具;>100KB 或二进制仍走 file 块。
217
+ const MC_AI_INLINE_FILE_MAX_BYTES = 100 * 1024
218
+ const MC_AI_TEXT_EXTENSIONS = new Set([
219
+ 'txt', 'text', 'md', 'markdown', 'json', 'json5', 'yml', 'yaml', 'toml', 'csv', 'tsv', 'log',
220
+ 'java', 'kt', 'kts', 'groovy', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'py', 'rb', 'go', 'rs',
221
+ 'c', 'h', 'cc', 'cpp', 'hpp', 'cs', 'php', 'lua', 'sh', 'bash', 'zsh', 'bat', 'cmd', 'ps1',
222
+ 'cfg', 'conf', 'config', 'properties', 'ini', 'html', 'htm', 'css', 'scss', 'xml', 'sql',
223
+ 'diff', 'patch', 'mcmeta', 'mcfunction', 'snbt',
224
+ ])
225
+
226
+ /** Node 的 base64 解码很宽容:必须重新编码和原文一致,才算规范 base64。 */
227
+ function decodeCanonicalBase64(text) {
228
+ if (typeof text !== 'string' || text.length === 0) return null
229
+ const bytes = Buffer.from(text, 'base64')
230
+ return bytes.toString('base64') === text ? bytes : null
231
+ }
232
+
233
+ /** 文本内容里可打印字符的占比是否够高(二进制文件往往含大量控制字符)。 */
234
+ function looksLikeText(text) {
235
+ if (text.length === 0) return false
236
+ let printable = 0
237
+ for (const ch of text) {
238
+ const code = ch.codePointAt(0)
239
+ if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) continue
240
+ if (code === 0x7f) continue
241
+ printable++
242
+ }
243
+ return printable / text.length >= 0.95
244
+ }
245
+
246
+ /**
247
+ * 文件附件能否内联给模型:≤100KB、UTF-8 严格可解码,且(常见文本扩展名 或 可打印比例高)。
248
+ * 返回内联文本;不能内联返回 null(调用方继续走 file 块 + 路径投影)。
249
+ */
250
+ function inlineFileText(name, bytes) {
251
+ if (bytes.byteLength > MC_AI_INLINE_FILE_MAX_BYTES) return null
252
+ let text = ''
253
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes) } catch { return null }
254
+ const match = /\.([A-Za-z0-9]+)$/.exec(String(name || ''))
255
+ const ext = match ? match[1].toLowerCase() : ''
256
+ // 常见文本扩展名直接内联;其它(比如无扩展名)看内容是不是足够像文本。
257
+ if (MC_AI_TEXT_EXTENSIONS.has(ext)) return text
258
+ return looksLikeText(text) ? text : null
259
+ }
260
+
261
+ /**
262
+ * 校验 /mc-ai 请求里的 attachments。
263
+ * 返回 { ok: true, items: [{ kind, name, mediaType, bytes, inlineText }] } 或 { ok: false, error: '中文原因' };
264
+ * 坏数据 / 未知类型 / 超限都在这里拒掉,不往上冒异常;inlineText 为 null 表示走 file 块。
265
+ */
266
+ function normalizeMcAiAttachments(raw) {
267
+ if (raw === undefined || raw === null) return { ok: true, items: [] }
268
+ if (!Array.isArray(raw)) return { ok: false, error: 'attachments 必须是数组' }
269
+ if (raw.length > MC_AI_MAX_ATTACHMENTS) {
270
+ return { ok: false, error: '当前版本一次最多带 ' + MC_AI_MAX_ATTACHMENTS + ' 个附件' }
271
+ }
272
+ const items = []
273
+ let totalBytes = 0
274
+ for (let i = 0; i < raw.length; i++) {
275
+ const att = raw[i]
276
+ const at = '第 ' + (i + 1) + ' 个附件'
277
+ if (!att || typeof att !== 'object') return { ok: false, error: at + '格式不对' }
278
+ const kind = String(att.kind || '')
279
+ if (kind !== 'image' && kind !== 'file') return { ok: false, error: at + '的 kind 只能是 image 或 file' }
280
+ const isImage = kind === 'image'
281
+ const name = String(att.name || (isImage ? 'image.png' : 'file')).slice(0, 255)
282
+ const mediaType = String(att.mediaType || (isImage ? 'image/png' : 'application/octet-stream')).toLowerCase()
283
+ if (isImage && !MC_AI_IMAGE_MEDIA_TYPES.includes(mediaType)) {
284
+ return { ok: false, error: at + '的图片类型不支持:' + mediaType + '(只接受 png / jpeg / webp / gif)' }
285
+ }
286
+ if (typeof att.data !== 'string' || att.data.length === 0) return { ok: false, error: at + '缺少 data(base64)' }
287
+ const maxBytes = isImage ? MC_AI_IMAGE_MAX_BYTES : MC_AI_FILE_MAX_BYTES
288
+ // 先按 base64 字符串长度粗判,避免超限数据白白解码、占一大块内存。
289
+ if (att.data.length > Math.ceil(maxBytes / 3) * 4 + 8) {
290
+ return { ok: false, error: at + '超过大小上限(' + (maxBytes / 1024 / 1024) + 'MB)' }
291
+ }
292
+ const bytes = decodeCanonicalBase64(att.data)
293
+ if (!bytes) return { ok: false, error: at + '的 data 不是规范 base64' }
294
+ if (bytes.byteLength > maxBytes) {
295
+ return { ok: false, error: at + '超过大小上限(' + (maxBytes / 1024 / 1024) + 'MB)' }
296
+ }
297
+ totalBytes += bytes.byteLength
298
+ if (totalBytes > MC_AI_TOTAL_MAX_BYTES) {
299
+ return { ok: false, error: '附件总大小超过 ' + (MC_AI_TOTAL_MAX_BYTES / 1024 / 1024) + 'MB 上限' }
300
+ }
301
+ items.push({ kind, name, mediaType, bytes, inlineText: kind === 'file' ? inlineFileText(name, bytes) : null })
302
+ }
303
+ return { ok: true, items }
304
+ }
305
+
306
+ /** 附件概要,写进 mc-ai.log,例如 [att 1 image/png 230KB]、[att 1 file/application/octet-stream 1KB inline]。 */
307
+ function describeMcAiAttachments(items) {
308
+ if (!items.length) return ''
309
+ const kinds = items.map((a) => (a.kind === 'image' ? a.mediaType : 'file/' + a.mediaType))
310
+ const total = items.reduce((sum, a) => sum + a.bytes.byteLength, 0)
311
+ const inline = items.some((a) => a.kind === 'file' && a.inlineText !== null) ? ' inline' : ''
312
+ return '[att ' + items.length + ' ' + kinds.join('+') + ' ' + Math.max(1, Math.round(total / 1024)) + 'KB' + inline + ']'
313
+ }
314
+
315
+ /** 把校验过的附件存进 DSH 的 attachments 存储,返回要追加到 user message 的 content 块。 */
316
+ async function storeMcAiAttachment(store, item) {
317
+ if (item.kind === 'image') {
318
+ const refs = await store.saveImages([{ data: item.bytes, mediaType: item.mediaType, name: item.name }])
319
+ return { type: 'image', attachment: refs[0] }
320
+ }
321
+ const ref = await store.saveFile({ data: item.bytes, name: item.name })
322
+ return { type: 'file', attachment: ref }
323
+ }
324
+
207
325
  export const name = 'mc-server-ops'
208
326
  export const inject = ['tools']
209
327
  // 诊断/测试用:判断某个路径是否落在受保护区域,以及临时改一份受保护清单
@@ -604,6 +722,75 @@ export function apply(ctx, config) {
604
722
  panel: (liveConfig && liveConfig.panel) || {},
605
723
  })
606
724
 
725
+ // ── 群服互通的目标群:配置 → 上次记住 → 本地捕获(qq-keys.txt)三层兜底 ──
726
+ // 插件配置存在 profile 的 cordis.patch.yml 里;重装/升级插件时 DSH 会重建这条配置行,
727
+ // 用户填的 bridge.groups 会丢。群 openid 本身可以本地记住,所以这里做持久化 + 自动恢复,
728
+ // 避免「重装一次插件,群服互通就哑了」。
729
+ const BRIDGE_GROUPS_FILE = join(opsDir, 'data', 'bridge-groups.json')
730
+ function readBridgeGroupList(list) {
731
+ return Array.isArray(list) ? list.map((x) => String(x || '').trim()).filter(Boolean) : []
732
+ }
733
+ function rememberBridgeGroups(groups) {
734
+ const list = [...new Set(readBridgeGroupList(groups))]
735
+ if (!list.length) return
736
+ try {
737
+ mkdirSync(join(opsDir, 'data'), { recursive: true })
738
+ writeFileSync(BRIDGE_GROUPS_FILE, JSON.stringify({ at: new Date().toISOString(), groups: list }, null, 2) + '\n', 'utf8')
739
+ } catch (error) { }
740
+ }
741
+ function loadRememberedBridgeGroups() {
742
+ try {
743
+ const doc = JSON.parse(readFileSync(BRIDGE_GROUPS_FILE, 'utf8'))
744
+ return readBridgeGroupList(Array.isArray(doc) ? doc : doc && doc.groups)
745
+ } catch (error) { return [] }
746
+ }
747
+ function loadCapturedBridgeGroups(limit = 3) {
748
+ // qqbot 的 inbound.js 抓到群消息时会把 openid 记进 ops/data/qq-keys.txt(每行「时间 group OPENID」)
749
+ try {
750
+ const text = readFileSync(join(opsDir, 'data', 'qq-keys.txt'), 'utf8')
751
+ const seen = []
752
+ for (const line of text.split(/\r?\n/)) {
753
+ const match = /\bgroup\s+([0-9A-Za-z]{16,64})\b/.exec(line)
754
+ if (!match) continue
755
+ const openid = match[1]
756
+ const index = seen.indexOf(openid)
757
+ if (index !== -1) seen.splice(index, 1)
758
+ seen.push(openid)
759
+ }
760
+ return seen.slice(-limit).reverse()
761
+ } catch (error) { return [] }
762
+ }
763
+ let bridgeGroupsState = { groups: [], source: 'none' }
764
+ let lastBridgeGroupsLog = ''
765
+ function resolveBridgeGroups(rawBridge) {
766
+ const configured = readBridgeGroupList(rawBridge && rawBridge.groups)
767
+ if (configured.length) {
768
+ rememberBridgeGroups(configured)
769
+ bridgeGroupsState = { groups: configured, source: 'config' }
770
+ } else {
771
+ const remembered = loadRememberedBridgeGroups()
772
+ if (remembered.length) {
773
+ bridgeGroupsState = { groups: remembered, source: 'remembered' }
774
+ } else {
775
+ const captured = loadCapturedBridgeGroups()
776
+ if (captured.length) {
777
+ rememberBridgeGroups(captured)
778
+ bridgeGroupsState = { groups: captured, source: 'captured' }
779
+ } else {
780
+ bridgeGroupsState = { groups: [], source: 'none' }
781
+ }
782
+ }
783
+ }
784
+ const key = bridgeGroupsState.source + ':' + bridgeGroupsState.groups.join(',')
785
+ if (key !== lastBridgeGroupsLog) {
786
+ lastBridgeGroupsLog = key
787
+ try {
788
+ appendFileSync(join(opsDir, 'data', 'bridge.log'), new Date().toISOString() + ' [bridge] 群目标:' + (bridgeGroupsState.groups.join(', ') || '(空)') + '(来源:' + bridgeGroupsState.source + ')\n')
789
+ } catch (error) { }
790
+ }
791
+ return bridgeGroupsState
792
+ }
793
+
607
794
  // ── 群服互通:游戏聊天 → QQ 群(不经过 AI,不产生 token)──
608
795
  // 常驻创建、常驻运行:是否真的转发由 liveConfig.bridge.enabled 决定,
609
796
  // 这样在面板里打开开关立刻生效,不用再重启一次。
@@ -616,17 +803,24 @@ export function apply(ctx, config) {
616
803
  serverDir,
617
804
  appId,
618
805
  appSecret,
619
- readConfig: () => (liveConfig && liveConfig.bridge) || {},
806
+ readConfig: () => {
807
+ const raw = (liveConfig && liveConfig.bridge) || {}
808
+ const resolved = resolveBridgeGroups(raw)
809
+ return Object.assign({}, raw, { groups: resolved.groups, groupsSource: resolved.source })
810
+ },
620
811
  log: (m) => {
621
812
  try { appendFileSync(join(opsDir, 'data', 'bridge.log'), new Date().toISOString() + ' ' + m + '\n') } catch { }
622
813
  },
623
814
  })
624
815
  ctx.effect(() => {
816
+ resolveBridgeGroups((liveConfig && liveConfig.bridge) || {})
625
817
  void bridge.start()
626
818
  const tick = setInterval(() => {
819
+ resolveBridgeGroups((liveConfig && liveConfig.bridge) || {})
627
820
  writeBridgeState(serverDir, Object.assign(
628
821
  { appId: appId ? appId.slice(0, 3) + '***' : '', hasSecret: !!appSecret },
629
822
  bridge.status(),
823
+ { groups: bridgeGroupsState.groups, groupsSource: bridgeGroupsState.source },
630
824
  ))
631
825
  }, 10000)
632
826
  if (tick.unref) tick.unref()
@@ -637,6 +831,8 @@ export function apply(ctx, config) {
637
831
  // ── 游戏内 AI 对话:给 Forge mod 的本地 HTTP 入口 ──
638
832
  // 玩家在游戏里 /ai 内容 → mod POST 到 127.0.0.1:<port>/mc-ai → 这里开一个 agent 回合
639
833
  // → 拿回复回给 mod。会话 id 形如 mc-ai:<uuid>,不是本机会话,所以走「群友」权限。
834
+ // mod 1.1.0 起请求还能带 1 个附件:图片存进 DSH 的 attachments 存储后随消息给模型看;
835
+ // 小文本文件直接内联进消息文本,大文件/二进制才落盘,由 DSH 投影成只读路径给 agent 读。
640
836
  const aiCfg = Object.assign({ enabled: true, port: 8765, timeoutSeconds: 60 }, (liveConfig && liveConfig.ai) || {})
641
837
  if (aiCfg.enabled) {
642
838
  const aiSessions = new Map()
@@ -645,7 +841,7 @@ export function apply(ctx, config) {
645
841
  try { appendFileSync(join(opsDir, 'data', 'mc-ai.log'), new Date().toISOString() + ' ' + m + '\n') } catch { }
646
842
  }
647
843
 
648
- const askAgent = async (key, text) => {
844
+ const askAgent = async (key, text, attachmentItems = []) => {
649
845
  const agents = ctx.get('agents')
650
846
  if (!agents || typeof agents.create !== 'function') throw new Error('DSH 没有可用的 agents 服务')
651
847
  let agent = aiSessions.get(key)
@@ -679,20 +875,47 @@ export function apply(ctx, config) {
679
875
  }
680
876
  }
681
877
  }
878
+ // 附件组装:图片块给模型直接看;小文本文件直接内联成 text 块(不依赖 agent 的文件工具);
879
+ // 超过 100KB 或二进制的文件才落进 DSH 的 attachments 存储,靠 file 块的只读路径投影给 agent 读。
880
+ const content = [{ type: 'text', text }]
881
+ if (attachmentItems.length) {
882
+ let store = null
883
+ for (const item of attachmentItems) {
884
+ if (item.kind === 'file' && item.inlineText !== null) {
885
+ content.push({
886
+ type: 'text',
887
+ text: '--- 附件:' + item.name + '(' + item.bytes.byteLength + ' 字节,已内联)---\n'
888
+ + item.inlineText + '\n--- 附件结束 ---',
889
+ })
890
+ continue
891
+ }
892
+ if (!store) {
893
+ store = ctx.get('attachments')
894
+ if (!store || typeof store.saveImages !== 'function' || typeof store.saveFile !== 'function') {
895
+ throw new Error('DSH 没有可用的 attachments 服务')
896
+ }
897
+ }
898
+ try {
899
+ content.push(await storeMcAiAttachment(store, item))
900
+ } catch (error) {
901
+ throw new Error('附件保存失败:' + (error && error.message ? error.message : String(error)))
902
+ }
903
+ }
904
+ }
682
905
  const timeoutMs = Math.max(5, Number(aiCfg.timeoutSeconds) || 60) * 1000
683
906
  // 优先用 DSH 自己的构造函数,拿不到就手搓一个同形状的消息
684
907
  let message = null
685
908
  try {
686
909
  const llm = await import('@deepseek-ai/dsh-llm')
687
910
  if (llm && typeof llm.createUserMessage === 'function') {
688
- message = llm.createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
911
+ message = llm.createUserMessage({ content, source: { kind: 'user' } })
689
912
  }
690
913
  } catch { /* 拿不到就退回手搓 */ }
691
914
  if (!message) {
692
915
  message = {
693
916
  id: 'mcai-' + randomUUID(),
694
917
  role: 'user',
695
- content: [{ type: 'text', text }],
918
+ content,
696
919
  source: { kind: 'user' },
697
920
  time: Date.now(),
698
921
  }
@@ -761,25 +984,47 @@ export function apply(ctx, config) {
761
984
  return send(404, { ok: false, error: 'not found' })
762
985
  }
763
986
  const chunks = []
764
- req.on('data', (c) => chunks.push(Buffer.from(c)))
987
+ let bodyBytes = 0
988
+ let bodyTooBig = false
989
+ req.on('data', (c) => {
990
+ if (bodyTooBig) return
991
+ bodyBytes += c.length
992
+ if (bodyBytes > MC_AI_MAX_BODY_BYTES) {
993
+ // 超限的请求体直接丢弃,按合约回 JSON(200 + ok:false),连接不炸。
994
+ bodyTooBig = true
995
+ chunks.length = 0
996
+ return
997
+ }
998
+ chunks.push(Buffer.from(c))
999
+ })
765
1000
  req.on('end', () => {
1001
+ if (bodyTooBig) return send(200, { ok: false, error: '请求体太大(附件总大小上限 ' + (MC_AI_TOTAL_MAX_BYTES / 1024 / 1024) + 'MB)' })
766
1002
  let body = null
767
1003
  try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') } catch { body = null }
768
1004
  if (!body) return send(400, { ok: false, error: '请求体不是合法 JSON' })
769
1005
  const player = String(body.player || '').slice(0, 32)
770
1006
  const uuid = String(body.uuid || player).slice(0, 64)
771
1007
  const text = String(body.text || '').trim().slice(0, 1000)
772
- if (!text) return send(400, { ok: false, error: '内容不能为空' })
1008
+ // 附件先整体校验:坏 base64 / 未知媒体类型 / 超限都在开 agent 回合之前拒掉,
1009
+ // 不让异常冒到服务外面。校验通过后再在队列里落盘、组消息。
1010
+ const attachmentResult = normalizeMcAiAttachments(body.attachments)
1011
+ if (!attachmentResult.ok) {
1012
+ aiLog('[ai] ' + (player || '?') + ' 附件被拒:' + attachmentResult.error)
1013
+ return send(200, { ok: false, error: attachmentResult.error })
1014
+ }
1015
+ const attachmentItems = attachmentResult.items
1016
+ if (!text && !attachmentItems.length) return send(400, { ok: false, error: '内容不能为空' })
1017
+ const attSummary = describeMcAiAttachments(attachmentItems)
773
1018
  const key = 'mc-ai:' + (uuid || player)
774
1019
  const startedAt = Date.now()
775
1020
  enqueue(key, async () => {
776
1021
  try {
777
- const reply = await askAgent(key, text)
778
- aiLog('[ai] ' + player + ' → ' + text.slice(0, 60) + ' ⇒ ' + String(reply || '').slice(0, 60))
1022
+ const reply = await askAgent(key, text, attachmentItems)
1023
+ aiLog('[ai] ' + player + ' → ' + text.slice(0, 60) + (attSummary ? ' ' + attSummary : '') + ' ⇒ ' + String(reply || '').slice(0, 60))
779
1024
  send(200, { ok: true, reply: reply || '(小铜没说话)', elapsedMs: Date.now() - startedAt })
780
1025
  } catch (error) {
781
1026
  const message = error && error.message ? error.message : String(error)
782
- aiLog('[ai] ' + player + ' 失败:' + message)
1027
+ aiLog('[ai] ' + player + (attSummary ? ' ' + attSummary : '') + ' 失败:' + message)
783
1028
  send(200, { ok: false, error: message })
784
1029
  }
785
1030
  })
@@ -896,10 +1141,20 @@ export function apply(ctx, config) {
896
1141
  try {
897
1142
  const groups = await new QqApi({ appId, appSecret }).listGroups()
898
1143
  if (!groups.length) return { ok: true, text: '机器人还没加入任何群(或者没有「群管理」权限,拿不到群列表)。' }
1144
+ rememberBridgeGroups(groups.map((g) => g.openid))
899
1145
  return { ok: true, text: groups.map((g) => g.name + '\n ' + g.openid).join('\n') }
900
1146
  } catch (error) {
901
1147
  const message = error && error.message ? error.message : String(error)
902
- return { ok: false, text: '查群列表失败:' + message + '\n(需要 AppID/AppSecret,以及开放平台的「群管理」权限)' }
1148
+ const local = [...new Set([...loadRememberedBridgeGroups(), ...loadCapturedBridgeGroups()])]
1149
+ if (local.length) {
1150
+ return {
1151
+ ok: true,
1152
+ text: 'QQ 接口不支持直接列群(' + message + '),改用本地记录到的群 openid:\n'
1153
+ + local.join('\n')
1154
+ + '\n\n填到「群服互通 → 转发到哪些群」即可;留空也会自动用这些群。',
1155
+ }
1156
+ }
1157
+ return { ok: false, text: '查群列表失败:' + message + '\n(需要 AppID/AppSecret,以及开放平台的「群管理」权限;也可以让群友在群里 @ 一次机器人来捕获群 openid)' }
903
1158
  }
904
1159
  }
905
1160
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mc-server-ops",
3
- "version": "0.5.4",
3
+ "version": "0.6.1",
4
4
  "description": "在 DeepSeek Harness 里托管 Minecraft 服务器的插件:状态/启停/日志/白名单/投票授权,静态命令拦截,本地/Pterodactyl 可插拔适配器,游戏聊天直通 QQ 群(不经过 AI、不耗 token),把人设注入 QQ 会话,并让游戏内玩家用 /ai 和「小铜」对话(配套 Forge mod)。需要先安装 QQ 机器人插件。",
5
5
  "type": "module",
6
6
  "main": "./index.js",