@napuketto/adapter 0.16.2 → 0.17.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.
Files changed (56) hide show
  1. package/dist/{essence-Gnvq6YWT.mjs → buddy-req-BvAxJo6d.mjs} +94 -85
  2. package/dist/buddy-req-BvAxJo6d.mjs.map +1 -0
  3. package/dist/core/index.d.mts +5 -2
  4. package/dist/core/index.mjs +1 -1
  5. package/dist/{core-D5c78lFV.mjs → core-D8sq68iP.mjs} +65 -5
  6. package/dist/core-D8sq68iP.mjs.map +1 -0
  7. package/dist/gray-tip-DNo_Mi4E.d.mts.map +1 -1
  8. package/dist/gray-tip-DmZmdtjP.mjs +214 -0
  9. package/dist/gray-tip-DmZmdtjP.mjs.map +1 -0
  10. package/dist/index-B-HpCes-.d.mts +820 -0
  11. package/dist/index-B-HpCes-.d.mts.map +1 -0
  12. package/dist/index-CepyMhuM.d.mts +701 -0
  13. package/dist/index-CepyMhuM.d.mts.map +1 -0
  14. package/dist/index-DBD-IZKn.d.mts +808 -0
  15. package/dist/index-DBD-IZKn.d.mts.map +1 -0
  16. package/dist/{index-Dhd-kaUF.d.mts → index-DBjlR2dn.d.mts} +36 -6
  17. package/dist/index-DBjlR2dn.d.mts.map +1 -0
  18. package/dist/index-dsurF2t_.d.mts +435 -0
  19. package/dist/index-dsurF2t_.d.mts.map +1 -0
  20. package/dist/index.d.mts +23 -1
  21. package/dist/index.mjs +6 -1
  22. package/dist/kurobot/index.d.mts +2 -812
  23. package/dist/kurobot/index.mjs +1 -1125
  24. package/dist/kurobot-cMBAVX3L.mjs +1126 -0
  25. package/dist/kurobot-cMBAVX3L.mjs.map +1 -0
  26. package/dist/milky/index.d.mts +5 -206
  27. package/dist/milky/index.mjs +1 -3363
  28. package/dist/milky-CYAOJLv_.mjs +3323 -0
  29. package/dist/milky-CYAOJLv_.mjs.map +1 -0
  30. package/dist/onebot11/index.d.mts +2 -805
  31. package/dist/onebot11/index.mjs +1 -3929
  32. package/dist/onebot11-BikYDo3k.mjs +3900 -0
  33. package/dist/onebot11-BikYDo3k.mjs.map +1 -0
  34. package/dist/{raw-message-Cz0UOrND.mjs → raw-message-D5nMIebz.mjs} +3 -3
  35. package/dist/raw-message-D5nMIebz.mjs.map +1 -0
  36. package/dist/satori/index.d.mts +2 -433
  37. package/dist/satori/index.mjs +1 -1747
  38. package/dist/satori-Cb2uM3PY.mjs +1754 -0
  39. package/dist/satori-Cb2uM3PY.mjs.map +1 -0
  40. package/package.json +4 -4
  41. package/dist/core-D5c78lFV.mjs.map +0 -1
  42. package/dist/essence-Gnvq6YWT.mjs.map +0 -1
  43. package/dist/index-Dhd-kaUF.d.mts.map +0 -1
  44. package/dist/kurobot/index.d.mts.map +0 -1
  45. package/dist/kurobot/index.mjs.map +0 -1
  46. package/dist/log-BznNQnpx.mjs +0 -80
  47. package/dist/log-BznNQnpx.mjs.map +0 -1
  48. package/dist/media-DMMn74TC.mjs +0 -126
  49. package/dist/media-DMMn74TC.mjs.map +0 -1
  50. package/dist/milky/index.d.mts.map +0 -1
  51. package/dist/milky/index.mjs.map +0 -1
  52. package/dist/onebot11/index.d.mts.map +0 -1
  53. package/dist/onebot11/index.mjs.map +0 -1
  54. package/dist/raw-message-Cz0UOrND.mjs.map +0 -1
  55. package/dist/satori/index.d.mts.map +0 -1
  56. package/dist/satori/index.mjs.map +0 -1
@@ -1,3363 +1 @@
1
- import { i as runAction, n as BaseProtocolAdapter, r as ActionRegistry } from "../core-D5c78lFV.mjs";
2
- import { a as firstNonEmptyString, c as MS_TO_SEC, d as toUin, i as toUnixSeconds, l as numericUin, o as stringOrUndefined, r as subscribeRawMessages, s as startupBaselineSec, t as forEachRawMessage, u as resolveUin } from "../raw-message-Cz0UOrND.mjs";
3
- import { a as findRevokeElement, i as collectGrayTipUids, n as sliceRaw, o as firstUntranslatedGrayTip, s as hasGrayTip, t as logEventFailure } from "../log-BznNQnpx.mjs";
4
- import { a as nodeAt, c as textOf, d as BuddyReqDedup, f as batchUnreadNums, i as narrowSysMsgBlobs, l as varintAt, m as narrowBuddyReqs, n as extractEssenceSetSysMsg, o as processSysMsgBlob, p as filterBuddyReqs, r as narrowEssenceGroupArg, s as recognizeSysMsg, t as EssenceListSync, u as varintOf } from "../essence-Gnvq6YWT.mjs";
5
- import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, kernelError, toCanonicalElements } from "@napuketto/kernel";
6
- import { z } from "zod";
7
- import { randomUUID } from "node:crypto";
8
- import { join } from "node:path";
9
- import { detectFileType, downloadUrl, inferExtension } from "@napuketto/media";
10
- import { mkdir, rename, writeFile } from "node:fs/promises";
11
- import { fileURLToPath } from "node:url";
12
- import { HttpClient, HttpServer, createSseResponse, isWsOpen } from "@napuketto/network";
13
- // src/milky/action/base-action.ts
14
- /** KernelErrorCode → Milky retcode 映射表(-400/-403 规范语义,其余取常见 HTTP 语义近似负数)。 */
15
- const milkyErrorCodeMap = {
16
- SEND_FAILED: -500,
17
- PERMISSION_DENIED: -405,
18
- NOT_FOUND: -404,
19
- TIMEOUT: -504,
20
- NOT_LOGIN: -403,
21
- INVALID_PARAM: -400,
22
- INVALID_STATE: -409,
23
- UNKNOWN: -500
24
- };
25
- /** zod 错误摘要(单行,issues 取前 3 条)。 */
26
- function zodSummary(error) {
27
- const parts = [];
28
- for (const issue of error.issues.slice(0, 3)) parts.push(`${issue.path.map(String).join(".")}: ${issue.message}`);
29
- return parts.join("; ");
30
- }
31
- /** 声明式动作工厂:闭包依赖 + 统一信封与错误映射。 */
32
- function defineMilkyAction(spec) {
33
- return {
34
- name: spec.name,
35
- schema: spec.schema,
36
- handle: async (payload) => {
37
- const outcome = await runAction({
38
- schema: spec.schema,
39
- handle: spec.handle,
40
- errorCodeMap: milkyErrorCodeMap,
41
- invalidRetcode: -400,
42
- invalidMessage: (error) => `参数解析失败: ${zodSummary(error)}`
43
- }, payload);
44
- return outcome.ok ? {
45
- status: "ok",
46
- retcode: 0,
47
- data: outcome.data,
48
- message: ""
49
- } : {
50
- status: "failed",
51
- retcode: outcome.retcode,
52
- data: null,
53
- message: outcome.message
54
- };
55
- }
56
- };
57
- }
58
- // src/milky/helper/message/entities.ts
59
- /** GroupDetailInfo / Group → GroupEntity(detail 缺失时全兜底)。 */
60
- function toGroupEntity(detail, groupCode) {
61
- return {
62
- group_id: Number(groupCode),
63
- group_name: detail?.groupName ?? "",
64
- member_count: detail?.memberNum ?? 0,
65
- max_member_count: detail?.maxMemberNum ?? 0,
66
- remark: detail?.remarkName ?? "",
67
- created_time: detail?.groupCreateTime ?? 0,
68
- description: "",
69
- question: "",
70
- announcement: ""
71
- };
72
- }
73
- /** 群列表项(GroupCache Group)→ GroupEntity。 */
74
- function groupListToEntity(group) {
75
- return {
76
- group_id: Number(group.groupCode),
77
- group_name: group.groupName,
78
- member_count: group.memberCount,
79
- max_member_count: group.maxMember,
80
- remark: "",
81
- created_time: 0,
82
- description: "",
83
- question: "",
84
- announcement: ""
85
- };
86
- }
87
- /** GroupMember → GroupMemberEntity(member 缺失时按 uin 兜底最小实体)。 */
88
- function toGroupMemberEntity(member, groupCode, uin) {
89
- const shutUpSeconds = member?.shutUpTime ?? 0;
90
- return {
91
- user_id: Number(member?.uin !== void 0 && member.uin !== "" ? member.uin : uin),
92
- nickname: member?.nick ?? "",
93
- sex: "unknown",
94
- group_id: Number(groupCode),
95
- card: member?.cardName ?? "",
96
- title: member?.memberSpecialTitle ?? "",
97
- level: 0,
98
- role: GroupApi.roleToString(member?.role ?? 2),
99
- join_time: Number(member?.joinTime) || 0,
100
- last_sent_time: Number(member?.lastSpeakTime) || 0,
101
- shut_up_end_time: shutUpSeconds > 0 ? Math.floor(Date.now() / 1e3) + shutUpSeconds : null
102
- };
103
- }
104
- /** Friend → FriendEntity(kernel 无 qid/分类挂载,按最小实体兜底)。 */
105
- function toFriendEntity(friend, uin, nick) {
106
- return {
107
- user_id: Number(friend?.uin !== void 0 && friend.uin !== "" ? friend.uin : uin),
108
- nickname: friend?.nickname ?? nick,
109
- sex: "unknown",
110
- qid: "",
111
- remark: friend?.remark ?? "",
112
- category: {
113
- category_id: 0,
114
- category_name: ""
115
- }
116
- };
117
- }
118
- // src/milky/action/group-query.ts
119
- /** 群域共入参(群号 / 成员 uin / 可选布尔;群管理 / 通知 / 精华 / 文件域复用)。 */
120
- const groupIdField = { group_id: z.number().int().min(10001) };
121
- const userIdField = { user_id: z.number().int().min(10001) };
122
- const optBool$1 = z.boolean().nullable().optional();
123
- /** 群查询域动作工厂(群信息 / 成员列表 / 成员单查 / 公告列表)。 */
124
- function createGroupQueryActions(api) {
125
- return [
126
- defineMilkyAction({
127
- name: "get_group_info",
128
- schema: z.object({
129
- ...groupIdField,
130
- no_cache: optBool$1
131
- }),
132
- handle: async (payload) => {
133
- const groupCode = String(payload.group_id);
134
- return { group: toGroupEntity(api.groupCache !== void 0 ? await api.groupCache.getGroupDetail(groupCode) : await api.groupApi.getGroupInfo(groupCode), groupCode) };
135
- }
136
- }),
137
- defineMilkyAction({
138
- name: "get_group_member_list",
139
- schema: z.object({
140
- ...groupIdField,
141
- no_cache: optBool$1
142
- }),
143
- handle: async (payload) => {
144
- return { members: (await membersOf(api, String(payload.group_id))).map((m) => toGroupMemberEntity(m, String(payload.group_id), m.uin)) };
145
- }
146
- }),
147
- defineMilkyAction({
148
- name: "get_group_member_info",
149
- schema: z.object({
150
- ...groupIdField,
151
- ...userIdField,
152
- no_cache: optBool$1
153
- }),
154
- handle: async (payload) => {
155
- return { member: toGroupMemberEntity(await memberOf(api, payload.group_id, payload.user_id), String(payload.group_id), String(payload.user_id)) };
156
- }
157
- }),
158
- defineMilkyAction({
159
- name: "get_group_announcements",
160
- schema: z.object({ ...groupIdField }),
161
- handle: async (payload) => {
162
- const groupCode = String(payload.group_id);
163
- const bulletins = await api.groupApi.getGroupAnnouncements(groupCode);
164
- return { announcements: await Promise.all(bulletins.map((b) => bulletinToEntity(b, payload.group_id, api))) };
165
- }
166
- })
167
- ];
168
- }
169
- /** ---------- 内部辅助 ---------- */
170
- /** 成员列表(GroupCache 优先,未装配直查)。 */
171
- async function membersOf(api, groupCode) {
172
- if (api.groupCache !== void 0) return await api.groupCache.getMembers(groupCode);
173
- return await api.groupApi.getGroupMemberList(groupCode, true);
174
- }
175
- /** 成员单查(user_id = uin;缓存路径经 uid,直查路径按 uin 匹配)。 */
176
- async function memberOf(api, groupId, userId) {
177
- const groupCode = String(groupId);
178
- const uin = String(userId);
179
- if (api.groupCache !== void 0) {
180
- const uid = await api.resolveUidFromUin(userId).catch((err) => {
181
- api.logger?.debug({
182
- group: groupCode,
183
- uin,
184
- error: err instanceof Error ? err.message : String(err)
185
- }, "milky: 成员 uin→uid 失败,退用 uin 查缓存");
186
- return uin;
187
- });
188
- const member = await api.groupCache.getMember(groupCode, uid);
189
- if (member === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
190
- return member;
191
- }
192
- const hit = (await api.groupApi.getGroupMemberList(groupCode, true)).find((m) => m.uin === uin);
193
- if (hit === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
194
- return hit;
195
- }
196
- /** GroupBulletin → 群公告实体(senderUid → uin 反查;无源字段兜底,待校准)。 */
197
- async function bulletinToEntity(b, groupId, api) {
198
- return {
199
- group_id: groupId,
200
- announcement_id: b.announcementId ?? "",
201
- user_id: await senderUinOf(b, api),
202
- time: Number(b.publishTime) || 0,
203
- content: b.content ?? "",
204
- image_url: picUrlOf(b)
205
- };
206
- }
207
- /** 公告发送者 uid → uin(缺省/转换失败 0 兜底)。 */
208
- async function senderUinOf(b, api) {
209
- const uid = b.senderUid;
210
- if (typeof uid !== "string" || uid === "") return 0;
211
- const uins = await api.uidToUin([uid]).catch((err) => {
212
- api.logger?.debug({
213
- uid,
214
- error: err instanceof Error ? err.message : String(err)
215
- }, "milky: 公告发送者 uid→uin 失败,兜底 0");
216
- });
217
- return Number(uins?.get(uid)) || 0;
218
- }
219
- /** 公告图片 url(缺省 null)。 */
220
- function picUrlOf(b) {
221
- const url = b.pic?.url;
222
- return typeof url === "string" && url !== "" ? url : null;
223
- }
224
- // src/milky/action/group-essence.ts
225
- /** 群精华与表态域动作工厂。 */
226
- function createGroupEssenceActions(api) {
227
- return [
228
- defineMilkyAction({
229
- name: "get_group_essence_messages",
230
- schema: z.object({
231
- ...groupIdField,
232
- page_index: z.number().int().min(0),
233
- page_size: z.number().int().min(0)
234
- }),
235
- handle: async (payload) => {
236
- const items = await api.webApi.getEssenceMsgList(String(payload.group_id));
237
- const start = payload.page_index * payload.page_size;
238
- const page = items.slice(start, start + payload.page_size);
239
- return {
240
- messages: page.map((item) => essenceToEntity(item, payload.group_id)),
241
- is_end: start + page.length >= items.length
242
- };
243
- }
244
- }),
245
- defineMilkyAction({
246
- name: "set_group_essence_message",
247
- schema: z.object({
248
- ...groupIdField,
249
- message_seq: z.number().int().min(0),
250
- is_set: optBool$1
251
- }),
252
- handle: async (payload) => {
253
- const groupCode = String(payload.group_id);
254
- const peer = {
255
- chatType: ChatType.GROUP,
256
- peerUid: groupCode
257
- };
258
- const msgId = await api.resolveMsgIdBySeq(peer, payload.message_seq, ChatType.GROUP);
259
- if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
260
- if (payload.is_set === false) await api.groupApi.removeGroupEssence(groupCode, msgId);
261
- else await api.groupApi.addGroupEssence(groupCode, msgId);
262
- return {};
263
- }
264
- }),
265
- defineMilkyAction({
266
- name: "send_group_message_reaction",
267
- schema: z.object({
268
- ...groupIdField,
269
- message_seq: z.number().int().min(0),
270
- reaction: z.string().min(1),
271
- reaction_type: z.enum(["face", "emoji"]).nullable().optional(),
272
- is_add: z.boolean().nullable().optional()
273
- }),
274
- handle: async (payload) => {
275
- const peer = {
276
- chatType: ChatType.GROUP,
277
- peerUid: String(payload.group_id)
278
- };
279
- await api.msgApi.setMsgEmojiLike(peer, {
280
- msgSeq: String(payload.message_seq),
281
- emojiId: payload.reaction,
282
- emojiType: payload.reaction_type === "emoji" ? "2" : "1",
283
- like: payload.is_add !== false
284
- });
285
- return {};
286
- }
287
- })
288
- ];
289
- }
290
- /** ---------- 内部辅助 ---------- */
291
- /** 精华项 → GroupEssenceMessage(msg_content 近似翻译:text / image)。 */
292
- function essenceToEntity(item, groupId) {
293
- const segments = [];
294
- for (const c of item.msg_content) if (c.text !== void 0 && c.text !== "") segments.push({
295
- type: "text",
296
- data: { text: c.text }
297
- });
298
- else if (c.image_url !== void 0 && c.image_url !== "") segments.push({
299
- type: "image",
300
- data: {
301
- resource_id: c.image_url,
302
- temp_url: c.image_url,
303
- width: 0,
304
- height: 0,
305
- summary: "",
306
- sub_type: "normal"
307
- }
308
- });
309
- return {
310
- group_id: groupId,
311
- message_seq: item.msg_seq,
312
- message_time: item.add_digest_time,
313
- sender_id: Number(item.sender_uin) || 0,
314
- sender_name: item.sender_nick,
315
- operator_id: Number(item.add_digest_uin) || 0,
316
- operator_name: item.add_digest_nick,
317
- operation_time: item.add_digest_time,
318
- segments
319
- };
320
- }
321
- // src/milky/helper/message/media-uri.ts
322
- /**
323
- * 发送媒体 URI 解析(Milky OutgoingSegment uri → 本地路径)
324
- *
325
- * 规范支持 file:// / http(s):// / base64:// 三种(image/record/video 共用):
326
- * - file:// → 平台路径(segments.ts 的同步面已处理)
327
- * - base64:// → 解码落盘 cacheDir/milky/,file-type 探测扩展名后改名
328
- * - http(s):// → @napuketto/media downloadUrl 落盘 cacheDir/milky/
329
- * 未配置 mediaDir 时远程 URI 报错(不发静默空消息)。
330
- */
331
- /** file:// 前缀(fileURLToPath 失败时的裸剥离兜底)。 */
332
- const FILE_URI_PREFIX_RE$1 = /^file:\/\//;
333
- /** 解析远程媒体 URI 为本地绝对路径(base64:// / http(s)://;file:// 走同步面)。 */
334
- async function resolveMediaUri(uri, mediaDir) {
335
- if (mediaDir === void 0 || mediaDir === "") throw kernelError("远程媒体发送需要配置 [accounts.milky] cacheDir(下载缓存目录)", "INVALID_PARAM");
336
- if (uri.startsWith("base64://")) return await writeBase64(uri.slice(9), mediaDir);
337
- const dest = join(mediaDir, `${randomUUID()}${inferExtension(null, uri)}`);
338
- await downloadUrl(uri, dest);
339
- return dest;
340
- }
341
- /**
342
- * 动作参数 URI(image_uri / file_uri)→ 本地路径:file:// 同步展开(fileURLToPath
343
- * 失败裸剥离兜底,与 segments.ts 同步面同规则);http(s):// / base64:// 复用
344
- * resolveMediaUri 落盘;裸路径(go-cqhttp 惯例)原样。
345
- */
346
- async function resolveUriToPath(uri, mediaDir) {
347
- if (uri.startsWith("file://")) try {
348
- return fileURLToPath(uri);
349
- } catch {
350
- return uri.replace(FILE_URI_PREFIX_RE$1, "");
351
- }
352
- if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("base64://")) return await resolveMediaUri(uri, mediaDir);
353
- return uri;
354
- }
355
- /** base64 载荷 → 落盘(先写 .bin,探测到扩展名再改名)。 */
356
- async function writeBase64(payload, mediaDir) {
357
- let bytes;
358
- try {
359
- bytes = Buffer.from(payload, "base64");
360
- } catch {
361
- throw kernelError("base64:// 载荷解码失败", "INVALID_PARAM");
362
- }
363
- if (bytes.length === 0) throw kernelError("base64:// 载荷为空", "INVALID_PARAM");
364
- await mkdir(mediaDir, { recursive: true });
365
- const raw = join(mediaDir, `${randomUUID()}.bin`);
366
- await writeFile(raw, bytes);
367
- try {
368
- const { ext } = await detectFileType(raw);
369
- const final = join(mediaDir, `${randomUUID()}${ext}`);
370
- await rename(raw, final);
371
- return final;
372
- } catch {
373
- return raw;
374
- }
375
- }
376
- // src/milky/action/group-file.ts
377
- const fileIdField = { file_id: z.string().min(1) };
378
- const optStr$2 = z.string().nullable().optional();
379
- /** 群文件域动作工厂(列表 / 移动 / 重命名 / 删除 / 转存 / 文件夹 / 闪传上传 / 下载链接)。 */
380
- function createGroupFileActions(api) {
381
- return [
382
- defineMilkyAction({
383
- name: "get_group_files",
384
- schema: z.object({
385
- ...groupIdField,
386
- parent_folder_id: optStr$2
387
- }),
388
- handle: async (payload) => {
389
- const groupCode = String(payload.group_id);
390
- const parent = payload.parent_folder_id ?? "";
391
- const items = await api.richMediaApi.getGroupFileList(groupCode, parent);
392
- const files = [];
393
- const folders = [];
394
- for (const item of items) if (item.fileInfo !== void 0) files.push(fileToEntity(item.fileInfo, payload.group_id));
395
- else if (item.folderInfo !== void 0) folders.push(folderToEntity(item.folderInfo, payload.group_id));
396
- return {
397
- files,
398
- folders
399
- };
400
- }
401
- }),
402
- defineMilkyAction({
403
- name: "move_group_file",
404
- schema: z.object({
405
- ...groupIdField,
406
- ...fileIdField,
407
- parent_folder_id: optStr$2,
408
- target_folder_id: optStr$2
409
- }),
410
- handle: async (payload) => {
411
- await api.richMediaApi.moveGroupFile(String(payload.group_id), [payload.file_id], payload.target_folder_id ?? "");
412
- return {};
413
- }
414
- }),
415
- defineMilkyAction({
416
- name: "rename_group_file",
417
- schema: z.object({
418
- ...groupIdField,
419
- ...fileIdField,
420
- parent_folder_id: optStr$2,
421
- new_file_name: z.string().min(1)
422
- }),
423
- handle: async (payload) => {
424
- await api.richMediaApi.renameGroupFile(String(payload.group_id), payload.file_id, payload.new_file_name);
425
- return {};
426
- }
427
- }),
428
- defineMilkyAction({
429
- name: "delete_group_file",
430
- schema: z.object({
431
- ...groupIdField,
432
- ...fileIdField
433
- }),
434
- handle: async (payload) => {
435
- await api.richMediaApi.deleteGroupFile(String(payload.group_id), [payload.file_id]);
436
- return {};
437
- }
438
- }),
439
- defineMilkyAction({
440
- name: "persist_group_file",
441
- schema: z.object({
442
- ...groupIdField,
443
- ...fileIdField
444
- }),
445
- handle: async (payload) => {
446
- await api.richMediaApi.transGroupFile(String(payload.group_id), payload.file_id);
447
- return {};
448
- }
449
- }),
450
- defineMilkyAction({
451
- name: "create_group_folder",
452
- schema: z.object({
453
- ...groupIdField,
454
- folder_name: z.string().min(1)
455
- }),
456
- handle: async (payload) => {
457
- return { folder_id: await api.richMediaApi.createGroupFolder(String(payload.group_id), payload.folder_name) };
458
- }
459
- }),
460
- defineMilkyAction({
461
- name: "delete_group_folder",
462
- schema: z.object({
463
- ...groupIdField,
464
- folder_id: z.string().min(1)
465
- }),
466
- handle: async (payload) => {
467
- await api.richMediaApi.deleteGroupFolder(String(payload.group_id), payload.folder_id);
468
- return {};
469
- }
470
- }),
471
- defineMilkyAction({
472
- name: "upload_group_file",
473
- schema: z.object({
474
- ...groupIdField,
475
- parent_folder_id: optStr$2,
476
- file_uri: z.string().min(1),
477
- file_name: z.string().min(1)
478
- }),
479
- handle: async (payload) => {
480
- const path = await resolveUriToPath(payload.file_uri, api.mediaDir);
481
- const peer = {
482
- chatType: ChatType.GROUP,
483
- peerUid: String(payload.group_id)
484
- };
485
- return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
486
- }
487
- }),
488
- defineMilkyAction({
489
- name: "get_group_file_download_url",
490
- schema: z.object({
491
- ...groupIdField,
492
- ...fileIdField
493
- }),
494
- handle: async (payload) => {
495
- return { download_url: await api.richMediaApi.getGroupFileDownloadUrl(String(payload.group_id), payload.file_id) };
496
- }
497
- }),
498
- defineMilkyAction({
499
- name: "rename_group_folder",
500
- schema: z.object({
501
- ...groupIdField,
502
- folder_id: z.string().min(1),
503
- new_folder_name: z.string().min(1)
504
- }),
505
- handle: async (payload) => {
506
- await api.richMediaApi.renameGroupFolder(String(payload.group_id), payload.folder_id, payload.new_folder_name);
507
- return {};
508
- }
509
- })
510
- ];
511
- }
512
- /** ---------- 内部辅助 ---------- */
513
- /** GroupFileItemInfo → GroupFileEntity(fileSize 原生为字符串;无源字段兜底)。 */
514
- function fileToEntity(info, groupId) {
515
- return {
516
- group_id: groupId,
517
- file_id: info.fileId,
518
- file_name: info.fileName,
519
- parent_folder_id: info.parent ?? "",
520
- file_size: Number(info.fileSize) || 0,
521
- uploaded_time: Number(info.uploadTime) || 0,
522
- expire_time: null,
523
- uploader_id: Number(info.uploaderUin) || 0,
524
- downloaded_times: 0
525
- };
526
- }
527
- /** GroupFolderInfo → GroupFolderEntity(元数据无类型字段防御读取,缺省 0)。 */
528
- function folderToEntity(info, groupId) {
529
- const num = (key) => {
530
- const v = info[key];
531
- return typeof v === "number" ? v : Number(v) || 0;
532
- };
533
- return {
534
- group_id: groupId,
535
- folder_id: info.folderId,
536
- parent_folder_id: info.folderUid ?? "",
537
- folder_name: info.folderName,
538
- created_time: num("createTime"),
539
- last_modified_time: num("modifyTime"),
540
- creator_id: 0,
541
- file_count: num("totalFileCount")
542
- };
543
- }
544
- // src/milky/action/group-manage.ts
545
- /**
546
- * Milky 群管理域动作:send_group_nudge / set_group_name / set_group_member_card /
547
- * set_group_member_admin / set_group_member_mute / set_group_whole_mute /
548
- * kick_group_member / quit_group / set_group_avatar /
549
- * set_group_member_special_title / send_group_announcement / delete_group_announcement。
550
- * 写操作合:成员类操作 user_id(uin) → uid 转换后进 kernel(resolveUidFromUin);
551
- * 公告 image_uri / 头像 image_uri 落盘后进 kernel。
552
- */
553
- const optStr$1 = z.string().nullable().optional();
554
- /** NTGroupMemberRole 数值(ADMIN=3 / MEMBER=2,setMemberRole 入参)。 */
555
- const NTGroupMemberRoleAdmin = 3;
556
- const NTGroupMemberRoleMember = 2;
557
- /** 群管理域动作工厂(群设置 / 成员管理 / 公告 / 戳一戳)。 */
558
- function createGroupManageActions(api) {
559
- return [
560
- defineMilkyAction({
561
- name: "send_group_nudge",
562
- schema: z.object({
563
- ...groupIdField,
564
- ...userIdField
565
- }),
566
- handle: async (payload) => {
567
- const receiverUid = await api.resolveUidFromUin(payload.user_id);
568
- const peer = await api.resolvePeer("group", payload.group_id);
569
- await api.msgApi.sendNudge(peer, {
570
- receiverUid,
571
- callerUid: requireSelfUid$1(api)
572
- });
573
- return {};
574
- }
575
- }),
576
- defineMilkyAction({
577
- name: "set_group_name",
578
- schema: z.object({
579
- ...groupIdField,
580
- new_group_name: z.string()
581
- }),
582
- handle: async (payload) => {
583
- await api.groupApi.modifyGroupName(String(payload.group_id), payload.new_group_name);
584
- return {};
585
- }
586
- }),
587
- defineMilkyAction({
588
- name: "set_group_member_card",
589
- schema: z.object({
590
- ...groupIdField,
591
- ...userIdField,
592
- card: z.string()
593
- }),
594
- handle: async (payload) => {
595
- const uid = await api.resolveUidFromUin(payload.user_id);
596
- api.groupApi.setMemberCardName(String(payload.group_id), uid, payload.card);
597
- return {};
598
- }
599
- }),
600
- defineMilkyAction({
601
- name: "set_group_member_admin",
602
- schema: z.object({
603
- ...groupIdField,
604
- ...userIdField,
605
- is_set: optBool$1
606
- }),
607
- handle: async (payload) => {
608
- const uid = await api.resolveUidFromUin(payload.user_id);
609
- api.groupApi.setMemberRole(String(payload.group_id), uid, payload.is_set === false ? NTGroupMemberRoleMember : NTGroupMemberRoleAdmin);
610
- return {};
611
- }
612
- }),
613
- defineMilkyAction({
614
- name: "set_group_member_mute",
615
- schema: z.object({
616
- ...groupIdField,
617
- ...userIdField,
618
- duration: z.number().int().min(0).nullable().optional()
619
- }),
620
- handle: async (payload) => {
621
- const uid = await api.resolveUidFromUin(payload.user_id);
622
- await api.groupApi.setMemberShutUp(String(payload.group_id), [{
623
- uid,
624
- duration: payload.duration ?? 0
625
- }]);
626
- return {};
627
- }
628
- }),
629
- defineMilkyAction({
630
- name: "set_group_whole_mute",
631
- schema: z.object({
632
- ...groupIdField,
633
- is_mute: optBool$1
634
- }),
635
- handle: async (payload) => {
636
- await api.groupApi.setGroupShutUp(String(payload.group_id), payload.is_mute !== false);
637
- return {};
638
- }
639
- }),
640
- defineMilkyAction({
641
- name: "kick_group_member",
642
- schema: z.object({
643
- ...groupIdField,
644
- ...userIdField,
645
- reject_add_request: optBool$1
646
- }),
647
- handle: async (payload) => {
648
- const uid = await api.resolveUidFromUin(payload.user_id);
649
- await api.groupApi.kickMember(String(payload.group_id), [uid], payload.reject_add_request === true);
650
- return {};
651
- }
652
- }),
653
- defineMilkyAction({
654
- name: "quit_group",
655
- schema: z.object({ ...groupIdField }),
656
- handle: async (payload) => {
657
- await api.groupApi.quitGroup(String(payload.group_id));
658
- return {};
659
- }
660
- }),
661
- defineMilkyAction({
662
- name: "set_group_avatar",
663
- schema: z.object({
664
- ...groupIdField,
665
- image_uri: z.string().min(1)
666
- }),
667
- handle: async (payload) => {
668
- const imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir);
669
- await api.groupApi.setGroupAvatar(String(payload.group_id), imagePath);
670
- return {};
671
- }
672
- }),
673
- defineMilkyAction({
674
- name: "set_group_member_special_title",
675
- schema: z.object({
676
- ...groupIdField,
677
- ...userIdField,
678
- special_title: z.string()
679
- }),
680
- handle: async (payload) => {
681
- const uid = await api.resolveUidFromUin(payload.user_id);
682
- await api.groupApi.setMemberSpecialTitle(String(payload.group_id), uid, payload.special_title);
683
- return {};
684
- }
685
- }),
686
- defineMilkyAction({
687
- name: "send_group_announcement",
688
- schema: z.object({
689
- ...groupIdField,
690
- content: z.string().min(1),
691
- image_uri: optStr$1
692
- }),
693
- handle: async (payload) => {
694
- const groupCode = String(payload.group_id);
695
- let imagePath;
696
- if (payload.image_uri !== void 0 && payload.image_uri !== null && payload.image_uri !== "") imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir);
697
- await api.groupApi.publishGroupAnnouncement(groupCode, payload.content, imagePath);
698
- return {};
699
- }
700
- }),
701
- defineMilkyAction({
702
- name: "delete_group_announcement",
703
- schema: z.object({
704
- ...groupIdField,
705
- announcement_id: z.string().min(1)
706
- }),
707
- handle: async (payload) => {
708
- await api.groupApi.deleteGroupAnnouncement(String(payload.group_id), payload.announcement_id);
709
- return {};
710
- }
711
- })
712
- ];
713
- }
714
- /** self.uid 必备(nudge 发送的 callerUid;缺配置报 INVALID_PARAM)。 */
715
- function requireSelfUid$1(api) {
716
- const uid = api.self.uid;
717
- if (uid === void 0 || uid === "") throw kernelError("登录身份缺 uid(无法发起戳一戳)", "INVALID_PARAM");
718
- return uid;
719
- }
720
- // src/milky/api.ts
721
- var MilkyApi = class {
722
- msgApi;
723
- groupApi;
724
- friendApi;
725
- profileApi;
726
- profileLikeApi;
727
- ticketApi;
728
- webApi;
729
- groupNotifyApi;
730
- richMediaApi;
731
- /** kernel 闪传 API(文件投递:分享卡片,见 flash-transfer.ts 语义说明)。 */
732
- flashTransferApi;
733
- recentContactApi;
734
- self;
735
- groupCache;
736
- qqVersion;
737
- implVersion;
738
- mediaDir;
739
- /** 动作层可观测出口(缺省静默)。 */
740
- logger;
741
- /** message_seq ↔ msgId 双向映射(接收链路 record,动作侧反查)。 */
742
- seqIndex;
743
- constructor(opts, seqIndex) {
744
- this.msgApi = opts.msgApi;
745
- this.groupApi = opts.groupApi;
746
- this.friendApi = opts.friendApi;
747
- this.profileApi = opts.profileApi;
748
- this.profileLikeApi = opts.profileLikeApi;
749
- this.ticketApi = opts.ticketApi;
750
- this.webApi = opts.webApi;
751
- this.groupNotifyApi = opts.groupNotifyApi;
752
- this.richMediaApi = opts.richMediaApi;
753
- this.flashTransferApi = opts.flashTransferApi;
754
- this.recentContactApi = opts.recentContactApi;
755
- this.self = opts.self;
756
- this.groupCache = opts.groupCache;
757
- this.qqVersion = opts.qqVersion;
758
- this.implVersion = opts.implVersion;
759
- this.mediaDir = opts.mediaDir;
760
- this.logger = opts.logger;
761
- this.seqIndex = seqIndex;
762
- }
763
- /** uin → uid(私聊目标 / at 段发送转换 / 群管动作的 uid 入参)。 */
764
- uinToUid(uins) {
765
- return this.groupApi.uinToUid(uins);
766
- }
767
- /** uid → uin(事件路径 mention 转换)。 */
768
- uidToUin(uids) {
769
- return this.groupApi.uidToUin(uids);
770
- }
771
- /**
772
- * uin(数字)→ uid(群管动作入参转换);转换失败抛 INVALID_PARAM
773
- * (Milky 入参 user_id 都是 uin,kernel 群管 API 要 uid)。
774
- */
775
- async resolveUidFromUin(uin) {
776
- const uinStr = String(uin);
777
- let cause;
778
- try {
779
- const uid = (await this.uinToUid([uinStr])).get(uinStr);
780
- if (uid !== void 0 && uid !== "") return uid;
781
- } catch (err) {
782
- cause = err;
783
- }
784
- throw kernelError(`用户 ${uinStr} 不存在或 uin→uid 转换失败`, "INVALID_PARAM", cause === void 0 ? void 0 : { cause });
785
- }
786
- /**
787
- * message_scene + 数字 ID → NT Peer。
788
- * group = 群号直作 peerUid;friend/temp = uin → uid(失败退 uin 原样,交 QQ 端判断)。
789
- */
790
- async resolvePeer(scene, id) {
791
- if (scene === "group") return {
792
- chatType: ChatType.GROUP,
793
- peerUid: String(id)
794
- };
795
- const uin = String(id);
796
- let uid;
797
- try {
798
- uid = (await this.uinToUid([uin])).get(uin);
799
- } catch (err) {
800
- this.logger?.warn({
801
- uin,
802
- error: err instanceof Error ? err.message : String(err)
803
- }, "milky: uin→uid 转换失败,peer 退用 uin 原样");
804
- }
805
- return {
806
- chatType: scene === "friend" ? ChatType.C2C : ChatType.C2C_TEMP,
807
- peerUid: uid ?? uin
808
- };
809
- }
810
- /**
811
- * seq → msgId(索引优先,未登记扫描近段历史兜底)。
812
- * 两层都未命中返回 undefined(调用方抛 NOT_FOUND)。
813
- */
814
- async resolveMsgIdBySeq(peer, seq, chatType) {
815
- const indexed = this.seqIndex.resolveMsgId(chatType, peer.peerUid, seq);
816
- if (indexed !== void 0) return indexed;
817
- const hit = (await this.msgApi.fetchMessages(peer, { count: 60 }).catch((err) => {
818
- this.logger?.debug({
819
- peer: peer.peerUid,
820
- seq,
821
- error: err instanceof Error ? err.message : String(err)
822
- }, "milky: msgSeq 反查近段历史失败");
823
- return [];
824
- })).find((m) => Number(m.msgSeq) === seq);
825
- if (hit === void 0) return;
826
- this.seqIndex.record(hit);
827
- return hit.msgId;
828
- }
829
- /** 发送结果回查:msgId → {message_seq, time}(sendMessage 只回 msgId)。 */
830
- async resolveSentOutput(peer, msgId) {
831
- const [sent] = await this.msgApi.fetchMsgsByMsgId(peer, [msgId]);
832
- if (sent === void 0) throw kernelError("发送结果回查失败(msgId 未命中)", "UNKNOWN");
833
- this.seqIndex.record(sent);
834
- return {
835
- message_seq: Number(sent.msgSeq),
836
- time: toUnixSeconds(sent.msgTime)
837
- };
838
- }
839
- };
840
- /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
841
- const NOTIFY_SEARCH_COUNT$1 = 100;
842
- /**
843
- * 按通知 seq 查找群通知(先非可疑后可疑两屏依序,OB11 set_group_add_request
844
- * 同路径)。屏序惰性拉取:前一屏命中则不拉后续屏(群通知规范序)。
845
- * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
846
- * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
847
- */
848
- async function findGroupNotify(api, seq) {
849
- const screens = [() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)];
850
- for (const fetchScreen of screens) {
851
- const hit = (await fetchScreen()).find((item) => item.seq === seq);
852
- if (hit !== void 0) return hit;
853
- }
854
- throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
855
- }
856
- /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
857
- async function findBuddyReq(api, initiatorUid) {
858
- const hit = (await api.friendApi.getBuddyReqList()).find((req) => req.friendUid === initiatorUid);
859
- if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
860
- return hit;
861
- }
862
- // src/milky/helper/event/request.ts
863
- /**
864
- * BuddyReq → friend_request 事件。
865
- * comment 取验证留言:QQNT 实际字段是 `extWords`,`words` 为旧口径兜底(都缺省空串)。
866
- */
867
- function toFriendRequestEvent(req, ctx) {
868
- const comment = firstNonEmptyString(stringOrUndefined(req["extWords"]), stringOrUndefined(req["words"])) ?? "";
869
- return {
870
- time: Math.floor(Date.now() / MS_TO_SEC),
871
- self_id: Number(ctx.selfUin),
872
- event_type: "friend_request",
873
- data: {
874
- initiator_id: toUin(req.friendUid, ctx),
875
- initiator_uid: req.friendUid,
876
- comment,
877
- via: req.sourceName ?? ""
878
- }
879
- };
880
- }
881
- /** GroupNotify → Milky 群请求事件(非未处理状态 / 非请求类返回 null)。 */
882
- function toGroupRequestEvent(notify, doubt, ctx) {
883
- if (notify.status !== GroupNotifyMsgStatus.KUNHANDLE) return null;
884
- const groupId = Number(notify.group?.groupCode ?? 0);
885
- const seq = Number(notify.seq);
886
- const time = Math.floor(Date.now() / MS_TO_SEC);
887
- const selfId = Number(ctx.selfUin);
888
- switch (notify.type) {
889
- case GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS: return {
890
- time,
891
- self_id: selfId,
892
- event_type: "group_join_request",
893
- data: {
894
- group_id: groupId,
895
- notification_seq: seq,
896
- is_filtered: doubt,
897
- initiator_id: toUin(notify.user1?.uid, ctx),
898
- comment: notify.postscript ?? ""
899
- }
900
- };
901
- case GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS: return {
902
- time,
903
- self_id: selfId,
904
- event_type: "group_invited_join_request",
905
- data: {
906
- group_id: groupId,
907
- notification_seq: seq,
908
- initiator_id: toUin(notify.user1?.uid, ctx),
909
- target_user_id: toUin(notify.user2?.uid, ctx)
910
- }
911
- };
912
- case GroupNotifyMsgType.INVITED_BY_MEMBER: return {
913
- time,
914
- self_id: selfId,
915
- event_type: "group_invitation",
916
- data: {
917
- group_id: groupId,
918
- invitation_seq: seq,
919
- initiator_id: toUin(notify.user1?.uid, ctx),
920
- source_group_id: null
921
- }
922
- };
923
- default: return null;
924
- }
925
- }
926
- /**
927
- * 群通知涉及的 uid 集合(去重;get_group_notifications 与事件广播共用)。
928
- * kernel GroupEventChannel 的 onGroupNotifiesUpdated 回调参数已类型化
929
- * (GroupNotify[]),无需防御收窄。
930
- */
931
- function collectNotifyUids(notifies) {
932
- const uids = /* @__PURE__ */ new Set();
933
- for (const n of notifies) for (const uid of [n.user1?.uid, n.user2?.uid]) if (uid !== void 0 && uid !== "") uids.add(uid);
934
- return [...uids];
935
- }
936
- // src/milky/action/group-notice.ts
937
- const optStr = z.string().nullable().optional();
938
- /** 通知查找数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
939
- const NOTIFY_SEARCH_COUNT = 100;
940
- /** get_group_notifications 默认 limit(规范 default 20)。 */
941
- const NOTIFICATIONS_DEFAULT_LIMIT = 20;
942
- /** 群通知域动作工厂(通知列表 + 应答四动作)。 */
943
- function createGroupNoticeActions(api) {
944
- return [
945
- defineMilkyAction({
946
- name: "get_group_notifications",
947
- schema: z.object({
948
- start_notification_seq: z.number().int().min(0).nullable().optional(),
949
- is_filtered: optBool$1,
950
- limit: z.number().int().min(0).nullable().optional()
951
- }),
952
- handle: async (payload) => {
953
- const notifies = await api.groupNotifyApi.getSingleScreenNotifies(payload.is_filtered === true, NOTIFY_SEARCH_COUNT);
954
- const start = payload.start_notification_seq;
955
- const filtered = notifies.filter((n) => start === void 0 || start === null || Number(n.seq) < start);
956
- const uidToUin = await collectUidToUin$1(api, filtered);
957
- const entities = filtered.map((n) => notifyToEntity(n, payload.is_filtered === true, uidToUin)).filter((e) => e !== null);
958
- const limit = payload.limit ?? NOTIFICATIONS_DEFAULT_LIMIT;
959
- const page = entities.slice(0, limit);
960
- const minSeq = page.reduce((acc, e) => acc === null ? e.notification_seq : Math.min(acc, e.notification_seq), null);
961
- return {
962
- notifications: page,
963
- next_notification_seq: entities.length > page.length && minSeq !== null ? minSeq : null
964
- };
965
- }
966
- }),
967
- defineMilkyAction({
968
- name: "accept_group_request",
969
- schema: respondRequestSchema,
970
- handle: async (payload) => respondGroupNotify(api, payload.notification_seq, payload.is_filtered === true, true)
971
- }),
972
- defineMilkyAction({
973
- name: "reject_group_request",
974
- schema: rejectRequestSchema,
975
- handle: async (payload) => respondGroupNotify(api, payload.notification_seq, payload.is_filtered === true, false)
976
- }),
977
- defineMilkyAction({
978
- name: "accept_group_invitation",
979
- schema: invitationSchema,
980
- handle: async (payload) => respondGroupNotify(api, payload.invitation_seq, false, true)
981
- }),
982
- defineMilkyAction({
983
- name: "reject_group_invitation",
984
- schema: invitationSchema,
985
- handle: async (payload) => respondGroupNotify(api, payload.invitation_seq, false, false)
986
- })
987
- ];
988
- }
989
- /** accept_group_request 入参(notification_type 仅 schema 校验)。 */
990
- const respondRequestSchema = z.object({
991
- notification_seq: z.number().int().min(0),
992
- notification_type: z.enum(["join_request", "invited_join_request"]),
993
- ...groupIdField,
994
- is_filtered: optBool$1
995
- });
996
- /** reject_group_request 入参(reason 无源)。 */
997
- const rejectRequestSchema = z.object({
998
- notification_seq: z.number().int().min(0),
999
- notification_type: z.enum(["join_request", "invited_join_request"]),
1000
- ...groupIdField,
1001
- is_filtered: optBool$1,
1002
- reason: optStr
1003
- });
1004
- /** accept/reject_group_invitation 入参。 */
1005
- const invitationSchema = z.object({
1006
- ...groupIdField,
1007
- invitation_seq: z.number().int().min(0)
1008
- });
1009
- /** 应答公共路径:seq → 通知匹配 → handleGroupRequest。 */
1010
- async function respondGroupNotify(api, seq, doubt, approve) {
1011
- const notify = await findGroupNotify(api, String(seq));
1012
- await api.groupNotifyApi.handleGroupRequest(doubt, notify, approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE, " ");
1013
- return {};
1014
- }
1015
- /** 通知 user1/user2 uid → uin 批量转换(失败退空 Map,实体 id 兜底 0)。 */
1016
- async function collectUidToUin$1(api, notifies) {
1017
- const uids = collectNotifyUids(notifies);
1018
- if (uids.length === 0) return /* @__PURE__ */ new Map();
1019
- return await api.uidToUin(uids).catch((err) => {
1020
- api.logger?.warn({
1021
- count: uids.length,
1022
- error: err instanceof Error ? err.message : String(err)
1023
- }, "milky: 通知 uid→uin 失败,实体 id 兜底 0");
1024
- return /* @__PURE__ */ new Map();
1025
- });
1026
- }
1027
- /**
1028
- * GroupNotify → GroupNotificationEntity(uidToUin 已由调用方批量转换)。
1029
- * 类型→构造器表:7=入群申请 / 5=成员邀请他人 / 8=设管理 / 12,13=取消管理 /
1030
- * 9,10=踢出 / 11=退群;1=邀请自身无实体变体(事件层表达),其余 null。
1031
- */
1032
- const NOTIFY_ENTITY_BUILDERS = {
1033
- 7: (n, uinOf) => ({
1034
- type: "join_request",
1035
- group_id: Number(n.group?.groupCode ?? 0),
1036
- notification_seq: Number(n.seq),
1037
- is_filtered: false,
1038
- initiator_id: uinOf(n.user1?.uid),
1039
- state: "pending",
1040
- operator_id: null,
1041
- comment: n.postscript ?? ""
1042
- }),
1043
- 5: (n, uinOf) => ({
1044
- type: "invited_join_request",
1045
- group_id: Number(n.group?.groupCode ?? 0),
1046
- notification_seq: Number(n.seq),
1047
- initiator_id: uinOf(n.user1?.uid),
1048
- target_user_id: uinOf(n.user2?.uid),
1049
- state: "pending",
1050
- operator_id: null
1051
- }),
1052
- 8: (n, uinOf) => adminChangeEntity(n, uinOf, true),
1053
- 12: (n, uinOf) => adminChangeEntity(n, uinOf, false),
1054
- 13: (n, uinOf) => adminChangeEntity(n, uinOf, false),
1055
- 9: (n, uinOf) => kickEntity(n, uinOf),
1056
- 10: (n, uinOf) => kickEntity(n, uinOf),
1057
- 11: (n, uinOf) => ({
1058
- type: "quit",
1059
- group_id: Number(n.group?.groupCode ?? 0),
1060
- notification_seq: Number(n.seq),
1061
- target_user_id: uinOf(n.user1?.uid)
1062
- })
1063
- };
1064
- /** admin_change 实体(8/12/13 共用)。 */
1065
- function adminChangeEntity(n, uinOf, isSet) {
1066
- return {
1067
- type: "admin_change",
1068
- group_id: Number(n.group?.groupCode ?? 0),
1069
- notification_seq: Number(n.seq),
1070
- target_user_id: uinOf(n.user1?.uid),
1071
- is_set: isSet,
1072
- operator_id: uinOf(n.user2?.uid)
1073
- };
1074
- }
1075
- /** kick 实体(9/10 共用)。 */
1076
- function kickEntity(n, uinOf) {
1077
- return {
1078
- type: "kick",
1079
- group_id: Number(n.group?.groupCode ?? 0),
1080
- notification_seq: Number(n.seq),
1081
- target_user_id: uinOf(n.user1?.uid),
1082
- operator_id: uinOf(n.user2?.uid)
1083
- };
1084
- }
1085
- /** GroupNotify → 实体(isFiltered 透传给 join_request;未识别类型 null)。 */
1086
- function notifyToEntity(notify, isFiltered, uidToUin) {
1087
- const uinOf = (uid) => uid === void 0 || uid === "" ? 0 : Number(uidToUin.get(uid) ?? 0) || 0;
1088
- const builder = NOTIFY_ENTITY_BUILDERS[notify.type];
1089
- if (builder === void 0) return null;
1090
- const entity = builder(notify, uinOf);
1091
- if (entity.type === "join_request") entity.is_filtered = isFiltered;
1092
- return entity;
1093
- }
1094
- // src/milky/helper/message/segments.ts
1095
- /**
1096
- * Milky 消息段 ↔ canonical 元素转换(纯函数)
1097
- *
1098
- * 接收方向:canonical → IncomingSegment(规范 14 种中映射 12 种;market_face /
1099
- * markdown 无 canonical 对应(MFACE/MARKDOWN 原始元素形状未探测),unknown 一律
1100
- * 跳过——规范兼容性要求「数组中未知项跳过」)。forward 接收段不经 canonical:
1101
- * kernel 无 MULTI_FORWARD 分支,adapter 从 RawMessage 提取 resId 后经
1102
- * incomingForwardSegment + ctx 注入。
1103
- * 发送方向:OutgoingSegment → canonical(10 种全映射;forward 顶层段不走本转换器,
1104
- * 由 sendMilkyMessage 分流到组装链——本转换器内 forward 报错只拦截混发/嵌套)。
1105
- */
1106
- /** uin 字符串 → Milky user_id(非有限正数 = 转换失败)。 */
1107
- function toUserId(uin) {
1108
- const n = Number(uin);
1109
- return Number.isFinite(n) && n >= 10001 ? n : void 0;
1110
- }
1111
- /** canonical 元素 → IncomingSegment 列表(unknown / 转换失败段跳过)。 */
1112
- function canonicalToIncomingSegments(elements, ctx = {}) {
1113
- const out = [];
1114
- for (const el of elements) {
1115
- const seg = canonicalToIncomingSegment(el, ctx);
1116
- if (seg !== null) out.push(seg);
1117
- }
1118
- return out;
1119
- }
1120
- /** canonical image → image 段(resource_id = 本地路径优先,url 兜底)。 */
1121
- function imageToIncoming(el) {
1122
- return {
1123
- type: "image",
1124
- data: {
1125
- resource_id: el.path !== "" ? el.path : el.url ?? "",
1126
- temp_url: el.url ?? "",
1127
- width: el.size?.width ?? 0,
1128
- height: el.size?.height ?? 0,
1129
- summary: "",
1130
- sub_type: "normal"
1131
- }
1132
- };
1133
- }
1134
- /** canonical voice → record 段。 */
1135
- function voiceToIncoming(el) {
1136
- return {
1137
- type: "record",
1138
- data: {
1139
- resource_id: el.path !== "" ? el.path : el.url ?? "",
1140
- temp_url: el.url ?? "",
1141
- duration: el.durationMs !== void 0 ? Math.round(el.durationMs / 1e3) : 0
1142
- }
1143
- };
1144
- }
1145
- /** canonical video → video 段。 */
1146
- function videoToIncoming(el) {
1147
- return {
1148
- type: "video",
1149
- data: {
1150
- resource_id: el.path !== "" ? el.path : el.url ?? "",
1151
- temp_url: el.url ?? "",
1152
- width: el.width ?? 0,
1153
- height: el.height ?? 0,
1154
- duration: el.durationSec ?? 0
1155
- }
1156
- };
1157
- }
1158
- /** 按类型分发的段映射器表(键 = canonical type;缺项 = 跳过)。 */
1159
- const INCOMING_MAPPERS = {
1160
- text: (el) => ({
1161
- type: "text",
1162
- data: { text: el.text }
1163
- }),
1164
- at: atToIncoming,
1165
- face: (el) => ({
1166
- type: "face",
1167
- data: {
1168
- face_id: el.id,
1169
- is_large: false
1170
- }
1171
- }),
1172
- reply: replyToIncoming,
1173
- image: imageToIncoming,
1174
- voice: voiceToIncoming,
1175
- video: videoToIncoming,
1176
- file: fileToIncoming,
1177
- json: (el) => ({
1178
- type: "light_app",
1179
- data: {
1180
- app_name: parseAppName(el.raw),
1181
- json_payload: rawToPayload(el.raw)
1182
- }
1183
- }),
1184
- xml: (el) => ({
1185
- type: "xml",
1186
- data: {
1187
- service_id: 0,
1188
- xml_payload: rawToPayload(el.raw)
1189
- }
1190
- })
1191
- };
1192
- function canonicalToIncomingSegment(el, ctx) {
1193
- const mapper = INCOMING_MAPPERS[el.type];
1194
- return mapper === void 0 ? null : mapper(el, ctx);
1195
- }
1196
- /** canonical at → mention / mention_all(uid→uin 失败跳过该段)。 */
1197
- function atToIncoming(el, ctx) {
1198
- if (el.target === "all") return {
1199
- type: "mention_all",
1200
- data: {}
1201
- };
1202
- const userId = toUserId(ctx.uidToUin?.get(el.target) ?? el.target);
1203
- if (userId === void 0) return null;
1204
- return {
1205
- type: "mention",
1206
- data: {
1207
- user_id: userId,
1208
- name: el.display ?? ""
1209
- }
1210
- };
1211
- }
1212
- /** canonical reply → reply 段(引用元信息经 ctx 回填,未命中全 0 兜底)。 */
1213
- function replyToIncoming(el, ctx) {
1214
- const meta = ctx.replyMeta?.get(el.messageId);
1215
- return {
1216
- type: "reply",
1217
- data: {
1218
- message_seq: meta?.messageSeq ?? 0,
1219
- sender_id: meta?.senderId ?? 0,
1220
- sender_name: null,
1221
- time: meta?.time ?? 0,
1222
- segments: []
1223
- }
1224
- };
1225
- }
1226
- /** canonical file → file 段。 */
1227
- function fileToIncoming(el) {
1228
- return {
1229
- type: "file",
1230
- data: {
1231
- file_id: el.path,
1232
- file_name: el.name ?? "",
1233
- file_size: el.size ?? 0
1234
- }
1235
- };
1236
- }
1237
- /**
1238
- * 合并转发 → forward 段。
1239
- * 接收方向 canonical 不承载 MULTI_FORWARD(kernel toCanonicalElement 无此分支),
1240
- * 由 adapter 从 RawMessage 提取 resId 后调用本函数经 ctx 注入(翻译保持纯函数)。
1241
- * title 取 NT fileName(转发卡片标题语义)。
1242
- */
1243
- function incomingForwardSegment(resId, title) {
1244
- return {
1245
- type: "forward",
1246
- data: {
1247
- forward_id: resId,
1248
- title,
1249
- preview: [],
1250
- summary: ""
1251
- }
1252
- };
1253
- }
1254
- /** json 载荷 → 小程序名(spec app_name:JSON 顶层 app 字段,取不到空串)。 */
1255
- function parseAppName(raw) {
1256
- let obj = raw;
1257
- if (typeof raw === "string") try {
1258
- obj = JSON.parse(raw);
1259
- } catch {
1260
- return "";
1261
- }
1262
- if (typeof obj !== "object" || obj === null || !("app" in obj)) return "";
1263
- const app = obj["app"];
1264
- return typeof app === "string" ? app : "";
1265
- }
1266
- /** canonical json/xml raw → 字符串载荷(字符串原样,其余 JSON 序列化)。 */
1267
- function rawToPayload(raw) {
1268
- if (typeof raw === "string") return raw;
1269
- try {
1270
- return JSON.stringify(raw) ?? "";
1271
- } catch {
1272
- return "";
1273
- }
1274
- }
1275
- /**
1276
- * OutgoingSegment 数组 → canonical 元素(同步映射;媒体 URI 解析与 at uin→uid
1277
- * 由调用方在返回值上继续处理)。
1278
- * forward 在此报错:顶层 forward 已由 sendMilkyMessage 分流到组装链(message.ts,
1279
- *),命中本分支 = forward 与其他段混发漏网或嵌套 forward(组装链内逐项
1280
- * 转换经过此处)——均显式拒绝。
1281
- */
1282
- function outgoingSegmentsToCanonical(segments) {
1283
- const elements = [];
1284
- const atUins = [];
1285
- const replySeqs = [];
1286
- for (const seg of segments) switch (seg.type) {
1287
- case "text":
1288
- elements.push({
1289
- type: "text",
1290
- text: seg.data.text
1291
- });
1292
- break;
1293
- case "mention": {
1294
- const uin = String(seg.data.user_id);
1295
- atUins.push(uin);
1296
- elements.push({
1297
- type: "at",
1298
- target: uin
1299
- });
1300
- break;
1301
- }
1302
- case "mention_all":
1303
- elements.push({
1304
- type: "at",
1305
- target: "all"
1306
- });
1307
- break;
1308
- case "face":
1309
- elements.push({
1310
- type: "face",
1311
- id: seg.data.face_id
1312
- });
1313
- break;
1314
- case "reply":
1315
- replySeqs.push(seg.data.message_seq);
1316
- elements.push({
1317
- type: "reply",
1318
- messageId: String(seg.data.message_seq)
1319
- });
1320
- break;
1321
- case "image":
1322
- elements.push({
1323
- type: "image",
1324
- path: resolveUriToPathPlaceholder(seg.data.uri)
1325
- });
1326
- break;
1327
- case "record":
1328
- elements.push({
1329
- type: "voice",
1330
- path: resolveUriToPathPlaceholder(seg.data.uri)
1331
- });
1332
- break;
1333
- case "video":
1334
- elements.push({
1335
- type: "video",
1336
- path: resolveUriToPathPlaceholder(seg.data.uri)
1337
- });
1338
- break;
1339
- case "light_app":
1340
- elements.push({
1341
- type: "json",
1342
- raw: seg.data.json_payload
1343
- });
1344
- break;
1345
- case "forward": throw kernelError("forward 段不可与其他消息段混发或嵌套(顶层 forward 须单独发送)", "INVALID_PARAM");
1346
- }
1347
- return {
1348
- elements,
1349
- atUins,
1350
- replySeqs
1351
- };
1352
- }
1353
- /**
1354
- * 媒体 URI → 本地路径(同步面:file:// / 裸路径直接给 canonical;base64:// 与
1355
- * http(s):// 需要异步落盘,由 send 核心在 canonical 上二次解析——此处先放原始
1356
- * URI 作占位,send 核心按元素类型调用 resolveMediaUri 替换)。
1357
- */
1358
- function resolveUriToPathPlaceholder(uri) {
1359
- if (uri.startsWith("file://")) return fileUriToPath(uri);
1360
- if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("base64://")) return uri;
1361
- return uri;
1362
- }
1363
- /** file:// 前缀(fileURLToPath 失败时的裸剥离兜底)。 */
1364
- const FILE_URI_PREFIX_RE = /^file:\/\//;
1365
- /** file:// URI → 平台路径(Windows 盘符兼容)。 */
1366
- function fileUriToPath(uri) {
1367
- try {
1368
- return fileURLToPath(uri);
1369
- } catch {
1370
- return uri.replace(FILE_URI_PREFIX_RE, "");
1371
- }
1372
- }
1373
- // src/milky/helper/event/translate.ts
1374
- /**
1375
- * Milky 事件翻译(RawMessage → Milky 事件,纯函数)
1376
- *
1377
- * 事件两种:message_receive(onRecvMsg)/ message_recall(grayTip REVOKE)。
1378
- * 实体与 reply 回填在广播路径异步取得后经 ctx 注入(翻译保持纯函数);
1379
- * 撤回事件的 sender_id 取 RawMessage.senderUin(grayTip 系统消息的 sender
1380
- * 即被撤回原消息的发送者,口径待真实事件校准)。
1381
- */
1382
- /** chatType → message_scene。 */
1383
- function chatTypeToScene(chatType) {
1384
- if (chatType === ChatType.GROUP) return "group";
1385
- if (chatType === ChatType.C2C_TEMP) return "temp";
1386
- return "friend";
1387
- }
1388
- /** peer_id:群聊 = 群号(peerUid);好友/临时 = 对端 uin(peerUin,空退 peerUid)。 */
1389
- function peerIdOf(msg, scene) {
1390
- const raw = scene === "group" ? msg.peerUid : msg.peerUin !== "" ? msg.peerUin : msg.peerUid;
1391
- return Number(raw);
1392
- }
1393
- /** RawMessage → message_receive 事件(实体缺省最小合法值,schema 形状完整)。 */
1394
- function toMessageReceiveEvent(msg, ctx) {
1395
- const segments = canonicalToIncomingSegments(toCanonicalElements(msg), {
1396
- ...ctx.uidToUin !== void 0 ? { uidToUin: ctx.uidToUin } : {},
1397
- ...ctx.replyMeta !== void 0 ? { replyMeta: ctx.replyMeta } : {}
1398
- });
1399
- if (ctx.forwardSegments !== void 0) segments.push(...ctx.forwardSegments);
1400
- const scene = chatTypeToScene(msg.chatType);
1401
- const time = toUnixSeconds(msg.msgTime);
1402
- let data;
1403
- if (scene === "group") data = {
1404
- message_scene: "group",
1405
- peer_id: peerIdOf(msg, scene),
1406
- message_seq: Number(msg.msgSeq),
1407
- sender_id: Number(msg.senderUin),
1408
- time,
1409
- segments,
1410
- group: ctx.groupEntity ?? toGroupEntity(void 0, msg.peerUid),
1411
- group_member: ctx.groupMemberEntity ?? toGroupMemberEntity(void 0, msg.peerUid, msg.senderUin)
1412
- };
1413
- else if (scene === "friend") data = {
1414
- message_scene: "friend",
1415
- peer_id: peerIdOf(msg, scene),
1416
- message_seq: Number(msg.msgSeq),
1417
- sender_id: Number(msg.senderUin),
1418
- time,
1419
- segments,
1420
- friend: ctx.friendEntity ?? toFriendEntity(void 0, msg.peerUin !== "" ? msg.peerUin : msg.senderUin, msg.peerName)
1421
- };
1422
- else data = {
1423
- message_scene: "temp",
1424
- peer_id: peerIdOf(msg, scene),
1425
- message_seq: Number(msg.msgSeq),
1426
- sender_id: Number(msg.senderUin),
1427
- time,
1428
- segments,
1429
- group: ctx.groupEntity ?? null
1430
- };
1431
- return {
1432
- time,
1433
- self_id: Number(ctx.selfUin),
1434
- event_type: "message_receive",
1435
- data
1436
- };
1437
- }
1438
- /** 撤回 grayTip → message_recall 事件(非撤回 grayTip 返回 null)。 */
1439
- function toMessageRecallEvent(msg, ctx) {
1440
- const revoke = (msg.elements.find((el) => el.grayTipElement != null)?.grayTipElement)?.revokeElement;
1441
- if (revoke == null) return null;
1442
- const scene = chatTypeToScene(msg.chatType);
1443
- const operatorUin = ctx.uidToUin?.get(revoke.operatorUid) ?? revoke.operatorUid;
1444
- return {
1445
- time: toUnixSeconds(msg.msgTime),
1446
- self_id: Number(ctx.selfUin),
1447
- event_type: "message_recall",
1448
- data: {
1449
- message_scene: scene,
1450
- peer_id: peerIdOf(msg, scene),
1451
- message_seq: Number(msg.msgSeq),
1452
- sender_id: Number(msg.senderUin),
1453
- operator_id: Number(operatorUin) || 0,
1454
- display_suffix: revoke.wording ?? ""
1455
- }
1456
- };
1457
- }
1458
- /** 群文件上传事件(群场景文件消息 → group_file_upload,替代 message_receive)。 */
1459
- function toGroupFileUploadEvent(msg, selfUin) {
1460
- if (msg.chatType !== ChatType.GROUP) return null;
1461
- const file = msg.elements.find((el) => el.fileElement != null)?.fileElement;
1462
- if (file == null) return null;
1463
- return {
1464
- time: toUnixSeconds(msg.msgTime),
1465
- self_id: Number(selfUin),
1466
- event_type: "group_file_upload",
1467
- data: {
1468
- group_id: Number(msg.peerUid),
1469
- user_id: Number(msg.senderUin) || 0,
1470
- file_id: file.fileUuid ?? file.fileName ?? "",
1471
- file_name: file.fileName ?? "",
1472
- file_size: Number(file.fileSize ?? 0)
1473
- }
1474
- };
1475
- }
1476
- // src/milky/action/message-query.ts
1477
- /** get_message / mark_message_as_read 共入参(场景 + 对端 + seq)。 */
1478
- const peerMessageFields = {
1479
- message_scene: z.enum([
1480
- "friend",
1481
- "group",
1482
- "temp"
1483
- ]),
1484
- peer_id: z.number().int().min(10001),
1485
- message_seq: z.number().int().min(0)
1486
- };
1487
- /** 历史消息默认条数(规范 default 20)。 */
1488
- const HISTORY_DEFAULT_LIMIT = 20;
1489
- /** 消息查询域动作工厂(get_message / get_history_messages / get_forwarded_messages)。 */
1490
- function createMessageQueryActions(api) {
1491
- return [
1492
- defineMilkyAction({
1493
- name: "get_message",
1494
- schema: z.object({ ...peerMessageFields }),
1495
- handle: async (payload) => {
1496
- const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
1497
- const msgId = await api.resolveMsgIdBySeq(peer, payload.message_seq, peer.chatType);
1498
- if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1499
- const [msg] = await api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
1500
- if (msg === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1501
- return { message: await translateWithEntities(api, payload.message_scene, peer, msg) };
1502
- }
1503
- }),
1504
- defineMilkyAction({
1505
- name: "get_history_messages",
1506
- schema: z.object({
1507
- message_scene: z.enum([
1508
- "friend",
1509
- "group",
1510
- "temp"
1511
- ]),
1512
- peer_id: z.number().int().min(10001),
1513
- start_message_seq: z.number().int().min(0).nullable().optional(),
1514
- limit: z.number().int().min(0).nullable().optional()
1515
- }),
1516
- handle: async (payload) => {
1517
- const limit = payload.limit ?? HISTORY_DEFAULT_LIMIT;
1518
- const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
1519
- const anchor = await resolveAnchor(api, peer, payload.start_message_seq);
1520
- const msgs = await api.msgApi.fetchMessages(peer, {
1521
- count: limit,
1522
- ...anchor !== void 0 ? { msgId: anchor } : {}
1523
- });
1524
- for (const m of msgs) api.seqIndex.record(m);
1525
- const groupData = payload.message_scene === "group" ? await loadGroupData(api, peer.peerUid) : null;
1526
- const ordered = [...msgs].reverse();
1527
- const messages = ordered.map((m) => translateHistoryMessage(api, m, peer.peerUid, groupData));
1528
- const hasMore = msgs.length >= limit;
1529
- const oldest = ordered[0];
1530
- return {
1531
- messages,
1532
- next_message_seq: hasMore && oldest !== void 0 ? Number(oldest.msgSeq) : null
1533
- };
1534
- }
1535
- }),
1536
- defineMilkyAction({
1537
- name: "get_forwarded_messages",
1538
- schema: z.object({ forward_id: z.string().min(1) }),
1539
- handle: async (payload) => {
1540
- const entry = api.seqIndex.resolveForward(payload.forward_id);
1541
- if (entry === void 0) throw kernelError(`转发消息 ${payload.forward_id} 不存在(未登记)`, "NOT_FOUND");
1542
- const peer = {
1543
- chatType: entry.chatType,
1544
- peerUid: entry.peerUid
1545
- };
1546
- const msgs = await api.msgApi.fetchForwardMessage(peer, entry.msgId);
1547
- for (const m of msgs) api.seqIndex.record(m);
1548
- const uidToUin = await collectUidToUin(api, msgs);
1549
- const messages = [];
1550
- for (const m of msgs) messages.push({
1551
- message_seq: Number(m.msgSeq),
1552
- sender_name: await senderNameOf(api, m),
1553
- avatar_url: avatarUrlOf(m.senderUin),
1554
- time: toUnixSeconds(m.msgTime),
1555
- segments: receiveSegmentsOf(m, uidToUin)
1556
- });
1557
- return { messages };
1558
- }
1559
- })
1560
- ];
1561
- }
1562
- /** ---------- 内部辅助 ---------- */
1563
- /** 实体回填(group 场景 schema 要求完整实体)→ IncomingMessage。 */
1564
- async function translateWithEntities(api, scene, peer, msg) {
1565
- const ctx = { selfUin: api.self.uin };
1566
- if (scene === "group") {
1567
- const [detail, member] = await Promise.all([api.groupCache?.getGroupDetail(peer.peerUid).catch((err) => {
1568
- api.logger?.warn({
1569
- group: peer.peerUid,
1570
- error: err instanceof Error ? err.message : String(err)
1571
- }, "milky: 群详情缓存读取失败,实体回填退化");
1572
- }), api.groupCache?.getMember(peer.peerUid, msg.senderUid).catch((err) => {
1573
- api.logger?.debug({
1574
- group: peer.peerUid,
1575
- member: msg.senderUid,
1576
- error: err instanceof Error ? err.message : String(err)
1577
- }, "milky: 群成员缓存读取失败,实体回填退化");
1578
- })]);
1579
- ctx.groupEntity = toGroupEntity(detail, peer.peerUid);
1580
- ctx.groupMemberEntity = toGroupMemberEntity(member, peer.peerUid, msg.senderUin);
1581
- }
1582
- return toMessageReceiveEvent(msg, ctx).data;
1583
- }
1584
- /** start_message_seq → 锚点 msgId(给了 seq 却反查不到 = NOT_FOUND)。 */
1585
- async function resolveAnchor(api, peer, startSeq) {
1586
- if (startSeq === void 0 || startSeq === null) return;
1587
- const msgId = await api.resolveMsgIdBySeq(peer, startSeq, peer.chatType);
1588
- if (msgId === void 0) throw kernelError(`起始消息 ${startSeq} 不存在`, "NOT_FOUND");
1589
- return msgId;
1590
- }
1591
- /** 群场景回填数据(详情 + 成员表;缓存未装配返回空数据)。 */
1592
- async function loadGroupData(api, groupCode) {
1593
- if (api.groupCache === void 0) return {
1594
- detail: void 0,
1595
- members: /* @__PURE__ */ new Map()
1596
- };
1597
- const [detail, members] = await Promise.all([api.groupCache.getGroupDetail(groupCode).catch((err) => {
1598
- api.logger?.warn({
1599
- group: groupCode,
1600
- error: err instanceof Error ? err.message : String(err)
1601
- }, "milky: 群详情缓存读取失败,历史翻译退化");
1602
- }), api.groupCache.getMembers(groupCode).catch((err) => {
1603
- api.logger?.warn({
1604
- group: groupCode,
1605
- error: err instanceof Error ? err.message : String(err)
1606
- }, "milky: 群成员表缓存读取失败,历史翻译退化");
1607
- return [];
1608
- })]);
1609
- const memberByUid = /* @__PURE__ */ new Map();
1610
- for (const m of members) memberByUid.set(m.uid, m);
1611
- return {
1612
- detail,
1613
- members: memberByUid
1614
- };
1615
- }
1616
- /** 单条历史消息 → IncomingMessage(群场景注入实体,fail-soft)。 */
1617
- function translateHistoryMessage(api, msg, peerUid, groupData) {
1618
- const ctx = { selfUin: api.self.uin };
1619
- if (groupData !== null) {
1620
- if (groupData.detail !== void 0) ctx.groupEntity = toGroupEntity(groupData.detail, peerUid);
1621
- const member = groupData.members.get(msg.senderUid);
1622
- if (member !== void 0) ctx.groupMemberEntity = toGroupMemberEntity(member, peerUid, msg.senderUin);
1623
- }
1624
- return toMessageReceiveEvent(msg, ctx).data;
1625
- }
1626
- /** at 段 uid → uin 批量转换(mention 翻译;失败退空 Map)。 */
1627
- async function collectUidToUin(api, msgs) {
1628
- const uids = /* @__PURE__ */ new Set();
1629
- for (const m of msgs) for (const el of toCanonicalElements(m)) if (el.type === "at" && el.target !== "all") uids.add(el.target);
1630
- if (uids.size === 0) return /* @__PURE__ */ new Map();
1631
- return await api.uidToUin([...uids]).catch((err) => {
1632
- api.logger?.warn({
1633
- count: uids.size,
1634
- error: err instanceof Error ? err.message : String(err)
1635
- }, "milky: 历史 at uid→uin 失败,mention 段跳过");
1636
- return /* @__PURE__ */ new Map();
1637
- });
1638
- }
1639
- /** 发送者名(群场景成员缓存昵称/名片,失败退 uin 字符串)。 */
1640
- async function senderNameOf(api, msg) {
1641
- if (api.groupCache !== void 0 && msg.chatType === ChatType.GROUP) {
1642
- const member = await api.groupCache.getMember(msg.peerUid, msg.senderUid).catch((err) => {
1643
- api.logger?.debug({
1644
- group: msg.peerUid,
1645
- member: msg.senderUid,
1646
- error: err instanceof Error ? err.message : String(err)
1647
- }, "milky: 发送者成员缓存读取失败,退 uin 字符串");
1648
- });
1649
- const name = member?.cardName !== void 0 && member.cardName !== "" ? member.cardName : member?.nick;
1650
- if (name !== void 0 && name !== "") return name;
1651
- }
1652
- return msg.senderUin;
1653
- }
1654
- /** 单条消息 → 接收段(canonical 映射 + forward 段注入,forward 不经 canonical)。 */
1655
- function receiveSegmentsOf(msg, uidToUin) {
1656
- const segments = canonicalToIncomingSegments(toCanonicalElements(msg), { ...uidToUin.size > 0 ? { uidToUin } : {} });
1657
- const fwd = msg.elements.find((el) => el.multiForwardMsgElement != null)?.multiForwardMsgElement;
1658
- if (fwd !== void 0) segments.push(incomingForwardSegment(fwd.resId, fwd.fileName));
1659
- return segments;
1660
- }
1661
- /** QQ 头像 URL(公开头像服务,640px)。 */
1662
- function avatarUrlOf(uin) {
1663
- return uin === "" ? "" : `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=640`;
1664
- }
1665
- // src/milky/action/message-ops.ts
1666
- const recallFields = { message_seq: z.number().int().min(0) };
1667
- /** 消息操作域动作工厂(recall×2 / mark_read / 收藏表情 / 资源反查 / 私聊文件上传)。 */
1668
- function createMessageOpsActions(api) {
1669
- return [
1670
- defineMilkyAction({
1671
- name: "recall_private_message",
1672
- schema: z.object({
1673
- user_id: z.number().int().min(10001),
1674
- ...recallFields
1675
- }),
1676
- handle: async (payload) => {
1677
- await recallBySeq(await api.resolvePeer("friend", payload.user_id), payload.message_seq, api);
1678
- return {};
1679
- }
1680
- }),
1681
- defineMilkyAction({
1682
- name: "recall_group_message",
1683
- schema: z.object({
1684
- group_id: z.number().int().min(10001),
1685
- ...recallFields
1686
- }),
1687
- handle: async (payload) => {
1688
- await recallBySeq(await api.resolvePeer("group", payload.group_id), payload.message_seq, api);
1689
- return {};
1690
- }
1691
- }),
1692
- defineMilkyAction({
1693
- name: "mark_message_as_read",
1694
- schema: z.object({ ...peerMessageFields }),
1695
- handle: async (payload) => {
1696
- const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
1697
- await api.msgApi.markRead(peer);
1698
- return {};
1699
- }
1700
- }),
1701
- defineMilkyAction({
1702
- name: "get_custom_face_url_list",
1703
- schema: z.object({}),
1704
- handle: async () => ({ urls: await api.msgApi.queryFavEmojis() })
1705
- }),
1706
- defineMilkyAction({
1707
- name: "get_resource_temp_url",
1708
- schema: z.object({ resource_id: z.string().min(1) }),
1709
- handle: async (payload) => {
1710
- const id = payload.resource_id;
1711
- if (id.startsWith("http://") || id.startsWith("https://") || id.startsWith("base64://")) return { url: id };
1712
- throw kernelError(`资源 ${id} 无临时链接(resource_id 非链接形态)`, "NOT_FOUND");
1713
- }
1714
- }),
1715
- defineMilkyAction({
1716
- name: "upload_private_file",
1717
- schema: z.object({
1718
- user_id: z.number().int().min(10001),
1719
- file_uri: z.string().min(1),
1720
- file_name: z.string().min(1)
1721
- }),
1722
- handle: async (payload) => {
1723
- const path = await resolveUriToPath(payload.file_uri, api.mediaDir);
1724
- const peer = await api.resolvePeer("friend", payload.user_id);
1725
- return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1726
- }
1727
- })
1728
- ];
1729
- }
1730
- /** seq → msgId(反查)→ recallMessage。 */
1731
- async function recallBySeq(peer, seq, api) {
1732
- const msgId = await api.resolveMsgIdBySeq(peer, seq, peer.chatType);
1733
- if (msgId === void 0) throw kernelError(`消息 ${seq} 不存在`, "NOT_FOUND");
1734
- await api.msgApi.recallMessage(peer, [msgId]);
1735
- }
1736
- // src/milky/action/message-send.ts
1737
- /**
1738
- * OutgoingSegment 宽松校验:入口只保证「{type, data}」形状,字段级转换在
1739
- * outgoingSegmentsToCanonical 内做(未知段跳过 = 规范兼容性要求)。
1740
- */
1741
- const outgoingSegmentSchema = z.object({
1742
- type: z.string(),
1743
- data: z.record(z.string(), z.unknown())
1744
- }).loose();
1745
- const sendMessageFields = { message: z.array(outgoingSegmentSchema).min(1).max(200) };
1746
- /** 消息发送域动作工厂(send_private_message / send_group_message)。 */
1747
- function createMessageSendActions(api) {
1748
- return [defineMilkyAction({
1749
- name: "send_private_message",
1750
- schema: z.object({
1751
- user_id: z.number().int().min(10001),
1752
- ...sendMessageFields
1753
- }),
1754
- handle: async (payload) => {
1755
- return await sendMilkyMessage(await api.resolvePeer("friend", payload.user_id), payload.message, api);
1756
- }
1757
- }), defineMilkyAction({
1758
- name: "send_group_message",
1759
- schema: z.object({
1760
- group_id: z.number().int().min(10001),
1761
- ...sendMessageFields
1762
- }),
1763
- handle: async (payload) => {
1764
- return await sendMilkyMessage(await api.resolvePeer("group", payload.group_id), payload.message, api);
1765
- }
1766
- })];
1767
- }
1768
- /** ---------- 发送核心与组装链 ---------- */
1769
- /** 发送核心:segments → canonical(URI/ID 转换)→ sendMessage → 回查输出。
1770
- * forward 段分流到组装链(临时消息法)。 */
1771
- async function sendMilkyMessage(peer, segments, api) {
1772
- if (segments.some((s) => s.type === "forward")) return await sendForwardComposition(peer, segments, api);
1773
- const { elements, atUins } = outgoingSegmentsToCanonical(segments);
1774
- const resolved = await resolveElements(elements, atUins, api);
1775
- if (resolved.length === 0) throw kernelError("消息内容为空(全部消息段不可用)", "INVALID_PARAM");
1776
- const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1777
- return await api.resolveSentOutput(peer, msgId);
1778
- }
1779
- /**
1780
- * forward 段组装链(milky.md §0.6):仅支持单 forward 单独发。
1781
- * 临时消息法:逐条发送 messages[i].segments → sendForwardMessage(buildMultiForwardMsg
1782
- * 以目标 peer 的真实消息组装 → sendMsg)→ best-effort 撤回临时消息 → 回查输出。
1783
- *
1784
- * 已知差异(规范语义 vs kernel 出口,待实机联调):节点发送者恒为机器人自己
1785
- * (user_id / sender_name / time 不参与组装);title / preview / summary / prompt 忽略。
1786
- */
1787
- async function sendForwardComposition(peer, segments, api) {
1788
- if (segments.length !== 1) throw kernelError("forward 段必须单独发送(不支持与其他消息段混发)", "INVALID_PARAM");
1789
- const [forward] = segments;
1790
- if (forward === void 0 || forward.type !== "forward") throw kernelError("forward 组装链收到非 forward 段", "UNKNOWN");
1791
- const messages = narrowForwardMessages(forward);
1792
- const srcMsgIds = [];
1793
- for (const [i, item] of messages.entries()) {
1794
- const { elements, atUins } = outgoingSegmentsToCanonical(item.segments);
1795
- const resolved = await resolveElements(elements, atUins, api);
1796
- if (resolved.length === 0) throw kernelError(`forward 第 ${i + 1} 条消息无可用内容段`, "INVALID_PARAM");
1797
- const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1798
- srcMsgIds.push(msgId);
1799
- }
1800
- const { msgId } = await api.msgApi.sendForwardMessage(peer, peer, srcMsgIds);
1801
- await recallTempMessages(peer, srcMsgIds, api);
1802
- return await api.resolveSentOutput(peer, msgId);
1803
- }
1804
- /**
1805
- * forward 段载荷收窄(入口 schema 只保证 data 为 record):messages 非空数组,
1806
- * 项内 segments 非空数组。user_id / sender_name / time 不参与组装不校验
1807
- * (丢弃字段不设门槛);title / preview / summary / prompt 忽略。
1808
- */
1809
- function narrowForwardMessages(forward) {
1810
- const raw = forward.data.messages;
1811
- if (!Array.isArray(raw) || raw.length === 0) throw kernelError("forward 段 messages 必须是非空数组", "INVALID_PARAM");
1812
- const out = [];
1813
- for (const item of raw) {
1814
- if (typeof item !== "object" || item === null) throw kernelError("forward 段 messages 项必须是对象", "INVALID_PARAM");
1815
- const segments = item.segments;
1816
- if (!Array.isArray(segments) || segments.length === 0) throw kernelError("forward 段 messages 项的 segments 必须是非空数组", "INVALID_PARAM");
1817
- out.push(item);
1818
- }
1819
- return out;
1820
- }
1821
- /** 临时消息清理(best-effort:失败只留可见垃圾,转发已发出——warn 可观测不抛)。 */
1822
- async function recallTempMessages(peer, msgIds, api) {
1823
- try {
1824
- await api.msgApi.recallMessage(peer, msgIds);
1825
- } catch (e) {
1826
- api.logger?.warn({
1827
- peer: peer.peerUid,
1828
- count: msgIds.length,
1829
- error: e instanceof Error ? e.message : String(e)
1830
- }, "milky: forward 临时消息撤回失败(转发已发出)");
1831
- }
1832
- }
1833
- /** ---------- 元素二次解析 ---------- */
1834
- /** 元素二次解析:at uin→uid + 远程媒体 URI 落盘(reply seq 已在映射层兜底原样)。 */
1835
- async function resolveElements(elements, atUins, api) {
1836
- const uinToUid = await resolveAtUins(atUins, api);
1837
- const out = [];
1838
- for (const el of elements) out.push(await resolveElement(el, uinToUid, api));
1839
- return out;
1840
- }
1841
- /** at uin→uid 批量转换(失败返回 undefined:at 原样 uin,交 QQ 端判断)。 */
1842
- async function resolveAtUins(atUins, api) {
1843
- if (atUins.length === 0) return;
1844
- try {
1845
- return await api.uinToUid(atUins);
1846
- } catch (err) {
1847
- api.logger?.warn({
1848
- count: atUins.length,
1849
- error: err instanceof Error ? err.message : String(err)
1850
- }, "milky: at uin→uid 失败,at 段原样发送");
1851
- return;
1852
- }
1853
- }
1854
- /** 单元素解析:at 目标替换 / 远程媒体 URI 落盘 / 其余原样。 */
1855
- async function resolveElement(el, uinToUid, api) {
1856
- if (el.type === "at" && el.target !== "all") return {
1857
- ...el,
1858
- target: uinToUid?.get(el.target) ?? el.target
1859
- };
1860
- if (isRemoteMediaUri(el)) {
1861
- const media = el;
1862
- return {
1863
- ...media,
1864
- path: await resolveMediaUri(media.path, api.mediaDir)
1865
- };
1866
- }
1867
- return el;
1868
- }
1869
- /** 远程媒体元素(image/voice/video 且 path 为需落盘的 URI)。 */
1870
- function isRemoteMediaUri(el) {
1871
- return (el.type === "image" || el.type === "voice" || el.type === "video") && (el.path.startsWith("http://") || el.path.startsWith("https://") || el.path.startsWith("base64://"));
1872
- }
1873
- // src/milky/action/profile.ts
1874
- /**
1875
- * Milky 资料类动作:get_user_profile / get_friend_info / set_avatar /
1876
- * set_nickname / set_bio / get_cookies / get_csrf_token。
1877
- *
1878
- * set_avatar 的 uri 经 media-uri 解析(本地路径 / file:// 直用,http(s)/base64
1879
- * 落盘 mediaDir);get_cookies 输出规范为单字符串(k=v 分号拼接);
1880
- * get_csrf_token = qun.qq.com cookies 的 skey → bkn(OB11 get_csrf_token 同口径)。
1881
- */
1882
- /** CSRF 计算域名(bkn 口径,OB11 get_csrf_token 同源)。 */
1883
- const CSRF_DOMAIN = "qun.qq.com";
1884
- /** 资料类动作工厂(资料读取 / 头像昵称签名设置 / cookies 与 bkn)。 */
1885
- function createProfileActions(api) {
1886
- return [
1887
- defineMilkyAction({
1888
- name: "get_user_profile",
1889
- schema: z.object({ user_id: z.number().int().min(10001) }),
1890
- handle: async (payload) => {
1891
- const info = await api.profileApi.getStrangerInfo(String(payload.user_id));
1892
- return {
1893
- nickname: info.nickname,
1894
- qid: info.qid,
1895
- age: info.age,
1896
- sex: info.sex,
1897
- remark: info.remark,
1898
- bio: info.long_nick,
1899
- level: info.qq_level,
1900
- country: "",
1901
- city: "",
1902
- school: ""
1903
- };
1904
- }
1905
- }),
1906
- defineMilkyAction({
1907
- name: "get_friend_info",
1908
- schema: z.object({
1909
- user_id: z.number().int().min(10001),
1910
- no_cache: z.boolean().nullable().optional()
1911
- }),
1912
- handle: async (payload) => {
1913
- const uin = String(payload.user_id);
1914
- const friend = (await api.friendApi.getFriendList()).find((f) => f.uin === uin);
1915
- if (friend === void 0) throw kernelError(`好友 ${uin} 不存在`, "NOT_FOUND");
1916
- return { friend: toFriendEntity(friend, friend.uin, friend.nickname) };
1917
- }
1918
- }),
1919
- defineMilkyAction({
1920
- name: "set_avatar",
1921
- schema: z.object({ uri: z.string().min(1) }),
1922
- handle: async (payload) => {
1923
- const path = await resolveMediaUri(payload.uri, api.mediaDir);
1924
- await api.profileApi.setHeader(path);
1925
- return {};
1926
- }
1927
- }),
1928
- defineMilkyAction({
1929
- name: "set_nickname",
1930
- schema: z.object({ new_nickname: z.string() }),
1931
- handle: async (payload) => {
1932
- await api.profileApi.setNickName(payload.new_nickname);
1933
- return {};
1934
- }
1935
- }),
1936
- defineMilkyAction({
1937
- name: "set_bio",
1938
- schema: z.object({ new_bio: z.string() }),
1939
- handle: async (payload) => {
1940
- await api.profileApi.setLongNick(payload.new_bio);
1941
- return {};
1942
- }
1943
- }),
1944
- defineMilkyAction({
1945
- name: "get_cookies",
1946
- schema: z.object({ domain: z.string().min(1) }),
1947
- handle: async (payload) => {
1948
- const cookies = await api.ticketApi.getCookies(payload.domain, api.self.uin);
1949
- return { cookies: Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ") };
1950
- }
1951
- }),
1952
- defineMilkyAction({
1953
- name: "get_csrf_token",
1954
- schema: z.object({}).strict(),
1955
- handle: async () => {
1956
- const cookies = await api.ticketApi.getCookies(CSRF_DOMAIN, api.self.uin);
1957
- return { csrf_token: TicketApi.getBkn(cookies["skey"] ?? "") };
1958
- }
1959
- })
1960
- ];
1961
- }
1962
- // src/milky/action/social.ts
1963
- /** 可选布尔(nudge / pin 入参共用口径)。 */
1964
- const optBool = z.boolean().nullable().optional();
1965
- /** 社交类动作工厂(好友/群列表、赞、删好友、申请处理、戳一戳、会话置顶)。 */
1966
- function createSocialActions(api) {
1967
- return [
1968
- defineMilkyAction({
1969
- name: "get_friend_list",
1970
- schema: z.object({}).strict(),
1971
- handle: async () => {
1972
- return { friends: (await api.friendApi.getFriendList()).map((f) => toFriendEntity(f, f.uin, f.nickname)) };
1973
- }
1974
- }),
1975
- defineMilkyAction({
1976
- name: "get_group_list",
1977
- schema: z.object({}).strict(),
1978
- handle: async () => {
1979
- return { groups: (api.groupCache !== void 0 ? await api.groupCache.listGroupsRefreshed() : await api.groupApi.getGroupList(true)).map(groupListToEntity) };
1980
- }
1981
- }),
1982
- defineMilkyAction({
1983
- name: "send_profile_like",
1984
- schema: z.object({
1985
- user_id: z.number().int().min(10001),
1986
- count: z.number().int().min(0).nullable().optional()
1987
- }),
1988
- handle: async (payload) => {
1989
- const uid = await api.resolveUidFromUin(payload.user_id);
1990
- await api.profileLikeApi.sendLike(uid, payload.count ?? 1);
1991
- return {};
1992
- }
1993
- }),
1994
- defineMilkyAction({
1995
- name: "delete_friend",
1996
- schema: z.object({ user_id: z.number().int().min(10001) }),
1997
- handle: async (payload) => {
1998
- const uid = await api.resolveUidFromUin(payload.user_id);
1999
- await api.friendApi.deleteFriend(uid);
2000
- return {};
2001
- }
2002
- }),
2003
- defineMilkyAction({
2004
- name: "get_friend_requests",
2005
- schema: z.object({
2006
- limit: z.number().int().min(0).nullable().optional(),
2007
- is_filtered: z.boolean().nullable().optional()
2008
- }),
2009
- handle: async (payload) => {
2010
- const reqs = await api.friendApi.getBuddyReqList();
2011
- let uidToUin = /* @__PURE__ */ new Map();
2012
- if (reqs.length > 0) uidToUin = await api.uidToUin(reqs.map((req) => req.friendUid)).catch((err) => {
2013
- api.logger?.warn({
2014
- count: reqs.length,
2015
- error: err instanceof Error ? err.message : String(err)
2016
- }, "milky: 好友申请 uid→uin 失败,initiator_id 兜底 0");
2017
- return /* @__PURE__ */ new Map();
2018
- });
2019
- const requests = reqs.map((req) => ({
2020
- time: Number(req.reqTime) || 0,
2021
- initiator_id: Number(uidToUin.get(req.friendUid)) || 0,
2022
- initiator_uid: req.friendUid,
2023
- target_user_id: Number(api.self.uin),
2024
- target_user_uid: api.self.uid ?? "",
2025
- state: "pending",
2026
- comment: typeof req["words"] === "string" ? req["words"] : "",
2027
- via: req.sourceName ?? "",
2028
- is_filtered: false
2029
- }));
2030
- const limit = payload.limit ?? requests.length;
2031
- return { requests: requests.slice(0, limit) };
2032
- }
2033
- }),
2034
- defineMilkyAction({
2035
- name: "accept_friend_request",
2036
- schema: friendRequestRespondSchema,
2037
- handle: async (payload) => {
2038
- const notify = await findBuddyReq(api, payload.initiator_uid);
2039
- await api.friendApi.handleFriendRequest(notify, true);
2040
- return {};
2041
- }
2042
- }),
2043
- defineMilkyAction({
2044
- name: "reject_friend_request",
2045
- schema: friendRequestRespondSchema,
2046
- handle: async (payload) => {
2047
- const notify = await findBuddyReq(api, payload.initiator_uid);
2048
- await api.friendApi.handleFriendRequest(notify, false);
2049
- return {};
2050
- }
2051
- }),
2052
- defineMilkyAction({
2053
- name: "send_friend_nudge",
2054
- schema: z.object({
2055
- user_id: z.number().int().min(10001),
2056
- is_self: optBool
2057
- }),
2058
- handle: async (payload) => {
2059
- const callerUid = requireSelfUid(api);
2060
- const receiverUid = payload.is_self === true ? callerUid : await api.resolveUidFromUin(payload.user_id);
2061
- const peer = await api.resolvePeer("friend", payload.user_id);
2062
- await api.msgApi.sendNudge(peer, {
2063
- receiverUid,
2064
- callerUid
2065
- });
2066
- return {};
2067
- }
2068
- }),
2069
- defineMilkyAction({
2070
- name: "get_peer_pins",
2071
- schema: z.object({}),
2072
- handle: async () => {
2073
- const pinned = await api.recentContactApi.getPinnedContacts();
2074
- const friendUids = pinned.filter((p) => p.scene === "friend").map((p) => p.peerUid);
2075
- const groupCodes = pinned.filter((p) => p.scene === "group").map((p) => p.peerUid);
2076
- return {
2077
- friends: await pinnedFriendEntities(api, friendUids),
2078
- groups: await pinnedGroupEntities(api, groupCodes)
2079
- };
2080
- }
2081
- }),
2082
- defineMilkyAction({
2083
- name: "set_peer_pin",
2084
- schema: z.object({
2085
- message_scene: z.enum([
2086
- "friend",
2087
- "group",
2088
- "temp"
2089
- ]),
2090
- peer_id: z.number().int().min(10001),
2091
- is_pinned: optBool
2092
- }),
2093
- handle: async (payload) => {
2094
- const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
2095
- await api.msgApi.setContactTop(peer, payload.is_pinned ?? true);
2096
- return {};
2097
- }
2098
- })
2099
- ];
2100
- }
2101
- /** accept/reject_friend_request 共入参(is_filtered / reason 仅 schema 兼容)。 */
2102
- const friendRequestRespondSchema = z.object({
2103
- initiator_uid: z.string().min(1),
2104
- is_filtered: z.boolean().nullable().optional(),
2105
- reason: z.string().nullable().optional()
2106
- });
2107
- /** 置顶好友实体(uid 匹配全量好友列表;未命中跳过)。 */
2108
- async function pinnedFriendEntities(api, uids) {
2109
- if (uids.length === 0) return [];
2110
- const all = await api.friendApi.getFriendList();
2111
- const byUid = new Map(all.map((f) => [f.uid, f]));
2112
- return uids.flatMap((uid) => {
2113
- const f = byUid.get(uid);
2114
- return f !== void 0 ? [toFriendEntity(f, f.uin, f.nickname)] : [];
2115
- });
2116
- }
2117
- /** 置顶群实体(groupCode 匹配群列表,缓存优先;未命中跳过)。 */
2118
- async function pinnedGroupEntities(api, groupCodes) {
2119
- if (groupCodes.length === 0) return [];
2120
- const groups = api.groupCache !== void 0 ? await api.groupCache.listGroupsRefreshed() : await api.groupApi.getGroupList(true);
2121
- const byCode = new Map(groups.map((g) => [g.groupCode, g]));
2122
- return groupCodes.flatMap((code) => {
2123
- const g = byCode.get(code);
2124
- return g !== void 0 ? [groupListToEntity(g)] : [];
2125
- });
2126
- }
2127
- /** self.uid 必备(nudge 发送的 callerUid)。 */
2128
- function requireSelfUid(api) {
2129
- const uid = api.self.uid;
2130
- if (uid === void 0 || uid === "") throw kernelError("登录身份缺 uid(无法发起戳一戳)", "INVALID_PARAM");
2131
- return uid;
2132
- }
2133
- // src/milky/action/system.ts
2134
- /**
2135
- * Milky 系统类动作:get_login_info / get_impl_info
2136
- *
2137
- * get_impl_info 是 Milky 的版本协商面(规范 §compatibility):milky_version
2138
- * 固定 "1.3"(目标协议版本 1.3.0),qq_protocol_type 固定 windows(自建宿主)。
2139
- */
2140
- /** Milky 协议版本(docs/protocols/milky.md:目标 1.3.0)。 */
2141
- const MILKY_VERSION = "1.3";
2142
- /** 系统类动作工厂(login_info / impl_info)。 */
2143
- function createSystemActions(api) {
2144
- return [defineMilkyAction({
2145
- name: "get_login_info",
2146
- schema: z.object({}).strict(),
2147
- handle: async () => ({
2148
- uin: Number(api.self.uin),
2149
- nickname: api.self.nickname
2150
- })
2151
- }), defineMilkyAction({
2152
- name: "get_impl_info",
2153
- schema: z.object({}).strict(),
2154
- handle: async () => ({
2155
- impl_name: "napukettoqq",
2156
- impl_version: api.implVersion,
2157
- qq_protocol_version: api.qqVersion,
2158
- qq_protocol_type: "windows",
2159
- milky_version: MILKY_VERSION
2160
- })
2161
- })];
2162
- }
2163
- // src/milky/action/index.ts
2164
- /**
2165
- * Milky 动作注册表:动作按领域文件组织(每文件一个 create*Actions 工厂),
2166
- * 本入口按固定顺序遍历注册——新增动作在领域文件的工厂里登记即可。
2167
- *
2168
- * 64 动作 = docs/protocols/milky.md §9 清单全量。
2169
- */
2170
- /** Milky 动作域工厂(注册顺序即列表顺序:system → message → social/profile → group)。 */
2171
- const ACTION_FACTORIES = [
2172
- createSystemActions,
2173
- createMessageSendActions,
2174
- createMessageQueryActions,
2175
- createMessageOpsActions,
2176
- createSocialActions,
2177
- createProfileActions,
2178
- createGroupQueryActions,
2179
- createGroupManageActions,
2180
- createGroupEssenceActions,
2181
- createGroupNoticeActions,
2182
- createGroupFileActions
2183
- ];
2184
- /** 构建 Milky 动作注册表(64 个动作,领域工厂遍历注册)。 */
2185
- function createMilkyActionRegistry(opts) {
2186
- const registry = new ActionRegistry();
2187
- for (const factory of ACTION_FACTORIES) for (const action of factory(opts.api)) registry.register(action);
2188
- return registry;
2189
- }
2190
- // src/milky/enrichment.ts
2191
- /** 资料详情兜底的单批上限(好友申请批通常只有个位数,超限多为历史积压)。 */
2192
- const MAX_PROFILE_LOOKUPS = 10;
2193
- /** Milky 收链路异步回填器。 */
2194
- var MilkyEnrichment = class {
2195
- api;
2196
- constructor(deps) {
2197
- this.api = deps.api;
2198
- }
2199
- /**
2200
- * uid 批量 → uin(空集/失败返回 undefined 语义:调用方用空 Map)。
2201
- *
2202
- * `profileFallback` 时才做资料详情兜底(issue #122):好友申请的申请人通常不在
2203
- * 任何群里,群口径必然命中不了;而 grayTip 一类高频路径不做兜底——群口径整体失败
2204
- * 时逐 uid 打 IPC 会把收链路拖垮。
2205
- */
2206
- async resolveUidToUin(uids, options = {}) {
2207
- const unique = [...new Set(uids.filter((uid) => uid !== ""))];
2208
- if (unique.length === 0) return;
2209
- const map = await this.api.uidToUin(unique).catch((err) => {
2210
- this.api.logger?.warn({
2211
- count: unique.length,
2212
- error: err instanceof Error ? err.message : String(err)
2213
- }, "milky: uid→uin 批量转换失败,事件退用 uid");
2214
- return /* @__PURE__ */ new Map();
2215
- });
2216
- if (options.profileFallback === true) await this.fillMissingUins(unique, map);
2217
- return map;
2218
- }
2219
- /**
2220
- * 群口径未命中的 uid 逐个走 `profileApi.getUinByUid` 兜底(原地补 map)。
2221
- * fail-soft:单条失败 / 查不到保持未命中(翻译层退 0);条数设上限,防历史积压
2222
- * 批次把逐条 IPC 打满。
2223
- */
2224
- async fillMissingUins(uids, map) {
2225
- const missing = uids.filter((uid) => !map.has(uid));
2226
- for (const uid of missing.slice(0, MAX_PROFILE_LOOKUPS)) try {
2227
- const uin = await this.api.profileApi.getUinByUid(uid);
2228
- if (uin !== null) map.set(uid, uin);
2229
- } catch (err) {
2230
- this.api.logger?.debug({ error: err instanceof Error ? err.message : String(err) }, "milky: uid→uin 资料兜底失败(该 uid 退 0)");
2231
- }
2232
- if (missing.length > MAX_PROFILE_LOOKUPS) this.api.logger?.debug({
2233
- missing: missing.length,
2234
- limit: MAX_PROFILE_LOOKUPS
2235
- }, "milky: 待兜底 uid 超上限,其余保持未命中");
2236
- }
2237
- /** at uid → uin 批量转换(mention.user_id 用;失败 mention 段跳过)。 */
2238
- async fillMentionUids(elements, ctx) {
2239
- const atUids = elements.filter((el) => el.type === "at" && el.target !== "all").map((el) => el.target);
2240
- if (atUids.length === 0) return;
2241
- try {
2242
- ctx.uidToUin = await this.api.uidToUin(atUids);
2243
- } catch (err) {
2244
- this.api.logger?.warn({
2245
- count: atUids.length,
2246
- error: err instanceof Error ? err.message : String(err)
2247
- }, "milky: at uid→uin 失败,mention 段跳过");
2248
- }
2249
- }
2250
- /** 群场景实体回填(GroupCache 缓存优先,失败最小实体兜底)。 */
2251
- async fillGroupEntities(msg, ctx) {
2252
- if (msg.chatType !== ChatType.GROUP || this.api.groupCache === void 0) return;
2253
- const [detail, member] = await Promise.all([this.api.groupCache.getGroupDetail(msg.peerUid).catch((err) => {
2254
- this.api.logger?.warn({
2255
- group: msg.peerUid,
2256
- error: err instanceof Error ? err.message : String(err)
2257
- }, "milky: 群详情缓存读取失败,实体回填退化");
2258
- }), this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch((err) => {
2259
- this.api.logger?.debug({
2260
- group: msg.peerUid,
2261
- member: msg.senderUid,
2262
- error: err instanceof Error ? err.message : String(err)
2263
- }, "milky: 群成员缓存读取失败,实体回填退化");
2264
- })]);
2265
- ctx.groupEntity = toGroupEntity(detail, msg.peerUid);
2266
- ctx.groupMemberEntity = toGroupMemberEntity(member, msg.peerUid, msg.senderUin);
2267
- }
2268
- };
2269
- // src/milky/event-pipeline.ts
2270
- var MilkyEventPipeline = class {
2271
- deps;
2272
- unsubscribes = [];
2273
- constructor(deps) {
2274
- this.deps = deps;
2275
- }
2276
- /** 事件链异步失败兜底(单条/整批丢弃,warn 留痕不打断订阅)。 */
2277
- logFailure(kind, err) {
2278
- logEventFailure(this.deps.logger, `milky: ${kind} 翻译失败(丢弃)`, err);
2279
- }
2280
- /** 订阅 kernel 事件(消息 + 群 + 好友 + ,幂等;路由到 inbound/)。 */
2281
- subscribe() {
2282
- if (this.unsubscribes.length > 0) return;
2283
- this.deps.request.markStartup();
2284
- const { msgChannel, groupChannel, buddyChannel, recentContactChannel, loginChannel } = this.deps;
2285
- this.unsubscribes.push(subscribeRawMessages(msgChannel, (msg) => this.deps.message.handle(msg).catch((err) => {
2286
- this.logFailure("message_receive", err);
2287
- }), { logger: this.deps.logger }), msgChannel.on("Msg/onRecvSysMsg", (a) => this.deps.sysMsg.handleRawArg(a)), msgChannel.on("Msg/onRecvOfflineFileMsg", (m) => this.deps.fileNotice.fileMessages(m)), msgChannel.on("Msg/onFileMsgCome", (m) => this.deps.fileNotice.fileMessages(m)));
2288
- if (groupChannel !== void 0) this.unsubscribes.push(groupChannel.on("Group/onGroupNotifiesUpdated", (doubt, notifies) => {
2289
- this.deps.request.groupNotifies(doubt, notifies).catch((err) => {
2290
- this.logFailure("group request", err);
2291
- });
2292
- }), groupChannel.on("Group/onGroupEssenceListChange", (a) => this.deps.essence.change(a)));
2293
- if (buddyChannel !== void 0) this.unsubscribes.push(buddyChannel.on("Buddy/onBuddyReqChange", (a) => this.deps.request.buddyReqs(a)));
2294
- if (recentContactChannel !== void 0) {
2295
- this.unsubscribes.push(recentContactChannel.on("RecentContact/onRecentContactListChangedVer2", (lists) => {
2296
- this.deps.pin.handleChanges(lists);
2297
- }));
2298
- this.deps.pin.seed();
2299
- }
2300
- if (loginChannel !== void 0) this.unsubscribes.push(loginChannel.on("Login/onLoginDisConnected", (...args) => {
2301
- this.deps.fileNotice.botOffline("disconnected", args);
2302
- }), loginChannel.on("Login/onLogoutSucceed", (...args) => {
2303
- this.deps.fileNotice.botOffline("logout", args);
2304
- }));
2305
- }
2306
- /** 退订(幂等)。 */
2307
- unsubscribeAll() {
2308
- for (const off of this.unsubscribes) off();
2309
- this.unsubscribes = [];
2310
- }
2311
- };
2312
- // src/milky/helper/state/seq-index.ts
2313
- /** 单方向最大条目数(测试用例引用容量语义)。 */
2314
- const MAX_ENTRIES = 4096;
2315
- var MessageSeqIndex = class {
2316
- /** `${chatType}:${peerUid}:${seq}` → msgId。 */
2317
- seqToMsg = /* @__PURE__ */ new Map();
2318
- /** msgId → seq 元信息。 */
2319
- msgToMeta = /* @__PURE__ */ new Map();
2320
- /** 合并转发 resId → 定位信息(get_forwarded_messages)。 */
2321
- forwards = /* @__PURE__ */ new Map();
2322
- /** 接收链路登记(一条消息双向写入;重复 msgId 覆盖)。 */
2323
- record(msg) {
2324
- const seq = Number(msg.msgSeq);
2325
- if (!Number.isFinite(seq) || seq < 0) return;
2326
- this.seqToMsg.set(this.key(msg.chatType, msg.peerUid, seq), msg.msgId);
2327
- this.msgToMeta.set(msg.msgId, {
2328
- seq,
2329
- senderUin: msg.senderUin,
2330
- timeSec: toUnixSeconds(msg.msgTime)
2331
- });
2332
- this.evict();
2333
- }
2334
- /** seq → msgId(反查;未登记返回 undefined)。 */
2335
- resolveMsgId(chatType, peerUid, seq) {
2336
- return this.seqToMsg.get(this.key(chatType, peerUid, seq));
2337
- }
2338
- /**
2339
- * 批量回填 reply 引用元信息(msgId → Milky reply 段 data 所需三元组)。
2340
- * 未命中的 id 不进表(翻译层按 0 兜底)。
2341
- */
2342
- collectReplyMeta(msgIds) {
2343
- const out = /* @__PURE__ */ new Map();
2344
- for (const id of msgIds) {
2345
- const m = this.msgToMeta.get(id);
2346
- if (m !== void 0) out.set(id, {
2347
- messageSeq: m.seq,
2348
- senderId: Number(m.senderUin) || 0,
2349
- time: m.timeSec
2350
- });
2351
- }
2352
- return out;
2353
- }
2354
- /** key 规则(chatType 数值 + peerUid + seq;peerUid 群聊=群号,C2C=uid)。 */
2355
- key(chatType, peerUid, seq) {
2356
- return `${chatType}:${peerUid}:${seq}`;
2357
- }
2358
- /**
2359
- * 登记合并转发(接收链路:消息含 multiForwardMsgElement 时调用)。
2360
- * resId 是 Milky forward_id 的来源;同一 resId 重复覆盖。
2361
- */
2362
- recordForward(resId, entry) {
2363
- if (resId === "") return;
2364
- this.forwards.set(resId, entry);
2365
- while (this.forwards.size > MAX_ENTRIES) {
2366
- const oldest = this.forwards.keys().next().value;
2367
- if (oldest === void 0) break;
2368
- this.forwards.delete(oldest);
2369
- }
2370
- }
2371
- /** resId → 转发定位(get_forwarded_messages;未登记返回 undefined)。 */
2372
- resolveForward(resId) {
2373
- return this.forwards.get(resId);
2374
- }
2375
- /** FIFO 淘汰到容量上限内。 */
2376
- evict() {
2377
- while (this.seqToMsg.size > MAX_ENTRIES) {
2378
- const oldest = this.seqToMsg.keys().next().value;
2379
- if (oldest === void 0) break;
2380
- this.seqToMsg.delete(oldest);
2381
- }
2382
- while (this.msgToMeta.size > MAX_ENTRIES) {
2383
- const oldest = this.msgToMeta.keys().next().value;
2384
- if (oldest === void 0) break;
2385
- this.msgToMeta.delete(oldest);
2386
- }
2387
- }
2388
- };
2389
- // src/milky/helper/state/recent-keys.ts
2390
- /**
2391
- * 带过期去重键缓存(Milky)
2392
- *
2393
- * 两个场景共用:friend_file_upload 双回调(onRecvOfflineFileMsg / onFileMsgCome
2394
- * 同载荷,按 msgId 去重)与 group_essence_message_change 双路径(732:1 快路径
2395
- * vs 列表 diff,按 群:seq:方向 去重)。claim 语义 = 未登记过(或已过期)则登记
2396
- * 并返回 true——调用方据此决定是否广播。
2397
- */
2398
- var RecentKeyCache = class {
2399
- entries = /* @__PURE__ */ new Map();
2400
- ttlMs;
2401
- constructor(ttlMs) {
2402
- this.ttlMs = ttlMs;
2403
- }
2404
- /** 未命中则登记并返回 true(应广播);命中(窗口内重复)返回 false。 */
2405
- claim(key, now = Date.now()) {
2406
- this.prune(now);
2407
- const expiry = this.entries.get(key);
2408
- if (expiry !== void 0 && expiry > now) return false;
2409
- this.entries.set(key, now + this.ttlMs);
2410
- return true;
2411
- }
2412
- /** 惰性清理过期键(每次 claim 顺带执行,量级小无需定时器)。 */
2413
- prune(now) {
2414
- for (const [key, expiry] of this.entries) if (expiry <= now) this.entries.delete(key);
2415
- }
2416
- };
2417
- // src/milky/inbound/essence.ts
2418
- /** Milky 精华域处理器(双路径去重 + 串行 diff 同步 + group_essence 事件广播)。 */
2419
- var MilkyInboundEssence = class {
2420
- deps;
2421
- essenceKeys = new RecentKeyCache(3e5);
2422
- essenceSync;
2423
- constructor(deps) {
2424
- this.deps = deps;
2425
- this.essenceSync = new EssenceListSync({
2426
- fetchList: (groupCode) => deps.api.webApi.getEssenceMsgList(groupCode),
2427
- onAdded: (groupCode, added) => this.broadcastAdded(groupCode, added),
2428
- onRemoved: (groupCode, removed) => this.broadcastRemoved(groupCode, removed),
2429
- onFetchError: (g, err) => deps.logger?.warn({
2430
- group: g,
2431
- err: String(err)
2432
- }, "milky: 精华列表拉取失败(diff 跳过)")
2433
- });
2434
- }
2435
- /** sysmsg 732:1 快路径去重守卫:非精华恒 true;精华 claim 失败(diff 已抢发)→ false。 */
2436
- claimFastPath(ruleKind, data) {
2437
- if (ruleKind !== "group_essence_message_change") return true;
2438
- const rec = data;
2439
- if (typeof rec.group_id !== "number" || typeof rec.message_seq !== "number") return true;
2440
- return this.claimChange(rec.group_id, rec.message_seq, true);
2441
- }
2442
- /** 精华列表变更:拉全量列表 diff(remove 路径 + operator 回填;串行防乱序)。 */
2443
- change(arg) {
2444
- const groupCode = narrowEssenceGroupArg(arg);
2445
- if (groupCode === null) {
2446
- this.deps.logger?.warn({ raw: sliceRaw(JSON.stringify(arg)) }, "milky: onGroupEssenceListChange 未知参数形状");
2447
- return;
2448
- }
2449
- this.essenceSync.enqueue(groupCode);
2450
- }
2451
- /** diff 广播:add(operator = add_digest_uin,快路径已发则跳过)→ remove(operator 省略)。 */
2452
- broadcastAdded(groupCode, added) {
2453
- const now = Math.floor(Date.now() / 1e3);
2454
- for (const item of added) if (this.claimChange(groupCode, item.messageSeq, true)) this.broadcastChange(groupCode, item.messageSeq, true, numericUin(item.operatorUin), now);
2455
- }
2456
- broadcastRemoved(groupCode, removed) {
2457
- const now = Math.floor(Date.now() / 1e3);
2458
- for (const seq of removed) if (this.claimChange(groupCode, seq, false)) this.broadcastChange(groupCode, seq, false, null, now);
2459
- }
2460
- broadcastChange(groupCode, seq, isSet, operatorId, time) {
2461
- this.deps.broadcast({
2462
- time,
2463
- self_id: Number(this.deps.api.self.uin),
2464
- event_type: "group_essence_message_change",
2465
- data: {
2466
- group_id: Number(groupCode),
2467
- message_seq: seq,
2468
- is_set: isSet,
2469
- ...operatorId !== null ? { operator_id: operatorId } : {}
2470
- }
2471
- });
2472
- }
2473
- /** 双路径 claim(键 群:seq:方向;true = 未广播过,可发)。 */
2474
- claimChange(groupCode, seq, isSet) {
2475
- return this.essenceKeys.claim(`${groupCode}:${seq}:${isSet ? 1 : 0}`);
2476
- }
2477
- };
2478
- // src/milky/helper/event/file-upload.ts
2479
- /**
2480
- * friend_file_upload 翻译(Milky ,录制定型)
2481
- *
2482
- * 源:Msg/onRecvOfflineFileMsg 与 Msg/onFileMsgCome(同载荷 RawMessage 数组,
2483
- * 双回调按 msgId 在适配器去重);fileElement{fileName, fileSize 字符串,
2484
- * file10MMd5, fileUuid, ...},sendType 0=收到(sender=对端)/ 2=自己发出。
2485
- *
2486
- * 已知差异(milky.md §0.8.6):官方 file_hash 语义为 TriSHA1,接收侧
2487
- * fileSha/fileSha3 实测为空——取 file10MMd5(md5)充值,上传侧校准后回填。
2488
- */
2489
- /** 单条 C2C 文件消息 → 事件载荷(非 C2C / 无 fileElement / 无 fileUuid → null)。 */
2490
- function toFriendFileUploadData(msg, selfUin, uidToUin) {
2491
- if (msg.chatType !== ChatType.C2C) return null;
2492
- const file = msg.elements.find((el) => el.fileElement != null)?.fileElement;
2493
- if (file === void 0 || typeof file.fileUuid !== "string" || file.fileUuid === "") return null;
2494
- const isSelf = msg.sendType === 2 || String(msg.senderUin) === selfUin;
2495
- const userUin = msg.senderUin !== "" ? Number(msg.senderUin) : resolveUin(msg.senderUid, uidToUin);
2496
- const size = Number(file.fileSize ?? 0);
2497
- return {
2498
- user_id: Number.isFinite(userUin) ? userUin : 0,
2499
- file_id: file.fileUuid,
2500
- file_name: file.fileName ?? "",
2501
- file_size: Number.isFinite(size) ? size : 0,
2502
- file_hash: file.file10MMd5 ?? file.fileSha ?? "",
2503
- is_self: isSelf
2504
- };
2505
- }
2506
- // src/milky/inbound/file-notice.ts
2507
- /**
2508
- * Milky inbound 轻量通知域:私聊文件双回调(friend_file_upload,按 msgId 去重)
2509
- * 与 bot_offline(Login 桥,载荷零样本,reason 固定值)。置顶翻转在 pin.ts。
2510
- */
2511
- /** Milky 轻量通知域处理器(私聊文件 / bot_offline)。 */
2512
- var MilkyInboundFileNotice = class {
2513
- deps;
2514
- /** friend_file_upload 双回调去重(同载荷,按 msgId)。 */
2515
- fileKeys = new RecentKeyCache(6e5);
2516
- constructor(deps) {
2517
- this.deps = deps;
2518
- }
2519
- /** 私聊文件消息 → friend_file_upload(双回调同载荷,按 msgId 去重)。 */
2520
- fileMessages(msgs) {
2521
- forEachRawMessage(msgs, (msg) => {
2522
- const data = toFriendFileUploadData(msg, this.deps.api.self.uin, /* @__PURE__ */ new Map());
2523
- if (data === null) return;
2524
- if (data.user_id === 0) this.deps.logger?.debug({
2525
- msgId: msg.msgId,
2526
- senderUid: msg.senderUid
2527
- }, "milky: friend_file_upload senderUin 缺失(user_id=0)");
2528
- if (!this.fileKeys.claim(`file:${msg.msgId}`)) return;
2529
- this.deps.broadcast({
2530
- time: toUnixSeconds(msg.msgTime),
2531
- self_id: Number(this.deps.api.self.uin),
2532
- event_type: "friend_file_upload",
2533
- data
2534
- });
2535
- });
2536
- }
2537
- /** bot_offline:Login 桥回调(载荷零样本,reason 固定值 + raw 校准日志待野捕)。 */
2538
- botOffline(reason, args) {
2539
- this.deps.logger?.debug({
2540
- reason,
2541
- raw: sliceRaw(JSON.stringify(args))
2542
- }, "milky: bot_offline(reason 为固定值,回调载荷待野捕校准)");
2543
- this.deps.broadcast({
2544
- time: Math.floor(Date.now() / 1e3),
2545
- self_id: Number(this.deps.api.self.uin),
2546
- event_type: "bot_offline",
2547
- data: { reason }
2548
- });
2549
- }
2550
- };
2551
- // src/milky/helper/event/notice.ts
2552
- /** 事件信封公共字段。 */
2553
- function envelope(msg, ctx, eventType, data) {
2554
- return {
2555
- time: toUnixSeconds(msg.msgTime),
2556
- self_id: Number(ctx.selfUin),
2557
- event_type: eventType,
2558
- data
2559
- };
2560
- }
2561
- /** 单个 grayTip → Milky notice 事件(null = 不可翻译)。 */
2562
- function translateGrayTip(msg, g, ctx) {
2563
- if (g.aioOpGrayTipElement != null) return aioOpToEvent(msg, g, ctx);
2564
- if (g.subElementType === GrayTipSubType.GROUP) return groupElementToEvent(msg, g.groupElement, ctx);
2565
- return null;
2566
- }
2567
- /** 群成员变动类映射器表(键 = TipGroupElementType;缺项 = 不可翻译返回 null)。 */
2568
- const GROUP_CHANGE_MAPPERS = {
2569
- [TipGroupElementType.MEMBER_ADD]: toMemberIncrease,
2570
- [TipGroupElementType.QUIT]: toMemberDecrease,
2571
- [TipGroupElementType.SHUT_UP]: toShutUpEvent,
2572
- [TipGroupElementType.GROUP_NAME_MODIFIED]: toNameChange,
2573
- [TipGroupElementType.DISBANDED]: toDisband
2574
- };
2575
- function groupElementToEvent(msg, grp, ctx) {
2576
- if (grp == null || grp.type === void 0) return null;
2577
- const mapper = GROUP_CHANGE_MAPPERS[grp.type];
2578
- if (mapper === void 0) return null;
2579
- return mapper(msg, groupChangeCommon(grp, Number(msg.peerUid)), grp, ctx);
2580
- }
2581
- /** 禁言载荷优先(shutUp.member/admin 覆盖顶层 memberUid/adminUid)。 */
2582
- function groupChangeCommon(grp, groupId) {
2583
- return {
2584
- groupId,
2585
- memberUid: grp.shutUp?.member?.uid ?? grp.memberUid ?? "",
2586
- adminUid: grp.shutUp?.admin?.uid ?? grp.adminUid ?? ""
2587
- };
2588
- }
2589
- /** 群成员增加(管理员同意 → operator_id;邀请入群 → invitor_id)。 */
2590
- function toMemberIncrease(msg, common, _grp, ctx) {
2591
- const { groupId, memberUid, adminUid } = common;
2592
- return envelope(msg, ctx, "group_member_increase", {
2593
- group_id: groupId,
2594
- user_id: toUin(memberUid, ctx),
2595
- operator_id: adminUid !== "" && adminUid === memberUid ? toUin(adminUid, ctx) : null,
2596
- invitor_id: adminUid !== "" && adminUid !== memberUid ? toUin(adminUid, ctx) : null
2597
- });
2598
- }
2599
- /** 群成员减少(操作者与本人不同 = 被踢;主动退群无操作者)。 */
2600
- function toMemberDecrease(msg, common, _grp, ctx) {
2601
- const { groupId, memberUid, adminUid } = common;
2602
- return envelope(msg, ctx, "group_member_decrease", {
2603
- group_id: groupId,
2604
- user_id: toUin(memberUid, ctx),
2605
- operator_id: adminUid !== "" && adminUid !== memberUid ? toUin(adminUid, ctx) : null
2606
- });
2607
- }
2608
- /** 禁言(member 空 = 全员禁言口径;is_mute = 是否处于禁言态)。 */
2609
- function toShutUpEvent(msg, common, grp, ctx) {
2610
- const { groupId, memberUid, adminUid } = common;
2611
- const duration = Number(grp.shutUp?.duration ?? 0);
2612
- if (memberUid === "") return envelope(msg, ctx, "group_whole_mute", {
2613
- group_id: groupId,
2614
- operator_id: toUin(adminUid, ctx),
2615
- is_mute: duration > 0
2616
- });
2617
- return envelope(msg, ctx, "group_mute", {
2618
- group_id: groupId,
2619
- user_id: toUin(memberUid, ctx),
2620
- operator_id: toUin(adminUid, ctx),
2621
- duration
2622
- });
2623
- }
2624
- /** 改名 / 解散公共守卫:操作者 uid 不可得时不产出(schema operator_id 下限)。 */
2625
- function operatorOf(common) {
2626
- return common.adminUid !== "" ? common.adminUid : common.memberUid;
2627
- }
2628
- function toNameChange(msg, common, grp, ctx) {
2629
- const operatorUid = operatorOf(common);
2630
- if (operatorUid === "") return null;
2631
- return envelope(msg, ctx, "group_name_change", {
2632
- group_id: common.groupId,
2633
- new_group_name: grp.groupName ?? "",
2634
- operator_id: toUin(operatorUid, ctx)
2635
- });
2636
- }
2637
- function toDisband(msg, common, _grp, ctx) {
2638
- const operatorUid = operatorOf(common);
2639
- if (operatorUid === "") return null;
2640
- return envelope(msg, ctx, "group_disband", {
2641
- group_id: common.groupId,
2642
- operator_id: toUin(operatorUid, ctx)
2643
- });
2644
- }
2645
- /**
2646
- * aioOp → 戳一戳事件(friend_nudge / group_nudge)。
2647
- * aioOp 载荷完整字段形状未经实测(已证字段仅 operateType/peerUid):
2648
- * sender 取消息发送者、receiver 取 aioOp.peerUid(口径与 OB11 poke 一致,待校准);
2649
- * display_* 字段无来源,恒空串;始终打 raw 日志积累校准数据。
2650
- */
2651
- function aioOpToEvent(msg, g, ctx) {
2652
- const aioOp = g.aioOpGrayTipElement;
2653
- ctx.logger?.warn({ raw: JSON.stringify(g)?.slice(0, 2e3) }, "milky: aioOp grayTip raw(戳一戳待真实事件校准)");
2654
- if (msg.chatType === ChatType.GROUP) return envelope(msg, ctx, "group_nudge", {
2655
- group_id: Number(msg.peerUid),
2656
- sender_id: toUin(msg.senderUid, ctx),
2657
- receiver_id: toUin(aioOp?.peerUid ?? "", ctx),
2658
- display_action: "",
2659
- display_suffix: "",
2660
- display_action_img_url: ""
2661
- });
2662
- const senderUin = toUin(msg.senderUid, ctx);
2663
- return envelope(msg, ctx, "friend_nudge", {
2664
- user_id: senderUin,
2665
- is_self_send: senderUin === Number(ctx.selfUin),
2666
- is_self_receive: senderUin !== Number(ctx.selfUin),
2667
- display_action: "",
2668
- display_suffix: "",
2669
- display_action_img_url: ""
2670
- });
2671
- }
2672
- /**
2673
- * RawMessage → Milky notice 事件(无 grayTip / 不可翻译返回 null)。
2674
- * 未知子类型打 raw JSON 日志(JSON/BUDDY/ESSENCE/FILE 等——校准数据积累入口)。
2675
- */
2676
- function toMilkyNoticeEvent(msg, ctx) {
2677
- for (const el of msg.elements) {
2678
- const g = el.grayTipElement;
2679
- if (g == null) continue;
2680
- const event = translateGrayTip(msg, g, ctx);
2681
- if (event !== null) return event;
2682
- }
2683
- const untranslated = firstUntranslatedGrayTip(msg);
2684
- if (untranslated !== void 0) ctx.logger?.warn({
2685
- subType: untranslated.subElementType,
2686
- raw: JSON.stringify(untranslated)?.slice(0, 2e3)
2687
- }, "milky: 未翻译的 grayTip 子类型(raw 校准数据)");
2688
- return null;
2689
- }
2690
- // src/milky/inbound/message.ts
2691
- /** Milky 消息域处理器(Msg/onRecvMsg 分流与翻译派发)。 */
2692
- var MilkyInboundMessage = class {
2693
- deps;
2694
- constructor(deps) {
2695
- this.deps = deps;
2696
- }
2697
- /** 单条消息:seq 登记 → grayTip→notice / 群文件上传 / message_receive(自消息不上报)。 */
2698
- async handle(msg) {
2699
- this.deps.seqIndex.record(msg);
2700
- this.recordForward(msg);
2701
- if (hasGrayTip(msg)) {
2702
- await this.broadcastNotice(msg);
2703
- return;
2704
- }
2705
- const upload = toGroupFileUploadEvent(msg, this.deps.api.self.uin);
2706
- if (upload !== null) {
2707
- this.deps.broadcast(upload);
2708
- return;
2709
- }
2710
- if (String(msg.senderUin) === this.deps.api.self.uin) return;
2711
- this.deps.broadcast(await this.buildMessageReceiveEvent(msg));
2712
- }
2713
- /** grayTip → notice 事件广播(REVOKE 走 message_recall,其余走 notice 翻译)。 */
2714
- async broadcastNotice(msg) {
2715
- const uidToUin = await this.deps.enrich.resolveUidToUin(collectGrayTipUids(msg));
2716
- const event = findRevokeElement(msg) !== void 0 ? toMessageRecallEvent(msg, {
2717
- selfUin: this.deps.api.self.uin,
2718
- ...uidToUin !== void 0 ? { uidToUin } : {}
2719
- }) : toMilkyNoticeEvent(msg, this.noticeCtx(uidToUin));
2720
- if (event !== null) this.deps.broadcast(event);
2721
- }
2722
- /** notice 翻译上下文(uidToUin 缺省空 Map;logger 透传校准日志)。 */
2723
- noticeCtx(uidToUin) {
2724
- return {
2725
- selfUin: this.deps.api.self.uin,
2726
- ...uidToUin !== void 0 ? { uidToUin } : { uidToUin: /* @__PURE__ */ new Map() },
2727
- ...this.deps.logger !== void 0 ? { logger: this.deps.logger } : {}
2728
- };
2729
- }
2730
- /** message_receive 组装:at uid→uin + reply 回填 + 群实体回填 + 转发段(全部 fail-soft)。 */
2731
- async buildMessageReceiveEvent(msg) {
2732
- const elements = toCanonicalElements(msg);
2733
- const ctx = { selfUin: this.deps.api.self.uin };
2734
- await this.deps.enrich.fillMentionUids(elements, ctx);
2735
- const replyIds = elements.filter((el) => el.type === "reply").map((el) => el.messageId);
2736
- const meta = this.deps.seqIndex.collectReplyMeta(replyIds);
2737
- if (meta.size > 0) ctx.replyMeta = meta;
2738
- await this.deps.enrich.fillGroupEntities(msg, ctx);
2739
- const forward = this.findForward(msg);
2740
- if (forward !== void 0) ctx.forwardSegments = [incomingForwardSegment(forward.resId, forward.fileName)];
2741
- return toMessageReceiveEvent(msg, ctx);
2742
- }
2743
- /** 转发 resId → 定位登记(get_forwarded_messages 反查用)。 */
2744
- recordForward(msg) {
2745
- const forward = this.findForward(msg);
2746
- if (forward !== void 0 && forward.resId !== "") this.deps.seqIndex.recordForward(forward.resId, {
2747
- chatType: msg.chatType,
2748
- peerUid: msg.peerUid,
2749
- msgId: msg.msgId
2750
- });
2751
- }
2752
- findForward(msg) {
2753
- return msg.elements.find((el) => el.multiForwardMsgElement != null)?.multiForwardMsgElement;
2754
- }
2755
- };
2756
- // src/milky/helper/event/peer-pin.ts
2757
- /**
2758
- * peer_pin_change 翻译(Milky ,RecentContact/onRecentContactListChangedVer2)
2759
- *
2760
- * 回调随消息活动高频快照(含 topFlag 的全量条目 + chatType=7 影子条目),
2761
- * 不能见条目就广播——按「同会话 topFlag 前后值翻转」检测(PinWatch)。
2762
- * 启动期以 getPinnedContacts 播种基线(重启后首个取消置顶也能观测到)。
2763
- *
2764
- * 证据:set_peer_pin 自触发翻转实验——changedList 条目
2765
- * {chatType, peerUin, topFlag(1/0), topFlagTime(秒级 unix 字符串)},与操作
2766
- * 一一对应(milky.md §0.8.6)。
2767
- */
2768
- /** uin 形判别(peer_id 必须是数字串)。 */
2769
- const NUMERIC_RE$1 = /^\d+$/;
2770
- /** 置顶翻转检测(每适配器实例一份,键 = chatType:peerUin——群号与 uin 数值空间可重叠)。 */
2771
- var PinWatch = class {
2772
- states = /* @__PURE__ */ new Map();
2773
- /** 启动基线:置顶会话播种(只记状态,不产生事件)。 */
2774
- seed(pins) {
2775
- for (const pin of pins) {
2776
- if (pin.peerUin === void 0 || pin.peerUin === "") continue;
2777
- const chatType = pin.scene === "group" ? ChatType.GROUP : ChatType.C2C;
2778
- this.states.set(`${chatType}:${pin.peerUin}`, 1);
2779
- }
2780
- }
2781
- /**
2782
- * 观测一个变更条目:topFlag 相对上次观测翻转 → true(应广播);
2783
- * 首见(基线未建立)或未变 → false。
2784
- */
2785
- observe(chatType, peerUin, topFlag) {
2786
- const key = `${chatType}:${peerUin}`;
2787
- const prev = this.states.get(key);
2788
- this.states.set(key, topFlag);
2789
- return prev !== void 0 && prev !== topFlag;
2790
- }
2791
- };
2792
- /** 场景映射(changedList 条目 chatType → Milky message_scene;影子/其他类型丢弃)。 */
2793
- function pinScene(chatType) {
2794
- if (chatType === ChatType.GROUP) return "group";
2795
- if (chatType === ChatType.C2C) return "friend";
2796
- return null;
2797
- }
2798
- /** 变更条目 → 事件载荷(null = 条目不含置顶字段/场景不支持,跳过不广播)。 */
2799
- function toPeerPinChangeData(entry) {
2800
- const scene = pinScene(entry.chatType);
2801
- if (scene === null || entry.topFlag === void 0) return null;
2802
- const peerUin = typeof entry.peerUin === "string" && entry.peerUin !== "" ? entry.peerUin : scene === "group" ? entry.peerUid : "";
2803
- if (peerUin === "" || !NUMERIC_RE$1.test(peerUin)) return null;
2804
- return {
2805
- data: {
2806
- message_scene: scene,
2807
- peer_id: Number(peerUin),
2808
- is_pinned: entry.topFlag === 1
2809
- },
2810
- topFlagTime: typeof entry.topFlagTime === "string" ? entry.topFlagTime : void 0,
2811
- peerUin
2812
- };
2813
- }
2814
- // src/milky/inbound/pin.ts
2815
- /** Milky 置顶域处理器(翻转检测 + 播种基线 + peer_pin_change 广播)。 */
2816
- var MilkyInboundPin = class {
2817
- deps;
2818
- /** peer_pin 翻转检测(启动期 getPinnedContacts 播种)。 */
2819
- pinWatch = new PinWatch();
2820
- constructor(deps) {
2821
- this.deps = deps;
2822
- }
2823
- /** 会话列表变更 → 翻转检测逐条处理(首见/未变/不支持场景静默跳过)。 */
2824
- handleChanges(lists) {
2825
- const arr = Array.isArray(lists) ? lists : [lists];
2826
- for (const list of arr) for (const entry of changedListOf(list)) this.handleEntry(entry);
2827
- }
2828
- /** 启动基线:置顶会话播种(失败补 debug 日志,不再静默)。 */
2829
- seed() {
2830
- this.deps.api.recentContactApi.getPinnedContacts().then((pins) => {
2831
- this.pinWatch.seed(pins);
2832
- }).catch((err) => {
2833
- this.deps.logger?.debug({ err: String(err) }, "milky: 置顶基线播种失败(跳过)");
2834
- });
2835
- }
2836
- /** 单个变更条目:翻译 + 翻转检测 + 广播。 */
2837
- handleEntry(entry) {
2838
- const payload = pinPayloadOf(entry);
2839
- if (payload === null) return;
2840
- if (!this.pinWatch.observe(payload.chatType, payload.peerUin, payload.topFlag)) return;
2841
- this.deps.broadcast({
2842
- time: secondsOf(payload.topFlagTime),
2843
- self_id: Number(this.deps.api.self.uin),
2844
- event_type: "peer_pin_change",
2845
- data: payload.data
2846
- });
2847
- }
2848
- };
2849
- /** 变更列表 → changedList 条目数组(形状不符 → 空)。 */
2850
- function changedListOf(list) {
2851
- if (list === null || typeof list !== "object") return [];
2852
- const changed = list.changedList;
2853
- return Array.isArray(changed) ? changed : [];
2854
- }
2855
- /** 变更条目 → 翻转检测输入(null = 条目不支持/缺置顶字段)。 */
2856
- function pinPayloadOf(entry) {
2857
- if (entry === null || typeof entry !== "object") return null;
2858
- return pinPayloadFrom(entry);
2859
- }
2860
- function pinPayloadFrom(contact) {
2861
- const topFlag = contact.topFlag;
2862
- const payload = toPeerPinChangeData(contact);
2863
- if (topFlag === void 0 || payload === null) return null;
2864
- return {
2865
- chatType: contact.chatType,
2866
- peerUin: payload.peerUin,
2867
- topFlag,
2868
- topFlagTime: payload.topFlagTime,
2869
- data: payload.data
2870
- };
2871
- }
2872
- /** 秒级时间戳归一(空/非法 → 当前时间;topFlagTime/msgTime 均为秒级字符串)。 */
2873
- function secondsOf(raw) {
2874
- return numericUin(raw ?? null) ?? Math.floor(Date.now() / 1e3);
2875
- }
2876
- // src/milky/inbound/request.ts
2877
- /** Milky 请求域处理器(群通知 / 好友申请的 uid 回填与广播)。 */
2878
- var MilkyInboundRequest = class {
2879
- deps;
2880
- /** 已广播申请的 `${friendUid}:${reqTime}`(实例级,跨 reloadTransports 保留)。 */
2881
- dedup = new BuddyReqDedup();
2882
- /** 历史积压基准(订阅时刷新:重连后以此刻为界)。 */
2883
- baselineSec = startupBaselineSec();
2884
- constructor(deps) {
2885
- this.deps = deps;
2886
- }
2887
- /** 刷新启动基准(pipeline subscribe 时调用)。 */
2888
- markStartup() {
2889
- this.baselineSec = startupBaselineSec();
2890
- }
2891
- /** 群通知通道:入群请求 / 成员邀请 / 邀请自身(uid→uin 批量后翻译)。 */
2892
- async groupNotifies(doubt, notifies) {
2893
- const ctx = await this.requestCtx(collectNotifyUids(notifies));
2894
- for (const notify of notifies) {
2895
- const event = toGroupRequestEvent(notify, doubt, ctx);
2896
- if (event !== null) this.deps.broadcast(event);
2897
- }
2898
- }
2899
- /** 好友请求通道:Buddy/onBuddyReqChange(防御收窄,未知形状 raw 日志)。 */
2900
- buddyReqs(arg) {
2901
- this.broadcastBuddyReqs(arg).catch((err) => logEventFailure(this.deps.logger, "milky: friend request 翻译失败(整批丢弃)", err));
2902
- }
2903
- async broadcastBuddyReqs(arg) {
2904
- if (batchUnreadNums(arg) === 0) {
2905
- this.deps.logger?.debug({}, "milky: onBuddyReqChange unreadNums=0(整批跳过)");
2906
- return;
2907
- }
2908
- const reqs = narrowBuddyReqs(arg);
2909
- if (reqs === null) {
2910
- this.deps.logger?.warn({ raw: sliceRaw(JSON.stringify(arg)) }, "milky: onBuddyReqChange 未知参数形状");
2911
- return;
2912
- }
2913
- const fresh = filterBuddyReqs(reqs, this.baselineSec).filter((req) => this.dedup.claim(req));
2914
- if (fresh.length < reqs.length) this.deps.logger?.debug({
2915
- total: reqs.length,
2916
- kept: fresh.length
2917
- }, "milky: 好友申请过滤(历史积压 / 已读 / 已处理 / 重复)");
2918
- if (fresh.length === 0) return;
2919
- const ctx = await this.requestCtx(fresh.map((req) => req.friendUid));
2920
- for (const req of fresh) this.deps.broadcast(toFriendRequestEvent(req, ctx));
2921
- }
2922
- /** request 翻译上下文(uid→uin 批量转换 + 资料兜底;失败退空 Map)。 */
2923
- async requestCtx(uids) {
2924
- const uidToUin = await this.deps.enrich.resolveUidToUin(uids, { profileFallback: true });
2925
- return {
2926
- selfUin: this.deps.api.self.uin,
2927
- ...uidToUin !== void 0 ? { uidToUin } : { uidToUin: /* @__PURE__ */ new Map() }
2928
- };
2929
- }
2930
- };
2931
- // src/milky/helper/event/sysmsg.ts
2932
- /**
2933
- * Milky sysmsg 识别表(识别机制共享自 shared/sysmsg.ts)
2934
- *
2935
- * 键 = 原生分发键 "msgType:subType",规则产出事件 data 体(信封 time/self_id/
2936
- * event_type 由适配器统一包装)。路径依据 = 三轮录制 wire bytes 全量解码
2937
- * (milky.md §0.8.6 识别表;临时解码脚本 .napuketto/decode-sysmsg*.mjs 不入库)。
2938
- *
2939
- * - 732:16 群消息表情回应:f1.f1=群号;f3.f2.f44.f1.f1={f1 变动值, f2.f1=msgSeq,
2940
- * f3={f1 faceId 字符串, f5: 1=添加/2=撤销, f3:1 仅添加时存在}}。
2941
- * operator 不在 push(f4=bot 自身 uid 占位)——user_id 省略。
2942
- * - 732:1 群精华设置:f1.f1=群号, f1.f8.f8.f1=msgSeq(路径提取共享自
2943
- * shared/essence.ts extractEssenceSetSysMsg);取消精华无独立 sysmsg
2944
- * (remove 走 onGroupEssenceListChange 列表 diff,shared/essence.ts)。
2945
- * - 528:349/381/382 多端设备同步族:不广播。
2946
- */
2947
- /** 数字串判别(faceId 实证为数字字符串)。 */
2948
- const NUMERIC_RE = /^\d+$/;
2949
- /** 732:16 → group_message_reaction。 */
2950
- const REACTION_RULE = {
2951
- kind: "group_message_reaction",
2952
- extract: (tree) => reactionData(tree)
2953
- };
2954
- /** 路径提取:f1.f1=群号 + f3.f2.f44.f1.f1=回应明细(任一缺失 → null)。 */
2955
- function reactionData(tree) {
2956
- const groupId = varintAt(tree, [1, 1]);
2957
- const detail = nodeAt(tree, [
2958
- 3,
2959
- 2,
2960
- 44,
2961
- 1,
2962
- 1
2963
- ]);
2964
- if (groupId === null || detail === null) return null;
2965
- return reactionDetail(groupId, detail);
2966
- }
2967
- /** 明细提取:f2.f1=msgSeq + f3=face 块(任一缺失 → null)。 */
2968
- function reactionDetail(groupId, detail) {
2969
- const msgSeq = varintAt(detail, [2, 1]);
2970
- const face = nodeAt(detail, [3]);
2971
- if (msgSeq === null || face === null) return null;
2972
- return reactionFace(groupId, msgSeq, face);
2973
- }
2974
- /** face 块提取:faceId 实证为数字字符串("76"/"124"…);f5 双判据(f3 仅添加时存在)。 */
2975
- function reactionFace(groupId, msgSeq, face) {
2976
- const isAdd = reactionIsAdd(face);
2977
- const faceId = reactionFaceId(face);
2978
- if (isAdd === null || faceId === null) return null;
2979
- return {
2980
- group_id: groupId,
2981
- message_seq: msgSeq,
2982
- face_id: faceId,
2983
- reaction_type: "face",
2984
- is_add: isAdd
2985
- };
2986
- }
2987
- /** faceId 字段(数字字符串 → number;缺失/非数字 → null)。 */
2988
- function reactionFaceId(face) {
2989
- const faceIdText = textOf(face, 1);
2990
- return faceIdText !== null && NUMERIC_RE.test(faceIdText) ? Number(faceIdText) : null;
2991
- }
2992
- /** is_add 判定:f5=1 添加 / 2 撤销(f3=1 仅添加时存在,双判据);非法 → null。 */
2993
- function reactionIsAdd(face) {
2994
- const op = varintOf(face, 5);
2995
- if (op === 1) return true;
2996
- return op === 2 ? false : null;
2997
- }
2998
- /** (msgType, subType) → 规则表(键 = 原生分发键)。 */
2999
- const KIND_TABLE = /* @__PURE__ */ new Map([["732:16", REACTION_RULE], ["732:1", {
3000
- kind: "group_essence_message_change",
3001
- extract: (tree) => {
3002
- const hit = extractEssenceSetSysMsg(tree);
3003
- if (hit === null) return null;
3004
- return {
3005
- group_id: hit.groupCode,
3006
- message_seq: hit.messageSeq,
3007
- is_set: true
3008
- };
3009
- }
3010
- }]]);
3011
- /** 已观测但未命名的键(多端设备同步族等,不广播只走校准日志)。 */
3012
- const OBSERVED_UNNAMED = /* @__PURE__ */ new Set([
3013
- "528:382",
3014
- "528:349",
3015
- "528:381"
3016
- ]);
3017
- /** (msgType, subType) → 识别结果(绑定 Milky 表;table 参数供单测注入)。 */
3018
- function recognizeMilkySysMsg(msgType, subType, table = KIND_TABLE) {
3019
- return recognizeSysMsg(msgType, subType, table, OBSERVED_UNNAMED);
3020
- }
3021
- // src/milky/inbound/sysmsg.ts
3022
- /**
3023
- * Milky inbound sysmsg 域:Msg/onRecvSysMsg 总闸——参数收窄(未知形状 raw warn)
3024
- * → 单条字节块走 shared/sysmsg.ts 的 processSysMsgBlob 通用管线(解码 →
3025
- * 信封 → 识别 → 分流)。表命中提取 data 体 → 精华快路径 claim 去重 → 信封包装
3026
- * 广播;未识别 / 提取失败落校准路径,不广播半成品。
3027
- */
3028
- /** Milky sysmsg 域处理器(解码识别分流 + 精华快路径去重)。 */
3029
- var MilkyInboundSysMsg = class {
3030
- deps;
3031
- constructor(deps) {
3032
- this.deps = deps;
3033
- }
3034
- /** onRecvSysMsg 总闸:参数收窄(未知形状 raw warn)→ 逐块走通用管线。 */
3035
- handleRawArg(arg) {
3036
- const blobs = narrowSysMsgBlobs(arg);
3037
- if (blobs === null) {
3038
- this.deps.logger?.warn({ raw: sliceRaw(JSON.stringify(arg)) }, "milky: onRecvSysMsg 未知参数形状");
3039
- return;
3040
- }
3041
- for (const blob of blobs) processSysMsgBlob(blob, {
3042
- scope: "milky",
3043
- logger: this.deps.logger,
3044
- decodeFailLevel: "debug",
3045
- recognize: (msgType, subType) => recognizeMilkySysMsg(msgType, subType),
3046
- onNotice: (tree, env, rec) => this.handleHit(tree, env, rec)
3047
- });
3048
- }
3049
- /** 表命中分流:提取 data 体 → 精华快路径 claim → 信封包装广播;失败落校准。 */
3050
- async handleHit(tree, env, rec) {
3051
- if (rec.kind !== "notice") return false;
3052
- const data = rec.rule.extract(tree, env, () => 0, {
3053
- selfUin: Number(this.deps.api.self.uin),
3054
- time: env.time ?? Math.floor(Date.now() / 1e3)
3055
- });
3056
- if (data === null) return false;
3057
- if (!this.deps.essence.claimFastPath(rec.rule.kind, data)) return true;
3058
- this.deps.broadcast({
3059
- time: env.time ?? Math.floor(Date.now() / 1e3),
3060
- self_id: Number(this.deps.api.self.uin),
3061
- event_type: rec.rule.kind,
3062
- data
3063
- });
3064
- return true;
3065
- }
3066
- };
3067
- // src/milky/transport.ts
3068
- /** /event 路径(规范固定)。 */
3069
- const EVENT_PATH = "/event";
3070
- /** /api/ 前缀 + 动作名(小写字母开头,小写/数字/下划线)。 */
3071
- const API_PATH_RE = /^\/api\/([a-z][a-z0-9_]*)$/;
3072
- /** Bearer 前缀。 */
3073
- const BEARER_PREFIX = "Bearer ";
3074
- /**
3075
- * Milky 事件枢纽:SSE 客户端 + WS 客户端集合,send 即广播。
3076
- * 传输适配器面(open/close/send,EventBroadcaster 多态派发)——生命周期随
3077
- * HttpServer。连接注册经 attachTo 挂到 HttpServer 注入点(本类内部闭环);
3078
- * WS 入帧忽略(规范:/event 为纯事件推送通道)。
3079
- */
3080
- var MilkyEventHub = class {
3081
- sseClients = /* @__PURE__ */ new Set();
3082
- sockets = /* @__PURE__ */ new Set();
3083
- /** 把 /event 的 SSE(onRawRequest)与 WS 升级(onUpgrade)挂到 HTTP server。 */
3084
- attachTo(server, config) {
3085
- server.onRawRequest = (ctx) => {
3086
- if (ctx.path !== EVENT_PATH || ctx.method !== "GET") return;
3087
- if (!config.eventModes.includes("sse")) return new Response("event mode sse disabled", { status: 404 });
3088
- return createSseResponse((client) => {
3089
- this.sseClients.add(client);
3090
- return () => {
3091
- this.sseClients.delete(client);
3092
- };
3093
- });
3094
- };
3095
- server.onUpgrade = (req, accept, reject) => {
3096
- if (pathnameOf(req.url) !== EVENT_PATH) return;
3097
- if (!config.eventModes.includes("ws")) {
3098
- reject(404, "event mode ws disabled");
3099
- return;
3100
- }
3101
- if (config.token !== "" && !tokenMatches(req, config.token)) {
3102
- reject(401, "unauthorized");
3103
- return;
3104
- }
3105
- accept((socket) => {
3106
- this.sockets.add(socket);
3107
- const remove = () => {
3108
- this.sockets.delete(socket);
3109
- };
3110
- socket.on("close", remove);
3111
- socket.on("error", remove);
3112
- });
3113
- };
3114
- }
3115
- /** 广播事件(EventBroadcaster emit 入口)。 */
3116
- send(event) {
3117
- const json = JSON.stringify(event);
3118
- for (const client of this.sseClients) client.send(json, "milky_event");
3119
- for (const socket of this.sockets) if (isWsOpen(socket)) socket.send(json);
3120
- }
3121
- open() {}
3122
- async close() {
3123
- for (const client of this.sseClients) client.close();
3124
- this.sseClients.clear();
3125
- for (const socket of this.sockets) socket.close(1001, "server shutdown");
3126
- this.sockets.clear();
3127
- }
3128
- onRequest;
3129
- };
3130
- /** 按配置装配 Milky 传输。 */
3131
- function assembleMilkyTransports(opts) {
3132
- const { config, broadcaster, registry, logger } = opts;
3133
- const hub = new MilkyEventHub();
3134
- const token = config.token;
3135
- const authorize = token !== "" ? makeMilkyAuthorize(token, logger) : void 0;
3136
- const server = new HttpServer({
3137
- host: config.host,
3138
- port: config.port,
3139
- ...authorize !== void 0 ? { authorize } : {}
3140
- });
3141
- hub.attachTo(server, config);
3142
- server.onPathRequest = (ctx, req, respond) => {
3143
- handleMilkyHttpRequest(ctx, req, respond, registry, logger);
3144
- };
3145
- const adapters = [server, hub];
3146
- for (const url of config.webhooks) {
3147
- const client = new HttpClient({
3148
- url,
3149
- ...token !== "" ? { headers: { authorization: `${BEARER_PREFIX}${token}` } } : {},
3150
- timeoutMs: 5e3,
3151
- onError: (err) => {
3152
- logger?.warn({
3153
- url,
3154
- err: String(err)
3155
- }, "milky: webhook 推送失败");
3156
- }
3157
- });
3158
- adapters.push(client);
3159
- }
3160
- for (const adapter of adapters) broadcaster.register(adapter);
3161
- return {
3162
- adapters,
3163
- close: async () => {
3164
- await server.close();
3165
- await hub.close();
3166
- for (const adapter of adapters) broadcaster.unregister(adapter);
3167
- }
3168
- };
3169
- }
3170
- /** HTTP /api 分发(规范信封 + 404/415 语义)。 */
3171
- function handleMilkyHttpRequest(ctx, req, respond, registry, logger) {
3172
- if (ctx.method !== "POST") {
3173
- respond(void 0, 404);
3174
- return;
3175
- }
3176
- const match = API_PATH_RE.exec(ctx.path);
3177
- if (match === null) {
3178
- respond(void 0, 404);
3179
- return;
3180
- }
3181
- const contentType = ctx.headers?.["content-type"];
3182
- if (contentType !== void 0 && !contentType.toLowerCase().includes("application/json")) {
3183
- respond(void 0, 415);
3184
- return;
3185
- }
3186
- const action = registry.get(match[1] ?? "");
3187
- if (action === void 0) {
3188
- respond(void 0, 404);
3189
- return;
3190
- }
3191
- action.handle(req).then((result) => {
3192
- if (result.status === "ok") respond({
3193
- status: "ok",
3194
- retcode: 0,
3195
- data: result.data ?? {}
3196
- });
3197
- else respond({
3198
- status: "failed",
3199
- retcode: result.retcode,
3200
- data: null,
3201
- message: result.message
3202
- });
3203
- }).catch((err) => {
3204
- logger?.warn({
3205
- path: ctx.path,
3206
- error: err instanceof Error ? err.message : String(err)
3207
- }, "milky: 动作分发异常,已回 -500");
3208
- respond({
3209
- status: "failed",
3210
- retcode: -500,
3211
- data: null,
3212
- message: "internal error"
3213
- });
3214
- });
3215
- }
3216
- /** 鉴权钩子:Bearer 头或 access_token 查询参数(规范允许 SSE/WS 查询参数兜底)。 */
3217
- function makeMilkyAuthorize(token, logger) {
3218
- return (ctx) => tokenMatches(ctx, token, logger);
3219
- }
3220
- /** 请求凭据匹配(头优先,查询参数兜底;URL 解析失败 fail-closed 拒绝并 debug 留痕)。 */
3221
- function tokenMatches(ctx, token, logger) {
3222
- const auth = ctx.headers["authorization"] ?? ctx.headers["Authorization"];
3223
- if (auth?.startsWith(BEARER_PREFIX)) return auth.slice(7) === token;
3224
- try {
3225
- return new URL(ctx.url, "http://localhost").searchParams.get("access_token") === token;
3226
- } catch (err) {
3227
- logger?.debug({
3228
- url: ctx.url,
3229
- error: err instanceof Error ? err.message : String(err)
3230
- }, "milky: 鉴权 URL 解析失败,按未授权拒绝");
3231
- return false;
3232
- }
3233
- }
3234
- /** URL 路径部分(无 scheme 相对 url 容错)。 */
3235
- function pathnameOf(url) {
3236
- try {
3237
- return new URL(url, "http://localhost").pathname;
3238
- } catch {
3239
- return url.split("?")[0] ?? "";
3240
- }
3241
- }
3242
- // src/milky/adapter.ts
3243
- var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3244
- protocol = "milky";
3245
- calibLogger;
3246
- api;
3247
- /** seq 双向登记索引(发送回查 / reply 回填 / 转发定位共享)。 */
3248
- seqIndex = new MessageSeqIndex();
3249
- /** 动作注册表(公共只读:装配方/测试枚举)。 */
3250
- registry;
3251
- /** 收链路事件管道(订阅 / 过滤 / 去重 / 翻译派发,拆出)。 */
3252
- pipeline;
3253
- stopTransports = null;
3254
- constructor(opts) {
3255
- super({
3256
- config: opts.config,
3257
- broadcaster: opts.broadcaster,
3258
- hooks: {
3259
- onStart: (config) => this.startTransports(config),
3260
- onStop: () => this.stopAll(),
3261
- onReload: (config) => this.reloadTransports(config)
3262
- }
3263
- });
3264
- this.calibLogger = opts.logger;
3265
- this.api = new MilkyApi(opts, this.seqIndex);
3266
- const base = {
3267
- api: this.api,
3268
- seqIndex: this.seqIndex,
3269
- broadcast: (event) => this.broadcastEvent(event),
3270
- logger: opts.logger
3271
- };
3272
- const enrich = new MilkyEnrichment({ api: this.api });
3273
- const essence = new MilkyInboundEssence(base);
3274
- this.pipeline = new MilkyEventPipeline({
3275
- msgChannel: opts.msgChannel,
3276
- ...opts.groupChannel !== void 0 ? { groupChannel: opts.groupChannel } : {},
3277
- ...opts.buddyChannel !== void 0 ? { buddyChannel: opts.buddyChannel } : {},
3278
- ...opts.recentContactChannel !== void 0 ? { recentContactChannel: opts.recentContactChannel } : {},
3279
- ...opts.loginChannel !== void 0 ? { loginChannel: opts.loginChannel } : {},
3280
- essence,
3281
- message: new MilkyInboundMessage({
3282
- ...base,
3283
- enrich
3284
- }),
3285
- sysMsg: new MilkyInboundSysMsg({
3286
- ...base,
3287
- essence
3288
- }),
3289
- request: new MilkyInboundRequest({
3290
- ...base,
3291
- enrich
3292
- }),
3293
- fileNotice: new MilkyInboundFileNotice(base),
3294
- pin: new MilkyInboundPin(base),
3295
- logger: opts.logger
3296
- });
3297
- this.registry = createMilkyActionRegistry({ api: this.api });
3298
- }
3299
- /** 启动传输 + 订阅(enabled=false 空转:不订阅不起传输)。 */
3300
- async startTransports(config) {
3301
- if (!config.enabled) {
3302
- this.calibLogger?.info({}, "milky: 未启用(enabled=false),跳过装配");
3303
- return;
3304
- }
3305
- const broadcaster = this.getBroadcaster();
3306
- if (broadcaster !== void 0) {
3307
- const set = assembleMilkyTransports({
3308
- config,
3309
- broadcaster,
3310
- registry: this.registry,
3311
- ...this.calibLogger !== void 0 ? { logger: this.calibLogger } : {}
3312
- });
3313
- this.stopTransports = set.close;
3314
- await Promise.all(set.adapters.map((a) => a.open()));
3315
- }
3316
- this.pipeline.subscribe();
3317
- this.calibLogger?.info({
3318
- host: config.host,
3319
- port: config.port,
3320
- modes: config.eventModes
3321
- }, "milky: adapter started");
3322
- }
3323
- /** 热更新:停止重建(enabled 切换生效)。 */
3324
- async reloadTransports(config) {
3325
- await this.stopAll();
3326
- await this.startTransports(config);
3327
- }
3328
- /** 停止:退订 + 关传输。 */
3329
- async stopAll() {
3330
- this.pipeline.unsubscribeAll();
3331
- if (this.stopTransports !== null) {
3332
- await this.stopTransports();
3333
- this.stopTransports = null;
3334
- }
3335
- }
3336
- };
3337
- // src/milky/config.ts
3338
- /**
3339
- * Milky 协议配置(zod schema,归属本包)
3340
- *
3341
- * 单一 TOML 的 `[accounts.milky]` 账号段(docs/protocols/milky.md §4):
3342
- * 单端口 HTTP 模型(/api + /event 同端口),`enabled` 缺省 false = 不启用。
3343
- */
3344
- /** Milky 配置 schema。 */
3345
- const milkyConfigSchema = z.object({
3346
- /** 启用开关(缺省 false:账号段存在但 enabled 未开 = 装配为空转)。 */
3347
- enabled: z.boolean().default(false),
3348
- /** HTTP 监听地址。 */
3349
- host: z.string().min(1).default("127.0.0.1"),
3350
- /** HTTP 监听端口(/api 与 /event 同端口)。 */
3351
- port: z.number().int().min(0).max(65535).default(3001),
3352
- /** access_token(空 = 不校验,仅限内网)。 */
3353
- token: z.string().default(""),
3354
- /** /event 允许的连接形态(缺省两者都开)。 */
3355
- eventModes: z.array(z.enum(["sse", "ws"])).default(["sse", "ws"]),
3356
- /** 额外事件推送地址(WebHook,可多个;协议端在请求头发 Bearer token)。 */
3357
- webhooks: z.array(z.string().min(1)).default([]),
3358
- /** 发送媒体 http(s) URI 下载缓存目录(缺省不下载 = http(s) 发送媒体不可用)。 */
3359
- cacheDir: z.string().optional()
3360
- });
3361
- export { NapukettoMilkyAdapter, milkyConfigSchema };
3362
-
3363
- //# sourceMappingURL=index.mjs.map
1
+ export { a as MilkyApi, t as NapukettoMilkyAdapter, n as assembleMilkyTransports, i as createMilkyActionRegistry, r as milkyConfigSchema, o as milkyErrorCodeMap } from "../milky-CYAOJLv_.mjs";