@napuketto/adapter 0.15.2 → 0.15.3

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.
@@ -11,259 +11,158 @@ import { z } from "zod";
11
11
  import { randomUUID } from "node:crypto";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { HttpClient, HttpServer, createSseResponse, isWsOpen } from "@napuketto/network";
14
- // src/milky/api.ts
15
- var MilkyApi = class {
16
- msgApi;
17
- groupApi;
18
- friendApi;
19
- profileApi;
20
- profileLikeApi;
21
- ticketApi;
22
- webApi;
23
- groupNotifyApi;
24
- richMediaApi;
25
- /** kernel 闪传 API(文件投递:分享卡片,见 flash-transfer.ts 语义说明)。 */
26
- flashTransferApi;
27
- recentContactApi;
28
- self;
29
- groupCache;
30
- qqVersion;
31
- implVersion;
32
- mediaDir;
33
- /** 动作层可观测出口(缺省静默)。 */
34
- logger;
35
- /** message_seq ↔ msgId 双向映射(接收链路 record,动作侧反查)。 */
36
- seqIndex;
37
- constructor(opts, seqIndex) {
38
- this.msgApi = opts.msgApi;
39
- this.groupApi = opts.groupApi;
40
- this.friendApi = opts.friendApi;
41
- this.profileApi = opts.profileApi;
42
- this.profileLikeApi = opts.profileLikeApi;
43
- this.ticketApi = opts.ticketApi;
44
- this.webApi = opts.webApi;
45
- this.groupNotifyApi = opts.groupNotifyApi;
46
- this.richMediaApi = opts.richMediaApi;
47
- this.flashTransferApi = opts.flashTransferApi;
48
- this.recentContactApi = opts.recentContactApi;
49
- this.self = opts.self;
50
- this.groupCache = opts.groupCache;
51
- this.qqVersion = opts.qqVersion;
52
- this.implVersion = opts.implVersion;
53
- this.mediaDir = opts.mediaDir;
54
- this.logger = opts.logger;
55
- this.seqIndex = seqIndex;
56
- }
57
- /** uin → uid(私聊目标 / at 段发送转换 / 群管动作的 uid 入参)。 */
58
- uinToUid(uins) {
59
- return this.groupApi.uinToUid(uins);
60
- }
61
- /** uid → uin(事件路径 mention 转换)。 */
62
- uidToUin(uids) {
63
- return this.groupApi.uidToUin(uids);
64
- }
65
- /**
66
- * uin(数字)→ uid(群管动作入参转换);转换失败抛 INVALID_PARAM
67
- * (Milky 入参 user_id 都是 uin,kernel 群管 API 要 uid)。
68
- */
69
- async resolveUidFromUin(uin) {
70
- const uinStr = String(uin);
71
- try {
72
- const uid = (await this.uinToUid([uinStr])).get(uinStr);
73
- if (uid !== void 0 && uid !== "") return uid;
74
- } catch {}
75
- throw kernelError(`用户 ${uinStr} 不存在或 uin→uid 转换失败`, "INVALID_PARAM");
76
- }
77
- /**
78
- * message_scene + 数字 ID → NT Peer。
79
- * group = 群号直作 peerUid;friend/temp = uin → uid(失败退 uin 原样,交 QQ 端判断)。
80
- */
81
- async resolvePeer(scene, id) {
82
- if (scene === "group") return {
83
- chatType: ChatType.GROUP,
84
- peerUid: String(id)
85
- };
86
- const uin = String(id);
87
- let uid;
88
- try {
89
- uid = (await this.uinToUid([uin])).get(uin);
90
- } catch {}
91
- return {
92
- chatType: scene === "friend" ? ChatType.C2C : ChatType.C2C_TEMP,
93
- peerUid: uid ?? uin
14
+ // src/milky/action/error-map.ts
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
+ // src/milky/action/base-action.ts
26
+ /** zod 错误摘要(单行,issues 取前 3 条)。 */
27
+ function zodSummary(error) {
28
+ const parts = [];
29
+ for (const issue of error.issues.slice(0, 3)) parts.push(`${issue.path.map(String).join(".")}: ${issue.message}`);
30
+ return parts.join("; ");
31
+ }
32
+ var MilkyAction = class {
33
+ /** 校验并执行(HTTP /api 入口;WS /event 不承载动作)。 */
34
+ async handle(payload) {
35
+ const outcome = await runAction({
36
+ schema: this.schema,
37
+ handle: (parsed) => this._handle(parsed),
38
+ errorCodeMap: this.errorCodeMap,
39
+ invalidRetcode: -400,
40
+ invalidMessage: (error) => `参数解析失败: ${zodSummary(error)}`
41
+ }, payload);
42
+ return outcome.ok ? {
43
+ status: "ok",
44
+ retcode: 0,
45
+ data: outcome.data,
46
+ message: ""
47
+ } : {
48
+ status: "failed",
49
+ retcode: outcome.retcode,
50
+ data: null,
51
+ message: outcome.message
94
52
  };
95
53
  }
96
- /**
97
- * seq → msgId(索引优先,未登记扫描近段历史兜底)。
98
- * 两层都未命中返回 undefined(调用方抛 NOT_FOUND)。
99
- */
100
- async resolveMsgIdBySeq(peer, seq, chatType) {
101
- const indexed = this.seqIndex.resolveMsgId(chatType, peer.peerUid, seq);
102
- if (indexed !== void 0) return indexed;
103
- const hit = (await this.msgApi.fetchMessages(peer, { count: 60 }).catch(() => [])).find((m) => Number(m.msgSeq) === seq);
104
- if (hit === void 0) return;
105
- this.seqIndex.record(hit);
106
- return hit.msgId;
107
- }
108
- /** 发送结果回查:msgId → {message_seq, time}(sendMessage 只回 msgId)。 */
109
- async resolveSentOutput(peer, msgId) {
110
- const [sent] = await this.msgApi.fetchMsgsByMsgId(peer, [msgId]);
111
- if (sent === void 0) throw kernelError("发送结果回查失败(msgId 未命中)", "UNKNOWN");
112
- this.seqIndex.record(sent);
113
- return {
114
- message_seq: Number(sent.msgSeq),
115
- time: Math.floor(Number(sent.msgTime) / 1e3)
116
- };
54
+ };
55
+ /**
56
+ * 持 MilkyApi 的动作基类:api 注入 + 统一错误映射表(milkyErrorCodeMap)收拢,
57
+ * 动作子类只写 name / schema / _handle。
58
+ */
59
+ var MilkyApiAction = class extends MilkyAction {
60
+ errorCodeMap = milkyErrorCodeMap;
61
+ api;
62
+ constructor(api) {
63
+ super();
64
+ this.api = api;
117
65
  }
118
66
  };
119
- /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
120
- const NOTIFY_SEARCH_COUNT$1 = 100;
67
+ // src/milky/action/group-essence.ts
68
+ const groupIdField$4 = { group_id: z.number().int().min(10001) };
69
+ const optBool$3 = z.boolean().nullable().optional();
121
70
  /**
122
- * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
123
- * 屏序骨架走 core findFirstMatch)。
124
- * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
125
- * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
71
+ * get_group_essence_messages:获取精华消息列表。
72
+ * WebApi.getEssenceMsgList 全量拉取后按 page_index/page_size 客户端分页
73
+ * (kernel 无分页参数);message_time 无源取 operation_time 兜底。
126
74
  */
127
- async function findGroupNotify(api, seq) {
128
- const hit = await findFirstMatch([() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)], (item) => item.seq === seq);
129
- if (hit === void 0) throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
130
- return hit;
131
- }
132
- /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
133
- async function findBuddyReq(api, initiatorUid) {
134
- const hit = await findFirstMatch([() => api.friendApi.getBuddyReqList()], (req) => req.friendUid === initiatorUid);
135
- if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
136
- return hit;
137
- }
138
- // src/milky/helper/event/request.ts
139
- /** BuddyReq → friend_request 事件(comment 取 words 字段,形状待校准,缺省空串)。 */
140
- function toFriendRequestEvent(req, ctx) {
141
- const words = req["words"];
142
- return {
143
- time: Math.floor(Date.now() / MS_TO_SEC$2),
144
- self_id: Number(ctx.selfUin),
145
- event_type: "friend_request",
146
- data: {
147
- initiator_id: toUin(req.friendUid, ctx),
148
- initiator_uid: req.friendUid,
149
- comment: typeof words === "string" ? words : "",
150
- via: req.sourceName ?? ""
151
- }
152
- };
153
- }
154
- /** GroupNotify → Milky 群请求事件(非未处理状态 / 非请求类返回 null)。 */
155
- function toGroupRequestEvent(notify, doubt, ctx) {
156
- if (notify.status !== GroupNotifyMsgStatus.KUNHANDLE) return null;
157
- const groupId = Number(notify.group?.groupCode ?? 0);
158
- const seq = Number(notify.seq);
159
- const time = Math.floor(Date.now() / MS_TO_SEC$2);
160
- const selfId = Number(ctx.selfUin);
161
- switch (notify.type) {
162
- case GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS: return {
163
- time,
164
- self_id: selfId,
165
- event_type: "group_join_request",
166
- data: {
167
- group_id: groupId,
168
- notification_seq: seq,
169
- is_filtered: doubt,
170
- initiator_id: toUin(notify.user1?.uid, ctx),
171
- comment: notify.postscript ?? ""
172
- }
75
+ var GetGroupEssenceMessagesAction = class extends MilkyApiAction {
76
+ name = "get_group_essence_messages";
77
+ schema = z.object({
78
+ ...groupIdField$4,
79
+ page_index: z.number().int().min(0),
80
+ page_size: z.number().int().min(0)
81
+ });
82
+ async _handle(payload) {
83
+ const items = await this.api.webApi.getEssenceMsgList(String(payload.group_id));
84
+ const start = payload.page_index * payload.page_size;
85
+ const page = items.slice(start, start + payload.page_size);
86
+ return {
87
+ messages: page.map((item) => essenceToEntity(item, payload.group_id)),
88
+ is_end: start + page.length >= items.length
173
89
  };
174
- case GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS: return {
175
- time,
176
- self_id: selfId,
177
- event_type: "group_invited_join_request",
178
- data: {
179
- group_id: groupId,
180
- notification_seq: seq,
181
- initiator_id: toUin(notify.user1?.uid, ctx),
182
- target_user_id: toUin(notify.user2?.uid, ctx)
183
- }
90
+ }
91
+ };
92
+ /** set_group_essence_message:设置/取消精华(seq → msgId 反查)。 */
93
+ var SetGroupEssenceMessageAction = class extends MilkyApiAction {
94
+ name = "set_group_essence_message";
95
+ schema = z.object({
96
+ ...groupIdField$4,
97
+ message_seq: z.number().int().min(0),
98
+ is_set: optBool$3
99
+ });
100
+ async _handle(payload) {
101
+ const groupCode = String(payload.group_id);
102
+ const peer = {
103
+ chatType: ChatType.GROUP,
104
+ peerUid: groupCode
184
105
  };
185
- case GroupNotifyMsgType.INVITED_BY_MEMBER: return {
186
- time,
187
- self_id: selfId,
188
- event_type: "group_invitation",
189
- data: {
190
- group_id: groupId,
191
- invitation_seq: seq,
192
- initiator_id: toUin(notify.user1?.uid, ctx),
193
- source_group_id: null
194
- }
106
+ const msgId = await this.api.resolveMsgIdBySeq(peer, payload.message_seq, ChatType.GROUP);
107
+ if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
108
+ if (payload.is_set === false) await this.api.groupApi.removeGroupEssence(groupCode, msgId);
109
+ else await this.api.groupApi.addGroupEssence(groupCode, msgId);
110
+ return {};
111
+ }
112
+ };
113
+ /** send_group_message_reaction:消息表情表态(reaction_type face→"1" / emoji→"2")。 */
114
+ var SendGroupMessageReactionAction = class extends MilkyApiAction {
115
+ name = "send_group_message_reaction";
116
+ schema = z.object({
117
+ ...groupIdField$4,
118
+ message_seq: z.number().int().min(0),
119
+ reaction: z.string().min(1),
120
+ reaction_type: z.enum(["face", "emoji"]).nullable().optional(),
121
+ is_add: z.boolean().nullable().optional()
122
+ });
123
+ async _handle(payload) {
124
+ const peer = {
125
+ chatType: ChatType.GROUP,
126
+ peerUid: String(payload.group_id)
195
127
  };
196
- default: return null;
128
+ await this.api.msgApi.setMsgEmojiLike(peer, {
129
+ msgSeq: String(payload.message_seq),
130
+ emojiId: payload.reaction,
131
+ emojiType: payload.reaction_type === "emoji" ? "2" : "1",
132
+ like: payload.is_add !== false
133
+ });
134
+ return {};
197
135
  }
198
- }
199
- /**
200
- * 群通知涉及的 uid 集合(去重;get_group_notifications 与事件广播共用)。
201
- * kernel GroupEventChannel 的 onGroupNotifiesUpdated 回调参数已类型化
202
- * (GroupNotify[]),无需防御收窄。
203
- */
204
- function collectNotifyUids(notifies) {
205
- const uids = /* @__PURE__ */ new Set();
206
- for (const n of notifies) for (const uid of [n.user1?.uid, n.user2?.uid]) if (uid !== void 0 && uid !== "") uids.add(uid);
207
- return [...uids];
208
- }
209
- // src/milky/helper/message/entities.ts
210
- /** GroupDetailInfo / Group → GroupEntity(detail 缺失时全兜底)。 */
211
- function toGroupEntity(detail, groupCode) {
212
- return {
213
- group_id: Number(groupCode),
214
- group_name: detail?.groupName ?? "",
215
- member_count: detail?.memberNum ?? 0,
216
- max_member_count: detail?.maxMemberNum ?? 0,
217
- remark: detail?.remarkName ?? "",
218
- created_time: detail?.groupCreateTime ?? 0,
219
- description: "",
220
- question: "",
221
- announcement: ""
222
- };
223
- }
224
- /** 群列表项(GroupCache Group)→ GroupEntity。 */
225
- function groupListToEntity(group) {
226
- return {
227
- group_id: Number(group.groupCode),
228
- group_name: group.groupName,
229
- member_count: group.memberCount,
230
- max_member_count: group.maxMember,
231
- remark: "",
232
- created_time: 0,
233
- description: "",
234
- question: "",
235
- announcement: ""
236
- };
237
- }
238
- /** GroupMember → GroupMemberEntity(member 缺失时按 uin 兜底最小实体)。 */
239
- function toGroupMemberEntity(member, groupCode, uin) {
240
- const shutUpSeconds = member?.shutUpTime ?? 0;
241
- return {
242
- user_id: Number(member?.uin !== void 0 && member.uin !== "" ? member.uin : uin),
243
- nickname: member?.nick ?? "",
244
- sex: "unknown",
245
- group_id: Number(groupCode),
246
- card: member?.cardName ?? "",
247
- title: member?.memberSpecialTitle ?? "",
248
- level: 0,
249
- role: GroupApi.roleToString(member?.role ?? 2),
250
- join_time: Number(member?.joinTime) || 0,
251
- last_sent_time: Number(member?.lastSpeakTime) || 0,
252
- shut_up_end_time: shutUpSeconds > 0 ? Math.floor(Date.now() / 1e3) + shutUpSeconds : null
253
- };
254
- }
255
- /** Friend → FriendEntity(kernel 无 qid/分类挂载,按最小实体兜底)。 */
256
- function toFriendEntity(friend, uin, nick) {
257
- return {
258
- user_id: Number(friend?.uin !== void 0 && friend.uin !== "" ? friend.uin : uin),
259
- nickname: friend?.nickname ?? nick,
260
- sex: "unknown",
261
- qid: "",
262
- remark: friend?.remark ?? "",
263
- category: {
264
- category_id: 0,
265
- category_name: ""
136
+ };
137
+ /** ---------- 内部辅助 ---------- */
138
+ /** 精华项 → GroupEssenceMessage(msg_content 近似翻译:text / image)。 */
139
+ function essenceToEntity(item, groupId) {
140
+ const segments = [];
141
+ for (const c of item.msg_content) if (c.text !== void 0 && c.text !== "") segments.push({
142
+ type: "text",
143
+ data: { text: c.text }
144
+ });
145
+ else if (c.image_url !== void 0 && c.image_url !== "") segments.push({
146
+ type: "image",
147
+ data: {
148
+ resource_id: c.image_url,
149
+ temp_url: c.image_url,
150
+ width: 0,
151
+ height: 0,
152
+ summary: "",
153
+ sub_type: "normal"
266
154
  }
155
+ });
156
+ return {
157
+ group_id: groupId,
158
+ message_seq: item.msg_seq,
159
+ message_time: item.add_digest_time,
160
+ sender_id: Number(item.sender_uin) || 0,
161
+ sender_name: item.sender_nick,
162
+ operator_id: Number(item.add_digest_uin) || 0,
163
+ operator_name: item.add_digest_nick,
164
+ operation_time: item.add_digest_time,
165
+ segments
267
166
  };
268
167
  }
269
168
  // src/milky/helper/message/media-uri.ts
@@ -321,104 +220,221 @@ async function writeBase64(payload, mediaDir) {
321
220
  return raw;
322
221
  }
323
222
  }
324
- // src/milky/action/error-map.ts
325
- const milkyErrorCodeMap = {
326
- SEND_FAILED: -500,
327
- PERMISSION_DENIED: -405,
328
- NOT_FOUND: -404,
329
- TIMEOUT: -504,
330
- NOT_LOGIN: -403,
331
- INVALID_PARAM: -400,
332
- INVALID_STATE: -409,
333
- UNKNOWN: -500
334
- };
335
- // src/milky/action/base-action.ts
336
- /** zod 错误摘要(单行,issues 取前 3 条)。 */
337
- function zodSummary(error) {
338
- const parts = [];
339
- for (const issue of error.issues.slice(0, 3)) parts.push(`${issue.path.map(String).join(".")}: ${issue.message}`);
340
- return parts.join("; ");
341
- }
342
- var MilkyAction = class {
343
- /** 校验并执行(HTTP /api 入口;WS /event 不承载动作)。 */
344
- async handle(payload) {
345
- const outcome = await runAction({
346
- schema: this.schema,
347
- handle: (parsed) => this._handle(parsed),
348
- errorCodeMap: this.errorCodeMap,
349
- invalidRetcode: -400,
350
- invalidMessage: (error) => `参数解析失败: ${zodSummary(error)}`
351
- }, payload);
352
- return outcome.ok ? {
353
- status: "ok",
354
- retcode: 0,
355
- data: outcome.data,
356
- message: ""
357
- } : {
358
- status: "failed",
359
- retcode: outcome.retcode,
360
- data: null,
361
- message: outcome.message
223
+ // src/milky/action/group-file.ts
224
+ const groupIdField$3 = { group_id: z.number().int().min(10001) };
225
+ const fileIdField = { file_id: z.string().min(1) };
226
+ const optStr$2 = z.string().nullable().optional();
227
+ /** get_group_files:获取群文件列表(根目录或指定文件夹;过滤 parent 匹配项)。 */
228
+ var GetGroupFilesAction = class extends MilkyApiAction {
229
+ name = "get_group_files";
230
+ schema = z.object({
231
+ ...groupIdField$3,
232
+ parent_folder_id: optStr$2
233
+ });
234
+ async _handle(payload) {
235
+ const groupCode = String(payload.group_id);
236
+ const parent = payload.parent_folder_id ?? "";
237
+ const items = await this.api.richMediaApi.getGroupFileList(groupCode, parent);
238
+ const files = [];
239
+ const folders = [];
240
+ for (const item of items) if (item.fileInfo !== void 0) files.push(fileToEntity(item.fileInfo, payload.group_id));
241
+ else if (item.folderInfo !== void 0) folders.push(folderToEntity(item.folderInfo, payload.group_id));
242
+ return {
243
+ files,
244
+ folders
362
245
  };
363
246
  }
364
247
  };
248
+ /** move_group_file:移动文件(target_folder_id 空 = 移到根目录;parent 入参仅 schema 兼容)。 */
249
+ var MoveGroupFileAction = class extends MilkyApiAction {
250
+ name = "move_group_file";
251
+ schema = z.object({
252
+ ...groupIdField$3,
253
+ ...fileIdField,
254
+ parent_folder_id: optStr$2,
255
+ target_folder_id: optStr$2
256
+ });
257
+ async _handle(payload) {
258
+ await this.api.richMediaApi.moveGroupFile(String(payload.group_id), [payload.file_id], payload.target_folder_id ?? "");
259
+ return {};
260
+ }
261
+ };
262
+ /** rename_group_file:重命名文件。 */
263
+ var RenameGroupFileAction = class extends MilkyApiAction {
264
+ name = "rename_group_file";
265
+ schema = z.object({
266
+ ...groupIdField$3,
267
+ ...fileIdField,
268
+ parent_folder_id: optStr$2,
269
+ new_file_name: z.string().min(1)
270
+ });
271
+ async _handle(payload) {
272
+ await this.api.richMediaApi.renameGroupFile(String(payload.group_id), payload.file_id, payload.new_file_name);
273
+ return {};
274
+ }
275
+ };
276
+ /** delete_group_file:删除文件。 */
277
+ var DeleteGroupFileAction = class extends MilkyApiAction {
278
+ name = "delete_group_file";
279
+ schema = z.object({
280
+ ...groupIdField$3,
281
+ ...fileIdField
282
+ });
283
+ async _handle(payload) {
284
+ await this.api.richMediaApi.deleteGroupFile(String(payload.group_id), [payload.file_id]);
285
+ return {};
286
+ }
287
+ };
288
+ /**
289
+ * persist_group_file:转存文件(RichMediaApi.transGroupFile,转存语义待对齐)。
290
+ */
291
+ var PersistGroupFileAction = class extends MilkyApiAction {
292
+ name = "persist_group_file";
293
+ schema = z.object({
294
+ ...groupIdField$3,
295
+ ...fileIdField
296
+ });
297
+ async _handle(payload) {
298
+ await this.api.richMediaApi.transGroupFile(String(payload.group_id), payload.file_id);
299
+ return {};
300
+ }
301
+ };
302
+ /** create_group_folder:创建文件夹(返回 folder_id)。 */
303
+ var CreateGroupFolderAction = class extends MilkyApiAction {
304
+ name = "create_group_folder";
305
+ schema = z.object({
306
+ ...groupIdField$3,
307
+ folder_name: z.string().min(1)
308
+ });
309
+ async _handle(payload) {
310
+ return { folder_id: await this.api.richMediaApi.createGroupFolder(String(payload.group_id), payload.folder_name) };
311
+ }
312
+ };
313
+ /** delete_group_folder:删除文件夹。 */
314
+ var DeleteGroupFolderAction = class extends MilkyApiAction {
315
+ name = "delete_group_folder";
316
+ schema = z.object({
317
+ ...groupIdField$3,
318
+ folder_id: z.string().min(1)
319
+ });
320
+ async _handle(payload) {
321
+ await this.api.richMediaApi.deleteGroupFolder(String(payload.group_id), payload.folder_id);
322
+ return {};
323
+ }
324
+ };
325
+ /** GroupFileItemInfo → GroupFileEntity(fileSize 原生为字符串;无源字段兜底)。 */
326
+ function fileToEntity(info, groupId) {
327
+ return {
328
+ group_id: groupId,
329
+ file_id: info.fileId,
330
+ file_name: info.fileName,
331
+ parent_folder_id: info.parent ?? "",
332
+ file_size: Number(info.fileSize) || 0,
333
+ uploaded_time: Number(info.uploadTime) || 0,
334
+ expire_time: null,
335
+ uploader_id: Number(info.uploaderUin) || 0,
336
+ downloaded_times: 0
337
+ };
338
+ }
339
+ /** GroupFolderInfo → GroupFolderEntity(元数据无类型字段防御读取,缺省 0)。 */
340
+ function folderToEntity(info, groupId) {
341
+ const num = (key) => {
342
+ const v = info[key];
343
+ return typeof v === "number" ? v : Number(v) || 0;
344
+ };
345
+ return {
346
+ group_id: groupId,
347
+ folder_id: info.folderId,
348
+ parent_folder_id: info.folderUid ?? "",
349
+ folder_name: info.folderName,
350
+ created_time: num("createTime"),
351
+ last_modified_time: num("modifyTime"),
352
+ creator_id: 0,
353
+ file_count: num("totalFileCount")
354
+ };
355
+ }
365
356
  /**
366
- * 持 MilkyApi 的动作基类:api 注入 + 统一错误映射表(milkyErrorCodeMap)收拢,
367
- * 动作子类只写 name / schema / _handle。
357
+ * upload_group_file:上传并投递文件(**闪传通道**:分享链接卡片,见文件头语义说明)。
358
+ * file_id 返回闪传文件集 id(非群文件 fileId)。
368
359
  */
369
- var MilkyApiAction = class extends MilkyAction {
370
- errorCodeMap = milkyErrorCodeMap;
371
- api;
372
- constructor(api) {
373
- super();
374
- this.api = api;
360
+ var UploadGroupFileAction = class extends MilkyApiAction {
361
+ name = "upload_group_file";
362
+ schema = z.object({
363
+ ...groupIdField$3,
364
+ parent_folder_id: optStr$2,
365
+ file_uri: z.string().min(1),
366
+ file_name: z.string().min(1)
367
+ });
368
+ async _handle(payload) {
369
+ const path = await resolveUriToPath(payload.file_uri, this.api.mediaDir);
370
+ const peer = {
371
+ chatType: ChatType.GROUP,
372
+ peerUid: String(payload.group_id)
373
+ };
374
+ return { file_id: (await this.api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
375
375
  }
376
376
  };
377
- // src/milky/action/group.ts
378
- const groupIdField$1 = { group_id: z.number().int().min(10001) };
379
- const userIdField = { user_id: z.number().int().min(10001) };
380
- const optBool = z.boolean().nullable().optional();
381
- const optStr$1 = z.string().nullable().optional();
382
- /** get_group_info:获取群信息(GroupCache 详情缓存优先)。 */
383
- var GetGroupInfoAction = class extends MilkyApiAction {
384
- name = "get_group_info";
377
+ /** get_group_file_download_url:群文件下载链接(url 字段待实机确认,仅根目录)。 */
378
+ var GetGroupFileDownloadUrlAction = class extends MilkyApiAction {
379
+ name = "get_group_file_download_url";
385
380
  schema = z.object({
386
- ...groupIdField$1,
387
- no_cache: optBool
381
+ ...groupIdField$3,
382
+ ...fileIdField
388
383
  });
389
384
  async _handle(payload) {
390
- const groupCode = String(payload.group_id);
391
- return { group: toGroupEntity(this.api.groupCache !== void 0 ? await this.api.groupCache.getGroupDetail(groupCode) : await this.api.groupApi.getGroupInfo(groupCode), groupCode) };
385
+ return { download_url: await this.api.richMediaApi.getGroupFileDownloadUrl(String(payload.group_id), payload.file_id) };
392
386
  }
393
387
  };
394
- /** get_group_member_list:获取群成员列表(GroupCache 惰性回填)。 */
395
- var GetGroupMemberListAction = class extends MilkyApiAction {
396
- name = "get_group_member_list";
388
+ /** rename_group_folder:重命名群文件夹(renameGroupFile 同款形态,待校准)。 */
389
+ var RenameGroupFolderAction = class extends MilkyApiAction {
390
+ name = "rename_group_folder";
397
391
  schema = z.object({
398
- ...groupIdField$1,
399
- no_cache: optBool
392
+ ...groupIdField$3,
393
+ folder_id: z.string().min(1),
394
+ new_folder_name: z.string().min(1)
400
395
  });
401
396
  async _handle(payload) {
402
- return { members: (await membersOf(this.api, String(payload.group_id))).map((m) => toGroupMemberEntity(m, String(payload.group_id), m.uin)) };
397
+ await this.api.richMediaApi.renameGroupFolder(String(payload.group_id), payload.folder_id, payload.new_folder_name);
398
+ return {};
403
399
  }
404
400
  };
405
- /** get_group_member_info:获取群成员信息(user_id = uin → 成员单查)。 */
406
- var GetGroupMemberInfoAction = class extends MilkyApiAction {
407
- name = "get_group_member_info";
401
+ // src/milky/action/group-manage.ts
402
+ /**
403
+ * Milky 群管理域动作(2026-11-14 自 group.ts 拆分,结构重构会话 4/5)
404
+ *
405
+ * 写操作合:群名/名片/管理员/禁言/踢出/退群 + 群头像/专属头衔/公告发布与
406
+ * 删除/群戳一戳(P2 批次二)。成员类操作 user_id(uin) → uid 转换后进 kernel
407
+ * (resolveUidFromUin);公告 image_uri / 头像 image_uri 落盘后进 kernel。
408
+ */
409
+ const groupIdField$2 = { group_id: z.number().int().min(10001) };
410
+ const userIdField$1 = { user_id: z.number().int().min(10001) };
411
+ const optBool$2 = z.boolean().nullable().optional();
412
+ const optStr$1 = z.string().nullable().optional();
413
+ /** NTGroupMemberRole 数值(ADMIN=3 / MEMBER=2,setMemberRole 入参)。 */
414
+ const NTGroupMemberRoleAdmin = 3;
415
+ const NTGroupMemberRoleMember = 2;
416
+ /** send_group_nudge:发送群戳一戳(self.uid 缺失报 INVALID_PARAM)。 */
417
+ var SendGroupNudgeAction = class extends MilkyApiAction {
418
+ name = "send_group_nudge";
408
419
  schema = z.object({
409
- ...groupIdField$1,
410
- ...userIdField,
411
- no_cache: optBool
420
+ ...groupIdField$2,
421
+ ...userIdField$1
412
422
  });
413
423
  async _handle(payload) {
414
- return { member: toGroupMemberEntity(await memberOf(this.api, payload.group_id, payload.user_id), String(payload.group_id), String(payload.user_id)) };
424
+ const receiverUid = await this.api.resolveUidFromUin(payload.user_id);
425
+ const peer = await this.api.resolvePeer("group", payload.group_id);
426
+ await this.api.msgApi.sendNudge(peer, {
427
+ receiverUid,
428
+ callerUid: requireSelfUid$1(this.api)
429
+ });
430
+ return {};
415
431
  }
416
432
  };
417
433
  /** set_group_name:设置群名。 */
418
434
  var SetGroupNameAction = class extends MilkyApiAction {
419
435
  name = "set_group_name";
420
436
  schema = z.object({
421
- ...groupIdField$1,
437
+ ...groupIdField$2,
422
438
  new_group_name: z.string()
423
439
  });
424
440
  async _handle(payload) {
@@ -430,8 +446,8 @@ var SetGroupNameAction = class extends MilkyApiAction {
430
446
  var SetGroupMemberCardAction = class extends MilkyApiAction {
431
447
  name = "set_group_member_card";
432
448
  schema = z.object({
433
- ...groupIdField$1,
434
- ...userIdField,
449
+ ...groupIdField$2,
450
+ ...userIdField$1,
435
451
  card: z.string()
436
452
  });
437
453
  async _handle(payload) {
@@ -444,9 +460,9 @@ var SetGroupMemberCardAction = class extends MilkyApiAction {
444
460
  var SetGroupMemberAdminAction = class extends MilkyApiAction {
445
461
  name = "set_group_member_admin";
446
462
  schema = z.object({
447
- ...groupIdField$1,
448
- ...userIdField,
449
- is_set: optBool
463
+ ...groupIdField$2,
464
+ ...userIdField$1,
465
+ is_set: optBool$2
450
466
  });
451
467
  async _handle(payload) {
452
468
  const uid = await this.api.resolveUidFromUin(payload.user_id);
@@ -458,8 +474,8 @@ var SetGroupMemberAdminAction = class extends MilkyApiAction {
458
474
  var SetGroupMemberMuteAction = class extends MilkyApiAction {
459
475
  name = "set_group_member_mute";
460
476
  schema = z.object({
461
- ...groupIdField$1,
462
- ...userIdField,
477
+ ...groupIdField$2,
478
+ ...userIdField$1,
463
479
  duration: z.number().int().min(0).nullable().optional()
464
480
  });
465
481
  async _handle(payload) {
@@ -475,8 +491,8 @@ var SetGroupMemberMuteAction = class extends MilkyApiAction {
475
491
  var SetGroupWholeMuteAction = class extends MilkyApiAction {
476
492
  name = "set_group_whole_mute";
477
493
  schema = z.object({
478
- ...groupIdField$1,
479
- is_mute: optBool
494
+ ...groupIdField$2,
495
+ is_mute: optBool$2
480
496
  });
481
497
  async _handle(payload) {
482
498
  await this.api.groupApi.setGroupShutUp(String(payload.group_id), payload.is_mute !== false);
@@ -487,9 +503,9 @@ var SetGroupWholeMuteAction = class extends MilkyApiAction {
487
503
  var KickGroupMemberAction = class extends MilkyApiAction {
488
504
  name = "kick_group_member";
489
505
  schema = z.object({
490
- ...groupIdField$1,
491
- ...userIdField,
492
- reject_add_request: optBool
506
+ ...groupIdField$2,
507
+ ...userIdField$1,
508
+ reject_add_request: optBool$2
493
509
  });
494
510
  async _handle(payload) {
495
511
  const uid = await this.api.resolveUidFromUin(payload.user_id);
@@ -500,79 +516,273 @@ var KickGroupMemberAction = class extends MilkyApiAction {
500
516
  /** quit_group:退出群聊。 */
501
517
  var QuitGroupAction = class extends MilkyApiAction {
502
518
  name = "quit_group";
503
- schema = z.object({ ...groupIdField$1 });
519
+ schema = z.object({ ...groupIdField$2 });
504
520
  async _handle(payload) {
505
521
  await this.api.groupApi.quitGroup(String(payload.group_id));
506
522
  return {};
507
523
  }
508
524
  };
509
- /**
510
- * get_group_essence_messages:获取精华消息列表。
511
- * WebApi.getEssenceMsgList 全量拉取后按 page_index/page_size 客户端分页
512
- * (kernel 无分页参数);message_time 无源取 operation_time 兜底。
513
- */
514
- var GetGroupEssenceMessagesAction = class extends MilkyApiAction {
515
- name = "get_group_essence_messages";
525
+ /** set_group_avatar:设置群头像(image_uri → 本地路径)。 */
526
+ var SetGroupAvatarAction = class extends MilkyApiAction {
527
+ name = "set_group_avatar";
516
528
  schema = z.object({
517
- ...groupIdField$1,
518
- page_index: z.number().int().min(0),
519
- page_size: z.number().int().min(0)
529
+ ...groupIdField$2,
530
+ image_uri: z.string().min(1)
520
531
  });
521
532
  async _handle(payload) {
522
- const items = await this.api.webApi.getEssenceMsgList(String(payload.group_id));
523
- const start = payload.page_index * payload.page_size;
524
- const page = items.slice(start, start + payload.page_size);
525
- return {
526
- messages: page.map((item) => essenceToEntity(item, payload.group_id)),
527
- is_end: start + page.length >= items.length
528
- };
533
+ const imagePath = await resolveUriToPath(payload.image_uri, this.api.mediaDir);
534
+ await this.api.groupApi.setGroupAvatar(String(payload.group_id), imagePath);
535
+ return {};
529
536
  }
530
537
  };
531
- /** set_group_essence_message:设置/取消精华(seq → msgId 反查)。 */
532
- var SetGroupEssenceMessageAction = class extends MilkyApiAction {
533
- name = "set_group_essence_message";
538
+ /** set_group_member_special_title:设置专属头衔(uin → uid)。 */
539
+ var SetGroupMemberSpecialTitleAction = class extends MilkyApiAction {
540
+ name = "set_group_member_special_title";
534
541
  schema = z.object({
535
- ...groupIdField$1,
536
- message_seq: z.number().int().min(0),
537
- is_set: optBool
542
+ ...groupIdField$2,
543
+ ...userIdField$1,
544
+ special_title: z.string()
545
+ });
546
+ async _handle(payload) {
547
+ const uid = await this.api.resolveUidFromUin(payload.user_id);
548
+ await this.api.groupApi.setMemberSpecialTitle(String(payload.group_id), uid, payload.special_title);
549
+ return {};
550
+ }
551
+ };
552
+ /** send_group_announcement:发群公告(image_uri 落盘后经上传+发布两步)。 */
553
+ var SendGroupAnnouncementAction = class extends MilkyApiAction {
554
+ name = "send_group_announcement";
555
+ schema = z.object({
556
+ ...groupIdField$2,
557
+ content: z.string().min(1),
558
+ image_uri: optStr$1
538
559
  });
539
560
  async _handle(payload) {
540
561
  const groupCode = String(payload.group_id);
541
- const peer = {
562
+ let imagePath;
563
+ if (payload.image_uri !== void 0 && payload.image_uri !== null && payload.image_uri !== "") imagePath = await resolveUriToPath(payload.image_uri, this.api.mediaDir);
564
+ await this.api.groupApi.publishGroupAnnouncement(groupCode, payload.content, imagePath);
565
+ return {};
566
+ }
567
+ };
568
+ /** delete_group_announcement:删除群公告。 */
569
+ var DeleteGroupAnnouncementAction = class extends MilkyApiAction {
570
+ name = "delete_group_announcement";
571
+ schema = z.object({
572
+ ...groupIdField$2,
573
+ announcement_id: z.string().min(1)
574
+ });
575
+ async _handle(payload) {
576
+ await this.api.groupApi.deleteGroupAnnouncement(String(payload.group_id), payload.announcement_id);
577
+ return {};
578
+ }
579
+ };
580
+ /** ---------- 内部辅助 ---------- */
581
+ /** self.uid 必备(nudge 发送的 callerUid;缺配置报 INVALID_PARAM)。 */
582
+ function requireSelfUid$1(api) {
583
+ const uid = api.self.uid;
584
+ if (uid === void 0 || uid === "") throw kernelError("登录身份缺 uid(无法发起戳一戳)", "INVALID_PARAM");
585
+ return uid;
586
+ }
587
+ // src/milky/api.ts
588
+ var MilkyApi = class {
589
+ msgApi;
590
+ groupApi;
591
+ friendApi;
592
+ profileApi;
593
+ profileLikeApi;
594
+ ticketApi;
595
+ webApi;
596
+ groupNotifyApi;
597
+ richMediaApi;
598
+ /** kernel 闪传 API(文件投递:分享卡片,见 flash-transfer.ts 语义说明)。 */
599
+ flashTransferApi;
600
+ recentContactApi;
601
+ self;
602
+ groupCache;
603
+ qqVersion;
604
+ implVersion;
605
+ mediaDir;
606
+ /** 动作层可观测出口(缺省静默)。 */
607
+ logger;
608
+ /** message_seq ↔ msgId 双向映射(接收链路 record,动作侧反查)。 */
609
+ seqIndex;
610
+ constructor(opts, seqIndex) {
611
+ this.msgApi = opts.msgApi;
612
+ this.groupApi = opts.groupApi;
613
+ this.friendApi = opts.friendApi;
614
+ this.profileApi = opts.profileApi;
615
+ this.profileLikeApi = opts.profileLikeApi;
616
+ this.ticketApi = opts.ticketApi;
617
+ this.webApi = opts.webApi;
618
+ this.groupNotifyApi = opts.groupNotifyApi;
619
+ this.richMediaApi = opts.richMediaApi;
620
+ this.flashTransferApi = opts.flashTransferApi;
621
+ this.recentContactApi = opts.recentContactApi;
622
+ this.self = opts.self;
623
+ this.groupCache = opts.groupCache;
624
+ this.qqVersion = opts.qqVersion;
625
+ this.implVersion = opts.implVersion;
626
+ this.mediaDir = opts.mediaDir;
627
+ this.logger = opts.logger;
628
+ this.seqIndex = seqIndex;
629
+ }
630
+ /** uin → uid(私聊目标 / at 段发送转换 / 群管动作的 uid 入参)。 */
631
+ uinToUid(uins) {
632
+ return this.groupApi.uinToUid(uins);
633
+ }
634
+ /** uid → uin(事件路径 mention 转换)。 */
635
+ uidToUin(uids) {
636
+ return this.groupApi.uidToUin(uids);
637
+ }
638
+ /**
639
+ * uin(数字)→ uid(群管动作入参转换);转换失败抛 INVALID_PARAM
640
+ * (Milky 入参 user_id 都是 uin,kernel 群管 API 要 uid)。
641
+ */
642
+ async resolveUidFromUin(uin) {
643
+ const uinStr = String(uin);
644
+ try {
645
+ const uid = (await this.uinToUid([uinStr])).get(uinStr);
646
+ if (uid !== void 0 && uid !== "") return uid;
647
+ } catch {}
648
+ throw kernelError(`用户 ${uinStr} 不存在或 uin→uid 转换失败`, "INVALID_PARAM");
649
+ }
650
+ /**
651
+ * message_scene + 数字 ID → NT Peer。
652
+ * group = 群号直作 peerUid;friend/temp = uin → uid(失败退 uin 原样,交 QQ 端判断)。
653
+ */
654
+ async resolvePeer(scene, id) {
655
+ if (scene === "group") return {
542
656
  chatType: ChatType.GROUP,
543
- peerUid: groupCode
657
+ peerUid: String(id)
658
+ };
659
+ const uin = String(id);
660
+ let uid;
661
+ try {
662
+ uid = (await this.uinToUid([uin])).get(uin);
663
+ } catch {}
664
+ return {
665
+ chatType: scene === "friend" ? ChatType.C2C : ChatType.C2C_TEMP,
666
+ peerUid: uid ?? uin
667
+ };
668
+ }
669
+ /**
670
+ * seq → msgId(索引优先,未登记扫描近段历史兜底)。
671
+ * 两层都未命中返回 undefined(调用方抛 NOT_FOUND)。
672
+ */
673
+ async resolveMsgIdBySeq(peer, seq, chatType) {
674
+ const indexed = this.seqIndex.resolveMsgId(chatType, peer.peerUid, seq);
675
+ if (indexed !== void 0) return indexed;
676
+ const hit = (await this.msgApi.fetchMessages(peer, { count: 60 }).catch(() => [])).find((m) => Number(m.msgSeq) === seq);
677
+ if (hit === void 0) return;
678
+ this.seqIndex.record(hit);
679
+ return hit.msgId;
680
+ }
681
+ /** 发送结果回查:msgId → {message_seq, time}(sendMessage 只回 msgId)。 */
682
+ async resolveSentOutput(peer, msgId) {
683
+ const [sent] = await this.msgApi.fetchMsgsByMsgId(peer, [msgId]);
684
+ if (sent === void 0) throw kernelError("发送结果回查失败(msgId 未命中)", "UNKNOWN");
685
+ this.seqIndex.record(sent);
686
+ return {
687
+ message_seq: Number(sent.msgSeq),
688
+ time: Math.floor(Number(sent.msgTime) / 1e3)
544
689
  };
545
- const msgId = await this.api.resolveMsgIdBySeq(peer, payload.message_seq, ChatType.GROUP);
546
- if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
547
- if (payload.is_set === false) await this.api.groupApi.removeGroupEssence(groupCode, msgId);
548
- else await this.api.groupApi.addGroupEssence(groupCode, msgId);
549
- return {};
550
690
  }
551
691
  };
552
- /** send_group_message_reaction:消息表情表态(reaction_type face→"1" / emoji→"2")。 */
553
- var SendGroupMessageReactionAction = class extends MilkyApiAction {
554
- name = "send_group_message_reaction";
555
- schema = z.object({
556
- ...groupIdField$1,
557
- message_seq: z.number().int().min(0),
558
- reaction: z.string().min(1),
559
- reaction_type: z.enum(["face", "emoji"]).nullable().optional(),
560
- is_add: z.boolean().nullable().optional()
561
- });
562
- async _handle(payload) {
563
- const peer = {
564
- chatType: ChatType.GROUP,
565
- peerUid: String(payload.group_id)
692
+ /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
693
+ const NOTIFY_SEARCH_COUNT$1 = 100;
694
+ /**
695
+ * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
696
+ * 屏序骨架走 core findFirstMatch)。
697
+ * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
698
+ * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
699
+ */
700
+ async function findGroupNotify(api, seq) {
701
+ const hit = await findFirstMatch([() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)], (item) => item.seq === seq);
702
+ if (hit === void 0) throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
703
+ return hit;
704
+ }
705
+ /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
706
+ async function findBuddyReq(api, initiatorUid) {
707
+ const hit = await findFirstMatch([() => api.friendApi.getBuddyReqList()], (req) => req.friendUid === initiatorUid);
708
+ if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
709
+ return hit;
710
+ }
711
+ // src/milky/helper/event/request.ts
712
+ /** BuddyReq → friend_request 事件(comment 取 words 字段,形状待校准,缺省空串)。 */
713
+ function toFriendRequestEvent(req, ctx) {
714
+ const words = req["words"];
715
+ return {
716
+ time: Math.floor(Date.now() / MS_TO_SEC$2),
717
+ self_id: Number(ctx.selfUin),
718
+ event_type: "friend_request",
719
+ data: {
720
+ initiator_id: toUin(req.friendUid, ctx),
721
+ initiator_uid: req.friendUid,
722
+ comment: typeof words === "string" ? words : "",
723
+ via: req.sourceName ?? ""
724
+ }
725
+ };
726
+ }
727
+ /** GroupNotify → Milky 群请求事件(非未处理状态 / 非请求类返回 null)。 */
728
+ function toGroupRequestEvent(notify, doubt, ctx) {
729
+ if (notify.status !== GroupNotifyMsgStatus.KUNHANDLE) return null;
730
+ const groupId = Number(notify.group?.groupCode ?? 0);
731
+ const seq = Number(notify.seq);
732
+ const time = Math.floor(Date.now() / MS_TO_SEC$2);
733
+ const selfId = Number(ctx.selfUin);
734
+ switch (notify.type) {
735
+ case GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS: return {
736
+ time,
737
+ self_id: selfId,
738
+ event_type: "group_join_request",
739
+ data: {
740
+ group_id: groupId,
741
+ notification_seq: seq,
742
+ is_filtered: doubt,
743
+ initiator_id: toUin(notify.user1?.uid, ctx),
744
+ comment: notify.postscript ?? ""
745
+ }
566
746
  };
567
- await this.api.msgApi.setMsgEmojiLike(peer, {
568
- msgSeq: String(payload.message_seq),
569
- emojiId: payload.reaction,
570
- emojiType: payload.reaction_type === "emoji" ? "2" : "1",
571
- like: payload.is_add !== false
572
- });
573
- return {};
747
+ case GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS: return {
748
+ time,
749
+ self_id: selfId,
750
+ event_type: "group_invited_join_request",
751
+ data: {
752
+ group_id: groupId,
753
+ notification_seq: seq,
754
+ initiator_id: toUin(notify.user1?.uid, ctx),
755
+ target_user_id: toUin(notify.user2?.uid, ctx)
756
+ }
757
+ };
758
+ case GroupNotifyMsgType.INVITED_BY_MEMBER: return {
759
+ time,
760
+ self_id: selfId,
761
+ event_type: "group_invitation",
762
+ data: {
763
+ group_id: groupId,
764
+ invitation_seq: seq,
765
+ initiator_id: toUin(notify.user1?.uid, ctx),
766
+ source_group_id: null
767
+ }
768
+ };
769
+ default: return null;
574
770
  }
575
- };
771
+ }
772
+ /**
773
+ * 群通知涉及的 uid 集合(去重;get_group_notifications 与事件广播共用)。
774
+ * kernel GroupEventChannel 的 onGroupNotifiesUpdated 回调参数已类型化
775
+ * (GroupNotify[]),无需防御收窄。
776
+ */
777
+ function collectNotifyUids(notifies) {
778
+ const uids = /* @__PURE__ */ new Set();
779
+ for (const n of notifies) for (const uid of [n.user1?.uid, n.user2?.uid]) if (uid !== void 0 && uid !== "") uids.add(uid);
780
+ return [...uids];
781
+ }
782
+ // src/milky/action/group-notice.ts
783
+ const groupIdField$1 = { group_id: z.number().int().min(10001) };
784
+ const optBool$1 = z.boolean().nullable().optional();
785
+ const optStr = z.string().nullable().optional();
576
786
  /**
577
787
  * get_group_notifications:获取群通知列表。
578
788
  * kernel getSingleScreenNotifies 为单屏快照(无翻页)——start_notification_seq
@@ -582,7 +792,7 @@ var GetGroupNotificationsAction = class extends MilkyApiAction {
582
792
  name = "get_group_notifications";
583
793
  schema = z.object({
584
794
  start_notification_seq: z.number().int().min(0).nullable().optional(),
585
- is_filtered: optBool,
795
+ is_filtered: optBool$1,
586
796
  limit: z.number().int().min(0).nullable().optional()
587
797
  });
588
798
  async _handle(payload) {
@@ -621,7 +831,7 @@ var AcceptGroupRequestAction = class extends HandleGroupNotifyBase {
621
831
  notification_seq: z.number().int().min(0),
622
832
  notification_type: z.enum(["join_request", "invited_join_request"]),
623
833
  ...groupIdField$1,
624
- is_filtered: optBool
834
+ is_filtered: optBool$1
625
835
  });
626
836
  approve = true;
627
837
  async _handle(payload) {
@@ -635,8 +845,8 @@ var RejectGroupRequestAction = class extends HandleGroupNotifyBase {
635
845
  notification_seq: z.number().int().min(0),
636
846
  notification_type: z.enum(["join_request", "invited_join_request"]),
637
847
  ...groupIdField$1,
638
- is_filtered: optBool,
639
- reason: optStr$1
848
+ is_filtered: optBool$1,
849
+ reason: optStr
640
850
  });
641
851
  approve = false;
642
852
  async _handle(payload) {
@@ -656,156 +866,22 @@ var AcceptGroupInvitationAction = class extends HandleGroupNotifyBase {
656
866
  }
657
867
  };
658
868
  /** reject_group_invitation:拒绝入群邀请。 */
659
- var RejectGroupInvitationAction = class extends HandleGroupNotifyBase {
660
- name = "reject_group_invitation";
661
- schema = z.object({
662
- ...groupIdField$1,
663
- invitation_seq: z.number().int().min(0)
664
- });
665
- approve = false;
666
- async _handle(payload) {
667
- return await this.respond(payload.invitation_seq, false);
668
- }
669
- };
670
- /** send_group_nudge:发送群戳一戳(self.uid 缺失报 INVALID_PARAM)。 */
671
- var SendGroupNudgeAction = class extends MilkyApiAction {
672
- name = "send_group_nudge";
673
- schema = z.object({
674
- ...groupIdField$1,
675
- ...userIdField
676
- });
677
- async _handle(payload) {
678
- const receiverUid = await this.api.resolveUidFromUin(payload.user_id);
679
- const peer = await this.api.resolvePeer("group", payload.group_id);
680
- await this.api.msgApi.sendNudge(peer, {
681
- receiverUid,
682
- callerUid: requireSelfUid$1(this.api)
683
- });
684
- return {};
685
- }
686
- };
687
- /** get_group_announcements:获取群公告列表(bulletin 形状待校准,宽松映射)。 */
688
- var GetGroupAnnouncementsAction = class extends MilkyApiAction {
689
- name = "get_group_announcements";
690
- schema = z.object({ ...groupIdField$1 });
691
- async _handle(payload) {
692
- const groupCode = String(payload.group_id);
693
- const bulletins = await this.api.groupApi.getGroupAnnouncements(groupCode);
694
- return { announcements: await Promise.all(bulletins.map((b) => bulletinToEntity(b, payload.group_id, this.api))) };
695
- }
696
- };
697
- /** send_group_announcement:发群公告(image_uri 落盘后经上传+发布两步)。 */
698
- var SendGroupAnnouncementAction = class extends MilkyApiAction {
699
- name = "send_group_announcement";
700
- schema = z.object({
701
- ...groupIdField$1,
702
- content: z.string().min(1),
703
- image_uri: optStr$1
704
- });
705
- async _handle(payload) {
706
- const groupCode = String(payload.group_id);
707
- let imagePath;
708
- if (payload.image_uri !== void 0 && payload.image_uri !== null && payload.image_uri !== "") imagePath = await resolveUriToPath(payload.image_uri, this.api.mediaDir);
709
- await this.api.groupApi.publishGroupAnnouncement(groupCode, payload.content, imagePath);
710
- return {};
711
- }
712
- };
713
- /** delete_group_announcement:删除群公告。 */
714
- var DeleteGroupAnnouncementAction = class extends MilkyApiAction {
715
- name = "delete_group_announcement";
716
- schema = z.object({
717
- ...groupIdField$1,
718
- announcement_id: z.string().min(1)
719
- });
720
- async _handle(payload) {
721
- await this.api.groupApi.deleteGroupAnnouncement(String(payload.group_id), payload.announcement_id);
722
- return {};
723
- }
724
- };
725
- /** set_group_avatar:设置群头像(image_uri → 本地路径)。 */
726
- var SetGroupAvatarAction = class extends MilkyApiAction {
727
- name = "set_group_avatar";
728
- schema = z.object({
729
- ...groupIdField$1,
730
- image_uri: z.string().min(1)
731
- });
732
- async _handle(payload) {
733
- const imagePath = await resolveUriToPath(payload.image_uri, this.api.mediaDir);
734
- await this.api.groupApi.setGroupAvatar(String(payload.group_id), imagePath);
735
- return {};
736
- }
737
- };
738
- /** set_group_member_special_title:设置专属头衔(uin → uid)。 */
739
- var SetGroupMemberSpecialTitleAction = class extends MilkyApiAction {
740
- name = "set_group_member_special_title";
741
- schema = z.object({
742
- ...groupIdField$1,
743
- ...userIdField,
744
- special_title: z.string()
745
- });
746
- async _handle(payload) {
747
- const uid = await this.api.resolveUidFromUin(payload.user_id);
748
- await this.api.groupApi.setMemberSpecialTitle(String(payload.group_id), uid, payload.special_title);
749
- return {};
750
- }
751
- };
752
- /** ---------- 内部辅助 ---------- */
753
- /** 通知查找数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
754
- const NOTIFY_SEARCH_COUNT = 100;
755
- /** get_group_notifications 默认 limit(规范 default 20)。 */
756
- const NOTIFICATIONS_DEFAULT_LIMIT = 20;
757
- /** NTGroupMemberRole 数值(ADMIN=3 / MEMBER=2,setMemberRole 入参)。 */
758
- const NTGroupMemberRoleAdmin = 3;
759
- const NTGroupMemberRoleMember = 2;
760
- /** 成员列表(GroupCache 优先,未装配直查)。 */
761
- async function membersOf(api, groupCode) {
762
- if (api.groupCache !== void 0) return await api.groupCache.getMembers(groupCode);
763
- return await api.groupApi.getGroupMemberList(groupCode, true);
764
- }
765
- /** 成员单查(user_id = uin;缓存路径经 uid,直查路径按 uin 匹配)。 */
766
- async function memberOf(api, groupId, userId) {
767
- const groupCode = String(groupId);
768
- const uin = String(userId);
769
- if (api.groupCache !== void 0) {
770
- const uid = await api.resolveUidFromUin(userId).catch(() => uin);
771
- const member = await api.groupCache.getMember(groupCode, uid);
772
- if (member === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
773
- return member;
774
- }
775
- const hit = (await api.groupApi.getGroupMemberList(groupCode, true)).find((m) => m.uin === uin);
776
- if (hit === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
777
- return hit;
778
- }
779
- /** 精华项 → GroupEssenceMessage(msg_content 近似翻译:text / image)。 */
780
- function essenceToEntity(item, groupId) {
781
- const segments = [];
782
- for (const c of item.msg_content) if (c.text !== void 0 && c.text !== "") segments.push({
783
- type: "text",
784
- data: { text: c.text }
785
- });
786
- else if (c.image_url !== void 0 && c.image_url !== "") segments.push({
787
- type: "image",
788
- data: {
789
- resource_id: c.image_url,
790
- temp_url: c.image_url,
791
- width: 0,
792
- height: 0,
793
- summary: "",
794
- sub_type: "normal"
795
- }
869
+ var RejectGroupInvitationAction = class extends HandleGroupNotifyBase {
870
+ name = "reject_group_invitation";
871
+ schema = z.object({
872
+ ...groupIdField$1,
873
+ invitation_seq: z.number().int().min(0)
796
874
  });
797
- return {
798
- group_id: groupId,
799
- message_seq: item.msg_seq,
800
- message_time: item.add_digest_time,
801
- sender_id: Number(item.sender_uin) || 0,
802
- sender_name: item.sender_nick,
803
- operator_id: Number(item.add_digest_uin) || 0,
804
- operator_name: item.add_digest_nick,
805
- operation_time: item.add_digest_time,
806
- segments
807
- };
808
- }
875
+ approve = false;
876
+ async _handle(payload) {
877
+ return await this.respond(payload.invitation_seq, false);
878
+ }
879
+ };
880
+ /** ---------- 内部辅助 ---------- */
881
+ /** 通知查找数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
882
+ const NOTIFY_SEARCH_COUNT = 100;
883
+ /** get_group_notifications 默认 limit(规范 default 20)。 */
884
+ const NOTIFICATIONS_DEFAULT_LIMIT = 20;
809
885
  /**
810
886
  * GroupNotify → GroupNotificationEntity(uidToUin 已由调用方批量转换)。
811
887
  * 类型→构造器表:7=入群申请 / 5=成员邀请他人 / 8=设管理 / 12,13=取消管理 /
@@ -873,213 +949,158 @@ function notifyToEntity(notify, isFiltered, uidToUin) {
873
949
  if (entity.type === "join_request") entity.is_filtered = isFiltered;
874
950
  return entity;
875
951
  }
876
- /** self.uid 必备(nudge 发送的 callerUid;缺配置报 INVALID_PARAM)。 */
877
- function requireSelfUid$1(api) {
878
- const uid = api.self.uid;
879
- if (uid === void 0 || uid === "") throw kernelError("登录身份缺 uid(无法发起戳一戳)", "INVALID_PARAM");
880
- return uid;
881
- }
882
- /** GroupBulletin → 群公告实体(senderUid → uin 反查;无源字段兜底,待校准)。 */
883
- async function bulletinToEntity(b, groupId, api) {
952
+ // src/milky/helper/message/entities.ts
953
+ /** GroupDetailInfo / Group → GroupEntity(detail 缺失时全兜底)。 */
954
+ function toGroupEntity(detail, groupCode) {
884
955
  return {
885
- group_id: groupId,
886
- announcement_id: b.announcementId ?? "",
887
- user_id: await senderUinOf(b, api),
888
- time: Number(b.publishTime) || 0,
889
- content: b.content ?? "",
890
- image_url: picUrlOf(b)
956
+ group_id: Number(groupCode),
957
+ group_name: detail?.groupName ?? "",
958
+ member_count: detail?.memberNum ?? 0,
959
+ max_member_count: detail?.maxMemberNum ?? 0,
960
+ remark: detail?.remarkName ?? "",
961
+ created_time: detail?.groupCreateTime ?? 0,
962
+ description: "",
963
+ question: "",
964
+ announcement: ""
891
965
  };
892
966
  }
893
- /** 公告发送者 uid → uin(缺省/转换失败 0 兜底)。 */
894
- async function senderUinOf(b, api) {
895
- const uid = b.senderUid;
896
- if (typeof uid !== "string" || uid === "") return 0;
897
- const uins = await api.uidToUin([uid]).catch(() => void 0);
898
- return Number(uins?.get(uid)) || 0;
899
- }
900
- /** 公告图片 url(缺省 null)。 */
901
- function picUrlOf(b) {
902
- const url = b.pic?.url;
903
- return typeof url === "string" && url !== "" ? url : null;
904
- }
905
- // src/milky/action/group-file.ts
906
- const groupIdField = { group_id: z.number().int().min(10001) };
907
- const fileIdField = { file_id: z.string().min(1) };
908
- const optStr = z.string().nullable().optional();
909
- /** get_group_files:获取群文件列表(根目录或指定文件夹;过滤 parent 匹配项)。 */
910
- var GetGroupFilesAction = class extends MilkyApiAction {
911
- name = "get_group_files";
912
- schema = z.object({
913
- ...groupIdField,
914
- parent_folder_id: optStr
915
- });
916
- async _handle(payload) {
917
- const groupCode = String(payload.group_id);
918
- const parent = payload.parent_folder_id ?? "";
919
- const items = await this.api.richMediaApi.getGroupFileList(groupCode, parent);
920
- const files = [];
921
- const folders = [];
922
- for (const item of items) if (item.fileInfo !== void 0) files.push(fileToEntity(item.fileInfo, payload.group_id));
923
- else if (item.folderInfo !== void 0) folders.push(folderToEntity(item.folderInfo, payload.group_id));
924
- return {
925
- files,
926
- folders
927
- };
928
- }
929
- };
930
- /** move_group_file:移动文件(target_folder_id 空 = 移到根目录;parent 入参仅 schema 兼容)。 */
931
- var MoveGroupFileAction = class extends MilkyApiAction {
932
- name = "move_group_file";
933
- schema = z.object({
934
- ...groupIdField,
935
- ...fileIdField,
936
- parent_folder_id: optStr,
937
- target_folder_id: optStr
938
- });
939
- async _handle(payload) {
940
- await this.api.richMediaApi.moveGroupFile(String(payload.group_id), [payload.file_id], payload.target_folder_id ?? "");
941
- return {};
942
- }
943
- };
944
- /** rename_group_file:重命名文件。 */
945
- var RenameGroupFileAction = class extends MilkyApiAction {
946
- name = "rename_group_file";
947
- schema = z.object({
948
- ...groupIdField,
949
- ...fileIdField,
950
- parent_folder_id: optStr,
951
- new_file_name: z.string().min(1)
952
- });
953
- async _handle(payload) {
954
- await this.api.richMediaApi.renameGroupFile(String(payload.group_id), payload.file_id, payload.new_file_name);
955
- return {};
956
- }
957
- };
958
- /** delete_group_file:删除文件。 */
959
- var DeleteGroupFileAction = class extends MilkyApiAction {
960
- name = "delete_group_file";
961
- schema = z.object({
962
- ...groupIdField,
963
- ...fileIdField
964
- });
965
- async _handle(payload) {
966
- await this.api.richMediaApi.deleteGroupFile(String(payload.group_id), [payload.file_id]);
967
- return {};
968
- }
969
- };
970
- /**
971
- * persist_group_file:转存文件(RichMediaApi.transGroupFile,转存语义待对齐)。
972
- */
973
- var PersistGroupFileAction = class extends MilkyApiAction {
974
- name = "persist_group_file";
975
- schema = z.object({
976
- ...groupIdField,
977
- ...fileIdField
978
- });
979
- async _handle(payload) {
980
- await this.api.richMediaApi.transGroupFile(String(payload.group_id), payload.file_id);
981
- return {};
982
- }
983
- };
984
- /** create_group_folder:创建文件夹(返回 folder_id)。 */
985
- var CreateGroupFolderAction = class extends MilkyApiAction {
986
- name = "create_group_folder";
987
- schema = z.object({
988
- ...groupIdField,
989
- folder_name: z.string().min(1)
990
- });
991
- async _handle(payload) {
992
- return { folder_id: await this.api.richMediaApi.createGroupFolder(String(payload.group_id), payload.folder_name) };
993
- }
994
- };
995
- /** delete_group_folder:删除文件夹。 */
996
- var DeleteGroupFolderAction = class extends MilkyApiAction {
997
- name = "delete_group_folder";
998
- schema = z.object({
999
- ...groupIdField,
1000
- folder_id: z.string().min(1)
1001
- });
1002
- async _handle(payload) {
1003
- await this.api.richMediaApi.deleteGroupFolder(String(payload.group_id), payload.folder_id);
1004
- return {};
1005
- }
1006
- };
1007
- /** GroupFileItemInfo → GroupFileEntity(fileSize 原生为字符串;无源字段兜底)。 */
1008
- function fileToEntity(info, groupId) {
967
+ /** 群列表项(GroupCache Group)→ GroupEntity。 */
968
+ function groupListToEntity(group) {
1009
969
  return {
1010
- group_id: groupId,
1011
- file_id: info.fileId,
1012
- file_name: info.fileName,
1013
- parent_folder_id: info.parent ?? "",
1014
- file_size: Number(info.fileSize) || 0,
1015
- uploaded_time: Number(info.uploadTime) || 0,
1016
- expire_time: null,
1017
- uploader_id: Number(info.uploaderUin) || 0,
1018
- downloaded_times: 0
970
+ group_id: Number(group.groupCode),
971
+ group_name: group.groupName,
972
+ member_count: group.memberCount,
973
+ max_member_count: group.maxMember,
974
+ remark: "",
975
+ created_time: 0,
976
+ description: "",
977
+ question: "",
978
+ announcement: ""
1019
979
  };
1020
980
  }
1021
- /** GroupFolderInfo → GroupFolderEntity(元数据无类型字段防御读取,缺省 0)。 */
1022
- function folderToEntity(info, groupId) {
1023
- const num = (key) => {
1024
- const v = info[key];
1025
- return typeof v === "number" ? v : Number(v) || 0;
981
+ /** GroupMember → GroupMemberEntity(member 缺失时按 uin 兜底最小实体)。 */
982
+ function toGroupMemberEntity(member, groupCode, uin) {
983
+ const shutUpSeconds = member?.shutUpTime ?? 0;
984
+ return {
985
+ user_id: Number(member?.uin !== void 0 && member.uin !== "" ? member.uin : uin),
986
+ nickname: member?.nick ?? "",
987
+ sex: "unknown",
988
+ group_id: Number(groupCode),
989
+ card: member?.cardName ?? "",
990
+ title: member?.memberSpecialTitle ?? "",
991
+ level: 0,
992
+ role: GroupApi.roleToString(member?.role ?? 2),
993
+ join_time: Number(member?.joinTime) || 0,
994
+ last_sent_time: Number(member?.lastSpeakTime) || 0,
995
+ shut_up_end_time: shutUpSeconds > 0 ? Math.floor(Date.now() / 1e3) + shutUpSeconds : null
1026
996
  };
997
+ }
998
+ /** Friend → FriendEntity(kernel 无 qid/分类挂载,按最小实体兜底)。 */
999
+ function toFriendEntity(friend, uin, nick) {
1027
1000
  return {
1028
- group_id: groupId,
1029
- folder_id: info.folderId,
1030
- parent_folder_id: info.folderUid ?? "",
1031
- folder_name: info.folderName,
1032
- created_time: num("createTime"),
1033
- last_modified_time: num("modifyTime"),
1034
- creator_id: 0,
1035
- file_count: num("totalFileCount")
1001
+ user_id: Number(friend?.uin !== void 0 && friend.uin !== "" ? friend.uin : uin),
1002
+ nickname: friend?.nickname ?? nick,
1003
+ sex: "unknown",
1004
+ qid: "",
1005
+ remark: friend?.remark ?? "",
1006
+ category: {
1007
+ category_id: 0,
1008
+ category_name: ""
1009
+ }
1036
1010
  };
1037
1011
  }
1038
- /**
1039
- * upload_group_file:上传并投递文件(**闪传通道**:分享链接卡片,见文件头语义说明)。
1040
- * file_id 返回闪传文件集 id(非群文件 fileId)。
1041
- */
1042
- var UploadGroupFileAction = class extends MilkyApiAction {
1043
- name = "upload_group_file";
1012
+ // src/milky/action/group-query.ts
1013
+ const groupIdField = { group_id: z.number().int().min(10001) };
1014
+ const userIdField = { user_id: z.number().int().min(10001) };
1015
+ const optBool = z.boolean().nullable().optional();
1016
+ /** get_group_info:获取群信息(GroupCache 详情缓存优先)。 */
1017
+ var GetGroupInfoAction = class extends MilkyApiAction {
1018
+ name = "get_group_info";
1044
1019
  schema = z.object({
1045
1020
  ...groupIdField,
1046
- parent_folder_id: optStr,
1047
- file_uri: z.string().min(1),
1048
- file_name: z.string().min(1)
1021
+ no_cache: optBool
1049
1022
  });
1050
1023
  async _handle(payload) {
1051
- const path = await resolveUriToPath(payload.file_uri, this.api.mediaDir);
1052
- const peer = {
1053
- chatType: ChatType.GROUP,
1054
- peerUid: String(payload.group_id)
1055
- };
1056
- return { file_id: (await this.api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1024
+ const groupCode = String(payload.group_id);
1025
+ return { group: toGroupEntity(this.api.groupCache !== void 0 ? await this.api.groupCache.getGroupDetail(groupCode) : await this.api.groupApi.getGroupInfo(groupCode), groupCode) };
1057
1026
  }
1058
1027
  };
1059
- /** get_group_file_download_url:群文件下载链接(url 字段待实机确认,仅根目录)。 */
1060
- var GetGroupFileDownloadUrlAction = class extends MilkyApiAction {
1061
- name = "get_group_file_download_url";
1028
+ /** get_group_member_list:获取群成员列表(GroupCache 惰性回填)。 */
1029
+ var GetGroupMemberListAction = class extends MilkyApiAction {
1030
+ name = "get_group_member_list";
1062
1031
  schema = z.object({
1063
1032
  ...groupIdField,
1064
- ...fileIdField
1033
+ no_cache: optBool
1065
1034
  });
1066
1035
  async _handle(payload) {
1067
- return { download_url: await this.api.richMediaApi.getGroupFileDownloadUrl(String(payload.group_id), payload.file_id) };
1036
+ return { members: (await membersOf(this.api, String(payload.group_id))).map((m) => toGroupMemberEntity(m, String(payload.group_id), m.uin)) };
1068
1037
  }
1069
1038
  };
1070
- /** rename_group_folder:重命名群文件夹(renameGroupFile 同款形态,待校准)。 */
1071
- var RenameGroupFolderAction = class extends MilkyApiAction {
1072
- name = "rename_group_folder";
1039
+ /** get_group_member_info:获取群成员信息(user_id = uin → 成员单查)。 */
1040
+ var GetGroupMemberInfoAction = class extends MilkyApiAction {
1041
+ name = "get_group_member_info";
1073
1042
  schema = z.object({
1074
1043
  ...groupIdField,
1075
- folder_id: z.string().min(1),
1076
- new_folder_name: z.string().min(1)
1044
+ ...userIdField,
1045
+ no_cache: optBool
1077
1046
  });
1078
1047
  async _handle(payload) {
1079
- await this.api.richMediaApi.renameGroupFolder(String(payload.group_id), payload.folder_id, payload.new_folder_name);
1080
- return {};
1048
+ return { member: toGroupMemberEntity(await memberOf(this.api, payload.group_id, payload.user_id), String(payload.group_id), String(payload.user_id)) };
1049
+ }
1050
+ };
1051
+ /** get_group_announcements:获取群公告列表(bulletin 形状待校准,宽松映射)。 */
1052
+ var GetGroupAnnouncementsAction = class extends MilkyApiAction {
1053
+ name = "get_group_announcements";
1054
+ schema = z.object({ ...groupIdField });
1055
+ async _handle(payload) {
1056
+ const groupCode = String(payload.group_id);
1057
+ const bulletins = await this.api.groupApi.getGroupAnnouncements(groupCode);
1058
+ return { announcements: await Promise.all(bulletins.map((b) => bulletinToEntity(b, payload.group_id, this.api))) };
1081
1059
  }
1082
1060
  };
1061
+ /** ---------- 内部辅助 ---------- */
1062
+ /** 成员列表(GroupCache 优先,未装配直查)。 */
1063
+ async function membersOf(api, groupCode) {
1064
+ if (api.groupCache !== void 0) return await api.groupCache.getMembers(groupCode);
1065
+ return await api.groupApi.getGroupMemberList(groupCode, true);
1066
+ }
1067
+ /** 成员单查(user_id = uin;缓存路径经 uid,直查路径按 uin 匹配)。 */
1068
+ async function memberOf(api, groupId, userId) {
1069
+ const groupCode = String(groupId);
1070
+ const uin = String(userId);
1071
+ if (api.groupCache !== void 0) {
1072
+ const uid = await api.resolveUidFromUin(userId).catch(() => uin);
1073
+ const member = await api.groupCache.getMember(groupCode, uid);
1074
+ if (member === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
1075
+ return member;
1076
+ }
1077
+ const hit = (await api.groupApi.getGroupMemberList(groupCode, true)).find((m) => m.uin === uin);
1078
+ if (hit === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
1079
+ return hit;
1080
+ }
1081
+ /** GroupBulletin → 群公告实体(senderUid → uin 反查;无源字段兜底,待校准)。 */
1082
+ async function bulletinToEntity(b, groupId, api) {
1083
+ return {
1084
+ group_id: groupId,
1085
+ announcement_id: b.announcementId ?? "",
1086
+ user_id: await senderUinOf(b, api),
1087
+ time: Number(b.publishTime) || 0,
1088
+ content: b.content ?? "",
1089
+ image_url: picUrlOf(b)
1090
+ };
1091
+ }
1092
+ /** 公告发送者 uid → uin(缺省/转换失败 0 兜底)。 */
1093
+ async function senderUinOf(b, api) {
1094
+ const uid = b.senderUid;
1095
+ if (typeof uid !== "string" || uid === "") return 0;
1096
+ const uins = await api.uidToUin([uid]).catch(() => void 0);
1097
+ return Number(uins?.get(uid)) || 0;
1098
+ }
1099
+ /** 公告图片 url(缺省 null)。 */
1100
+ function picUrlOf(b) {
1101
+ const url = b.pic?.url;
1102
+ return typeof url === "string" && url !== "" ? url : null;
1103
+ }
1083
1104
  // src/milky/helper/message/segments.ts
1084
1105
  /**
1085
1106
  * Milky 消息段 ↔ canonical 元素转换(纯函数,ADR-008)
@@ -1443,211 +1464,63 @@ function toMessageRecallEvent(msg, ctx) {
1443
1464
  sender_id: Number(msg.senderUin),
1444
1465
  operator_id: Number(operatorUin) || 0,
1445
1466
  display_suffix: revoke.wording ?? ""
1446
- }
1447
- };
1448
- }
1449
- /** 群文件上传事件(群场景文件消息 → group_file_upload,替代 message_receive)。 */
1450
- function toGroupFileUploadEvent(msg, selfUin) {
1451
- if (msg.chatType !== ChatType.GROUP) return null;
1452
- const file = msg.elements.find((el) => el.fileElement != null)?.fileElement;
1453
- if (file === void 0) return null;
1454
- return {
1455
- time: Math.floor(Number(msg.msgTime) / MS_TO_SEC$1),
1456
- self_id: Number(selfUin),
1457
- event_type: "group_file_upload",
1458
- data: {
1459
- group_id: Number(msg.peerUid),
1460
- user_id: Number(msg.senderUin) || 0,
1461
- file_id: file.fileUuid ?? file.fileName ?? "",
1462
- file_name: file.fileName ?? "",
1463
- file_size: Number(file.fileSize ?? 0)
1464
- }
1465
- };
1466
- }
1467
- // src/milky/action/message.ts
1468
- /**
1469
- * OutgoingSegment 宽松校验:入口只保证「{type, data}」形状,字段级转换在
1470
- * outgoingSegmentsToCanonical 内做(未知段跳过 = 规范兼容性要求)。
1471
- */
1472
- const outgoingSegmentSchema = z.object({
1473
- type: z.string(),
1474
- data: z.record(z.string(), z.unknown())
1475
- }).loose();
1476
- const sendMessageFields = { message: z.array(outgoingSegmentSchema).min(1).max(200) };
1477
- const recallFields = { message_seq: z.number().int().min(0) };
1478
- /** send_private_message:发送私聊消息。 */
1479
- var SendPrivateMessageAction = class extends MilkyApiAction {
1480
- name = "send_private_message";
1481
- schema = z.object({
1482
- user_id: z.number().int().min(10001),
1483
- ...sendMessageFields
1484
- });
1485
- async _handle(payload) {
1486
- return await sendMilkyMessage(await this.api.resolvePeer("friend", payload.user_id), payload.message, this.api);
1487
- }
1488
- };
1489
- /** send_group_message:发送群聊消息。 */
1490
- var SendGroupMessageAction = class extends MilkyApiAction {
1491
- name = "send_group_message";
1492
- schema = z.object({
1493
- group_id: z.number().int().min(10001),
1494
- ...sendMessageFields
1495
- });
1496
- async _handle(payload) {
1497
- return await sendMilkyMessage(await this.api.resolvePeer("group", payload.group_id), payload.message, this.api);
1498
- }
1499
- };
1500
- /** get_message:获取单条消息(seq → msgId 反查 + 实体回填)。 */
1501
- var GetMessageAction = class extends MilkyApiAction {
1502
- name = "get_message";
1503
- schema = z.object({ ...peerMessageFields });
1504
- async _handle(payload) {
1505
- const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1506
- const msgId = await this.api.resolveMsgIdBySeq(peer, payload.message_seq, peer.chatType);
1507
- if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1508
- const [msg] = await this.api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
1509
- if (msg === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1510
- return { message: await this.translateWithEntities(payload.message_scene, peer, msg) };
1511
- }
1512
- /** 实体回填(group 场景 schema 要求完整实体)→ IncomingMessage。 */
1513
- async translateWithEntities(scene, peer, msg) {
1514
- const ctx = { selfUin: this.api.self.uin };
1515
- if (scene === "group") {
1516
- const [detail, member] = await Promise.all([this.api.groupCache?.getGroupDetail(peer.peerUid).catch(() => void 0), this.api.groupCache?.getMember(peer.peerUid, msg.senderUid).catch(() => void 0)]);
1517
- ctx.groupEntity = toGroupEntity(detail, peer.peerUid);
1518
- ctx.groupMemberEntity = toGroupMemberEntity(member, peer.peerUid, msg.senderUin);
1519
- }
1520
- return toMessageReceiveEvent(msg, ctx).data;
1521
- }
1522
- };
1523
- /** recall_private_message:撤回私聊消息。 */ var RecallPrivateMessageAction = class extends MilkyApiAction {
1524
- name = "recall_private_message";
1525
- schema = z.object({
1526
- user_id: z.number().int().min(10001),
1527
- ...recallFields
1528
- });
1529
- async _handle(payload) {
1530
- await recallBySeq(await this.api.resolvePeer("friend", payload.user_id), payload.message_seq, this.api);
1531
- return {};
1532
- }
1533
- };
1534
- /** recall_group_message:撤回群消息。 */
1535
- var RecallGroupMessageAction = class extends MilkyApiAction {
1536
- name = "recall_group_message";
1537
- schema = z.object({
1538
- group_id: z.number().int().min(10001),
1539
- ...recallFields
1540
- });
1541
- async _handle(payload) {
1542
- await recallBySeq(await this.api.resolvePeer("group", payload.group_id), payload.message_seq, this.api);
1543
- return {};
1544
- }
1545
- };
1546
- /** seq → msgId(反查)→ recallMessage。 */
1547
- async function recallBySeq(peer, seq, api) {
1548
- const msgId = await api.resolveMsgIdBySeq(peer, seq, peer.chatType);
1549
- if (msgId === void 0) throw kernelError(`消息 ${seq} 不存在`, "NOT_FOUND");
1550
- await api.msgApi.recallMessage(peer, [msgId]);
1551
- }
1552
- /** 发送核心:segments → canonical(URI/ID 转换)→ sendMessage → 回查输出。
1553
- * forward 段分流到组装链(P2 批次一,临时消息法)。 */
1554
- async function sendMilkyMessage(peer, segments, api) {
1555
- if (segments.some((s) => s.type === "forward")) return await sendForwardComposition(peer, segments, api);
1556
- const { elements, atUins } = outgoingSegmentsToCanonical(segments);
1557
- const resolved = await resolveElements(elements, atUins, api);
1558
- if (resolved.length === 0) throw kernelError("消息内容为空(全部消息段不可用)", "INVALID_PARAM");
1559
- const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1560
- return await api.resolveSentOutput(peer, msgId);
1561
- }
1562
- /**
1563
- * forward 段组装链(P2 批次一,milky.md §0.6):仅支持单 forward 单独发。
1564
- * 临时消息法:逐条发送 messages[i].segments → sendForwardMessage(buildMultiForwardMsg
1565
- * 以目标 peer 的真实消息组装 → sendMsg)→ best-effort 撤回临时消息 → 回查输出。
1566
- *
1567
- * 已知差异(规范语义 vs kernel 出口,待实机联调):节点发送者恒为机器人自己
1568
- * (user_id / sender_name / time 不参与组装);title / preview / summary / prompt 忽略。
1569
- */
1570
- async function sendForwardComposition(peer, segments, api) {
1571
- if (segments.length !== 1) throw kernelError("forward 段必须单独发送(不支持与其他消息段混发)", "INVALID_PARAM");
1572
- const [forward] = segments;
1573
- if (forward === void 0 || forward.type !== "forward") throw kernelError("forward 组装链收到非 forward 段", "UNKNOWN");
1574
- const messages = narrowForwardMessages(forward);
1575
- const srcMsgIds = [];
1576
- for (const [i, item] of messages.entries()) {
1577
- const { elements, atUins } = outgoingSegmentsToCanonical(item.segments);
1578
- const resolved = await resolveElements(elements, atUins, api);
1579
- if (resolved.length === 0) throw kernelError(`forward 第 ${i + 1} 条消息无可用内容段`, "INVALID_PARAM");
1580
- const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1581
- srcMsgIds.push(msgId);
1582
- }
1583
- const { msgId } = await api.msgApi.sendForwardMessage(peer, peer, srcMsgIds);
1584
- await recallTempMessages(peer, srcMsgIds, api);
1585
- return await api.resolveSentOutput(peer, msgId);
1586
- }
1587
- /**
1588
- * forward 段载荷收窄(入口 schema 只保证 data 为 record):messages 非空数组,
1589
- * 项内 segments 非空数组。user_id / sender_name / time 不参与组装不校验
1590
- * (丢弃字段不设门槛);title / preview / summary / prompt 忽略。
1591
- */
1592
- function narrowForwardMessages(forward) {
1593
- const raw = forward.data.messages;
1594
- if (!Array.isArray(raw) || raw.length === 0) throw kernelError("forward 段 messages 必须是非空数组", "INVALID_PARAM");
1595
- const out = [];
1596
- for (const item of raw) {
1597
- if (typeof item !== "object" || item === null) throw kernelError("forward 段 messages 项必须是对象", "INVALID_PARAM");
1598
- const segments = item.segments;
1599
- if (!Array.isArray(segments) || segments.length === 0) throw kernelError("forward 段 messages 项的 segments 必须是非空数组", "INVALID_PARAM");
1600
- out.push(item);
1601
- }
1602
- return out;
1603
- }
1604
- /** 临时消息清理(best-effort:失败只留可见垃圾,转发已发出——warn 可观测不抛)。 */
1605
- async function recallTempMessages(peer, msgIds, api) {
1606
- try {
1607
- await api.msgApi.recallMessage(peer, msgIds);
1608
- } catch (e) {
1609
- api.logger?.warn({
1610
- peer: peer.peerUid,
1611
- count: msgIds.length,
1612
- error: e instanceof Error ? e.message : String(e)
1613
- }, "milky: forward 临时消息撤回失败(转发已发出)");
1614
- }
1615
- }
1616
- /** 元素二次解析:at uin→uid + 远程媒体 URI 落盘(reply seq 已在映射层兜底原样)。 */
1617
- async function resolveElements(elements, atUins, api) {
1618
- const uinToUid = await resolveAtUins(atUins, api);
1619
- const out = [];
1620
- for (const el of elements) out.push(await resolveElement(el, uinToUid, api));
1621
- return out;
1622
- }
1623
- /** at uin→uid 批量转换(失败返回 undefined:at 原样 uin,交 QQ 端判断)。 */
1624
- async function resolveAtUins(atUins, api) {
1625
- if (atUins.length === 0) return;
1626
- try {
1627
- return await api.uinToUid(atUins);
1628
- } catch {
1629
- return;
1630
- }
1631
- }
1632
- /** 单元素解析:at 目标替换 / 远程媒体 URI 落盘 / 其余原样。 */
1633
- async function resolveElement(el, uinToUid, api) {
1634
- if (el.type === "at" && el.target !== "all") return {
1635
- ...el,
1636
- target: uinToUid?.get(el.target) ?? el.target
1467
+ }
1637
1468
  };
1638
- if (isRemoteMediaUri(el)) {
1639
- const media = el;
1640
- return {
1641
- ...media,
1642
- path: await resolveMediaUri(media.path, api.mediaDir)
1643
- };
1644
- }
1645
- return el;
1646
1469
  }
1647
- /** 远程媒体元素(image/voice/video 且 path 为需落盘的 URI)。 */
1648
- function isRemoteMediaUri(el) {
1649
- return (el.type === "image" || el.type === "voice" || el.type === "video") && (el.path.startsWith("http://") || el.path.startsWith("https://") || el.path.startsWith("base64://"));
1470
+ /** 群文件上传事件(群场景文件消息 → group_file_upload,替代 message_receive)。 */
1471
+ function toGroupFileUploadEvent(msg, selfUin) {
1472
+ if (msg.chatType !== ChatType.GROUP) return null;
1473
+ const file = msg.elements.find((el) => el.fileElement != null)?.fileElement;
1474
+ if (file === void 0) return null;
1475
+ return {
1476
+ time: Math.floor(Number(msg.msgTime) / MS_TO_SEC$1),
1477
+ self_id: Number(selfUin),
1478
+ event_type: "group_file_upload",
1479
+ data: {
1480
+ group_id: Number(msg.peerUid),
1481
+ user_id: Number(msg.senderUin) || 0,
1482
+ file_id: file.fileUuid ?? file.fileName ?? "",
1483
+ file_name: file.fileName ?? "",
1484
+ file_size: Number(file.fileSize ?? 0)
1485
+ }
1486
+ };
1650
1487
  }
1488
+ // src/milky/action/message-query.ts
1489
+ /** get_message / mark_message_as_read 共入参(场景 + 对端 + seq)。 */
1490
+ const peerMessageFields = {
1491
+ message_scene: z.enum([
1492
+ "friend",
1493
+ "group",
1494
+ "temp"
1495
+ ]),
1496
+ peer_id: z.number().int().min(10001),
1497
+ message_seq: z.number().int().min(0)
1498
+ };
1499
+ /** get_message:获取单条消息(seq → msgId 反查 + 实体回填)。 */
1500
+ var GetMessageAction = class extends MilkyApiAction {
1501
+ name = "get_message";
1502
+ schema = z.object({ ...peerMessageFields });
1503
+ async _handle(payload) {
1504
+ const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1505
+ const msgId = await this.api.resolveMsgIdBySeq(peer, payload.message_seq, peer.chatType);
1506
+ if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1507
+ const [msg] = await this.api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
1508
+ if (msg === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1509
+ return { message: await this.translateWithEntities(payload.message_scene, peer, msg) };
1510
+ }
1511
+ /** 实体回填(group 场景 schema 要求完整实体)→ IncomingMessage。 */
1512
+ async translateWithEntities(scene, peer, msg) {
1513
+ const ctx = { selfUin: this.api.self.uin };
1514
+ if (scene === "group") {
1515
+ const [detail, member] = await Promise.all([this.api.groupCache?.getGroupDetail(peer.peerUid).catch(() => void 0), this.api.groupCache?.getMember(peer.peerUid, msg.senderUid).catch(() => void 0)]);
1516
+ ctx.groupEntity = toGroupEntity(detail, peer.peerUid);
1517
+ ctx.groupMemberEntity = toGroupMemberEntity(member, peer.peerUid, msg.senderUin);
1518
+ }
1519
+ return toMessageReceiveEvent(msg, ctx).data;
1520
+ }
1521
+ };
1522
+ /** 历史消息默认条数(规范 default 20)。 */
1523
+ const HISTORY_DEFAULT_LIMIT = 20;
1651
1524
  /** get_history_messages:获取历史消息(start seq 锚点 → 原生翻页 → 升序输出)。 */
1652
1525
  var GetHistoryMessagesAction = class extends MilkyApiAction {
1653
1526
  name = "get_history_messages";
@@ -1753,28 +1626,7 @@ var GetForwardedMessagesAction = class extends MilkyApiAction {
1753
1626
  return msg.senderUin;
1754
1627
  }
1755
1628
  };
1756
- /** mark_message_as_read:标记会话已读(NT setMsgRead 以会话为粒度,seq 入参仅兼容 schema)。 */
1757
- var MarkMessageAsReadAction = class extends MilkyApiAction {
1758
- name = "mark_message_as_read";
1759
- schema = z.object({ ...peerMessageFields });
1760
- async _handle(payload) {
1761
- const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1762
- await this.api.msgApi.markRead(peer);
1763
- return {};
1764
- }
1765
- };
1766
- /** 历史消息默认条数(规范 default 20)。 */
1767
- const HISTORY_DEFAULT_LIMIT = 20;
1768
- /** get_message / mark_message_as_read 共入参(场景 + 对端 + seq)。 */
1769
- const peerMessageFields = {
1770
- message_scene: z.enum([
1771
- "friend",
1772
- "group",
1773
- "temp"
1774
- ]),
1775
- peer_id: z.number().int().min(10001),
1776
- message_seq: z.number().int().min(0)
1777
- };
1629
+ /** ---------- 内部辅助 ---------- */
1778
1630
  /** 单条消息 → 接收段(canonical 映射 + forward 段注入,forward 不经 canonical)。 */
1779
1631
  function receiveSegmentsOf(msg, uidToUin) {
1780
1632
  const segments = canonicalToIncomingSegments(toCanonicalElements(msg), { ...uidToUin.size > 0 ? { uidToUin } : {} });
@@ -1786,6 +1638,48 @@ function receiveSegmentsOf(msg, uidToUin) {
1786
1638
  function avatarUrlOf(uin) {
1787
1639
  return uin === "" ? "" : `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=640`;
1788
1640
  }
1641
+ // src/milky/action/message-ops.ts
1642
+ const recallFields = { message_seq: z.number().int().min(0) };
1643
+ /** recall_private_message:撤回私聊消息。 */
1644
+ var RecallPrivateMessageAction = class extends MilkyApiAction {
1645
+ name = "recall_private_message";
1646
+ schema = z.object({
1647
+ user_id: z.number().int().min(10001),
1648
+ ...recallFields
1649
+ });
1650
+ async _handle(payload) {
1651
+ await recallBySeq(await this.api.resolvePeer("friend", payload.user_id), payload.message_seq, this.api);
1652
+ return {};
1653
+ }
1654
+ };
1655
+ /** recall_group_message:撤回群消息。 */
1656
+ var RecallGroupMessageAction = class extends MilkyApiAction {
1657
+ name = "recall_group_message";
1658
+ schema = z.object({
1659
+ group_id: z.number().int().min(10001),
1660
+ ...recallFields
1661
+ });
1662
+ async _handle(payload) {
1663
+ await recallBySeq(await this.api.resolvePeer("group", payload.group_id), payload.message_seq, this.api);
1664
+ return {};
1665
+ }
1666
+ };
1667
+ /** seq → msgId(反查)→ recallMessage。 */
1668
+ async function recallBySeq(peer, seq, api) {
1669
+ const msgId = await api.resolveMsgIdBySeq(peer, seq, peer.chatType);
1670
+ if (msgId === void 0) throw kernelError(`消息 ${seq} 不存在`, "NOT_FOUND");
1671
+ await api.msgApi.recallMessage(peer, [msgId]);
1672
+ }
1673
+ /** mark_message_as_read:标记会话已读(NT setMsgRead 以会话为粒度,seq 入参仅兼容 schema)。 */
1674
+ var MarkMessageAsReadAction = class extends MilkyApiAction {
1675
+ name = "mark_message_as_read";
1676
+ schema = z.object({ ...peerMessageFields });
1677
+ async _handle(payload) {
1678
+ const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1679
+ await this.api.msgApi.markRead(peer);
1680
+ return {};
1681
+ }
1682
+ };
1789
1683
  /** get_custom_face_url_list:收藏表情链接(queryFavEmojiByDesc 形状待校准)。 */
1790
1684
  var GetCustomFaceUrlListAction = class extends MilkyApiAction {
1791
1685
  name = "get_custom_face_url_list";
@@ -1826,6 +1720,139 @@ var UploadPrivateFileAction = class extends MilkyApiAction {
1826
1720
  return { file_id: (await this.api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1827
1721
  }
1828
1722
  };
1723
+ // src/milky/action/message-send.ts
1724
+ /**
1725
+ * OutgoingSegment 宽松校验:入口只保证「{type, data}」形状,字段级转换在
1726
+ * outgoingSegmentsToCanonical 内做(未知段跳过 = 规范兼容性要求)。
1727
+ */
1728
+ const outgoingSegmentSchema = z.object({
1729
+ type: z.string(),
1730
+ data: z.record(z.string(), z.unknown())
1731
+ }).loose();
1732
+ const sendMessageFields = { message: z.array(outgoingSegmentSchema).min(1).max(200) };
1733
+ /** send_private_message:发送私聊消息。 */
1734
+ var SendPrivateMessageAction = class extends MilkyApiAction {
1735
+ name = "send_private_message";
1736
+ schema = z.object({
1737
+ user_id: z.number().int().min(10001),
1738
+ ...sendMessageFields
1739
+ });
1740
+ async _handle(payload) {
1741
+ return await sendMilkyMessage(await this.api.resolvePeer("friend", payload.user_id), payload.message, this.api);
1742
+ }
1743
+ };
1744
+ /** send_group_message:发送群聊消息。 */
1745
+ var SendGroupMessageAction = class extends MilkyApiAction {
1746
+ name = "send_group_message";
1747
+ schema = z.object({
1748
+ group_id: z.number().int().min(10001),
1749
+ ...sendMessageFields
1750
+ });
1751
+ async _handle(payload) {
1752
+ return await sendMilkyMessage(await this.api.resolvePeer("group", payload.group_id), payload.message, this.api);
1753
+ }
1754
+ };
1755
+ /** ---------- 发送核心与组装链 ---------- */
1756
+ /** 发送核心:segments → canonical(URI/ID 转换)→ sendMessage → 回查输出。
1757
+ * forward 段分流到组装链(P2 批次一,临时消息法)。 */
1758
+ async function sendMilkyMessage(peer, segments, api) {
1759
+ if (segments.some((s) => s.type === "forward")) return await sendForwardComposition(peer, segments, api);
1760
+ const { elements, atUins } = outgoingSegmentsToCanonical(segments);
1761
+ const resolved = await resolveElements(elements, atUins, api);
1762
+ if (resolved.length === 0) throw kernelError("消息内容为空(全部消息段不可用)", "INVALID_PARAM");
1763
+ const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1764
+ return await api.resolveSentOutput(peer, msgId);
1765
+ }
1766
+ /**
1767
+ * forward 段组装链(P2 批次一,milky.md §0.6):仅支持单 forward 单独发。
1768
+ * 临时消息法:逐条发送 messages[i].segments → sendForwardMessage(buildMultiForwardMsg
1769
+ * 以目标 peer 的真实消息组装 → sendMsg)→ best-effort 撤回临时消息 → 回查输出。
1770
+ *
1771
+ * 已知差异(规范语义 vs kernel 出口,待实机联调):节点发送者恒为机器人自己
1772
+ * (user_id / sender_name / time 不参与组装);title / preview / summary / prompt 忽略。
1773
+ */
1774
+ async function sendForwardComposition(peer, segments, api) {
1775
+ if (segments.length !== 1) throw kernelError("forward 段必须单独发送(不支持与其他消息段混发)", "INVALID_PARAM");
1776
+ const [forward] = segments;
1777
+ if (forward === void 0 || forward.type !== "forward") throw kernelError("forward 组装链收到非 forward 段", "UNKNOWN");
1778
+ const messages = narrowForwardMessages(forward);
1779
+ const srcMsgIds = [];
1780
+ for (const [i, item] of messages.entries()) {
1781
+ const { elements, atUins } = outgoingSegmentsToCanonical(item.segments);
1782
+ const resolved = await resolveElements(elements, atUins, api);
1783
+ if (resolved.length === 0) throw kernelError(`forward 第 ${i + 1} 条消息无可用内容段`, "INVALID_PARAM");
1784
+ const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1785
+ srcMsgIds.push(msgId);
1786
+ }
1787
+ const { msgId } = await api.msgApi.sendForwardMessage(peer, peer, srcMsgIds);
1788
+ await recallTempMessages(peer, srcMsgIds, api);
1789
+ return await api.resolveSentOutput(peer, msgId);
1790
+ }
1791
+ /**
1792
+ * forward 段载荷收窄(入口 schema 只保证 data 为 record):messages 非空数组,
1793
+ * 项内 segments 非空数组。user_id / sender_name / time 不参与组装不校验
1794
+ * (丢弃字段不设门槛);title / preview / summary / prompt 忽略。
1795
+ */
1796
+ function narrowForwardMessages(forward) {
1797
+ const raw = forward.data.messages;
1798
+ if (!Array.isArray(raw) || raw.length === 0) throw kernelError("forward 段 messages 必须是非空数组", "INVALID_PARAM");
1799
+ const out = [];
1800
+ for (const item of raw) {
1801
+ if (typeof item !== "object" || item === null) throw kernelError("forward 段 messages 项必须是对象", "INVALID_PARAM");
1802
+ const segments = item.segments;
1803
+ if (!Array.isArray(segments) || segments.length === 0) throw kernelError("forward 段 messages 项的 segments 必须是非空数组", "INVALID_PARAM");
1804
+ out.push(item);
1805
+ }
1806
+ return out;
1807
+ }
1808
+ /** 临时消息清理(best-effort:失败只留可见垃圾,转发已发出——warn 可观测不抛)。 */
1809
+ async function recallTempMessages(peer, msgIds, api) {
1810
+ try {
1811
+ await api.msgApi.recallMessage(peer, msgIds);
1812
+ } catch (e) {
1813
+ api.logger?.warn({
1814
+ peer: peer.peerUid,
1815
+ count: msgIds.length,
1816
+ error: e instanceof Error ? e.message : String(e)
1817
+ }, "milky: forward 临时消息撤回失败(转发已发出)");
1818
+ }
1819
+ }
1820
+ /** ---------- 元素二次解析 ---------- */
1821
+ /** 元素二次解析:at uin→uid + 远程媒体 URI 落盘(reply seq 已在映射层兜底原样)。 */
1822
+ async function resolveElements(elements, atUins, api) {
1823
+ const uinToUid = await resolveAtUins(atUins, api);
1824
+ const out = [];
1825
+ for (const el of elements) out.push(await resolveElement(el, uinToUid, api));
1826
+ return out;
1827
+ }
1828
+ /** at uin→uid 批量转换(失败返回 undefined:at 原样 uin,交 QQ 端判断)。 */
1829
+ async function resolveAtUins(atUins, api) {
1830
+ if (atUins.length === 0) return;
1831
+ try {
1832
+ return await api.uinToUid(atUins);
1833
+ } catch {
1834
+ return;
1835
+ }
1836
+ }
1837
+ /** 单元素解析:at 目标替换 / 远程媒体 URI 落盘 / 其余原样。 */
1838
+ async function resolveElement(el, uinToUid, api) {
1839
+ if (el.type === "at" && el.target !== "all") return {
1840
+ ...el,
1841
+ target: uinToUid?.get(el.target) ?? el.target
1842
+ };
1843
+ if (isRemoteMediaUri(el)) {
1844
+ const media = el;
1845
+ return {
1846
+ ...media,
1847
+ path: await resolveMediaUri(media.path, api.mediaDir)
1848
+ };
1849
+ }
1850
+ return el;
1851
+ }
1852
+ /** 远程媒体元素(image/voice/video 且 path 为需落盘的 URI)。 */
1853
+ function isRemoteMediaUri(el) {
1854
+ return (el.type === "image" || el.type === "voice" || el.type === "video") && (el.path.startsWith("http://") || el.path.startsWith("https://") || el.path.startsWith("base64://"));
1855
+ }
1829
1856
  // src/milky/action/profile.ts
1830
1857
  /**
1831
1858
  * Milky 资料类动作(P1):get_user_profile / get_friend_info / set_avatar /