@napuketto/adapter 0.15.2 → 0.15.4

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.
@@ -1,8 +1,8 @@
1
- import { C as runAction, S as ActionRegistry, b as BaseProtocolAdapter, c as narrowSysMsgBlobs, d as recognizeSysMsg, f as textOf, h as varintOf, l as nodeAt, m as varintAt, u as processSysMsgBlob } from "../core-CxDffqmA.mjs";
1
+ import { C as runAction, S as ActionRegistry, b as BaseProtocolAdapter, c as narrowSysMsgBlobs, d as recognizeSysMsg, f as textOf, h as varintOf, l as nodeAt, m as varintAt, u as processSysMsgBlob } from "../core-DOyFBFOW.mjs";
2
2
  import { t as findFirstMatch } from "../lookup-Dw0W04Ng.mjs";
3
3
  import { a as MS_TO_SEC$2, c as toUin, i as hasGrayTip, n as findRevokeElement, o as numericUin, r as firstUntranslatedGrayTip, s as resolveUin, t as collectGrayTipUids } from "../gray-tip-C0pnbB__.mjs";
4
4
  import { r as subscribeRawMessages, t as forEachRawMessage } from "../raw-message-D2vA27kj.mjs";
5
- import { a as narrowEssenceGroupArg, i as extractEssenceSetSysMsg, o as narrowBuddyReqs, r as EssenceListSync, t as sliceRaw } from "../log-DiPRjA5P.mjs";
5
+ import { a as narrowEssenceGroupArg, i as extractEssenceSetSysMsg, o as narrowBuddyReqs, r as EssenceListSync, t as sliceRaw } from "../log-DYEB3Eto.mjs";
6
6
  import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, kernelError, toCanonicalElements } from "@napuketto/kernel";
7
7
  import { mkdir, rename, writeFile } from "node:fs/promises";
8
8
  import { join } from "node:path";
@@ -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);
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
52
+ };
64
53
  }
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");
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;
76
65
  }
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 {}
66
+ };
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();
70
+ /**
71
+ * get_group_essence_messages:获取精华消息列表。
72
+ * WebApi.getEssenceMsgList 全量拉取后按 page_index/page_size 客户端分页
73
+ * (kernel 无分页参数);message_time 无源取 operation_time 兜底。
74
+ */
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);
91
86
  return {
92
- chatType: scene === "friend" ? ChatType.C2C : ChatType.C2C_TEMP,
93
- peerUid: uid ?? uin
87
+ messages: page.map((item) => essenceToEntity(item, payload.group_id)),
88
+ is_end: start + page.length >= items.length
94
89
  };
95
90
  }
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;
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
105
+ };
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 {};
107
111
  }
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)
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)
116
127
  };
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 {};
117
135
  }
118
136
  };
119
- /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
120
- const NOTIFY_SEARCH_COUNT$1 = 100;
121
- /**
122
- * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
123
- * 屏序骨架走 core findFirstMatch)。
124
- * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
125
- * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
126
- */
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",
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",
146
147
  data: {
147
- initiator_id: toUin(req.friendUid, ctx),
148
- initiator_uid: req.friendUid,
149
- comment: typeof words === "string" ? words : "",
150
- via: req.sourceName ?? ""
148
+ resource_id: c.image_url,
149
+ temp_url: c.image_url,
150
+ width: 0,
151
+ height: 0,
152
+ summary: "",
153
+ sub_type: "normal"
151
154
  }
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
- }
173
- };
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
- }
184
- };
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
- }
195
- };
196
- default: return null;
197
- }
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) {
155
+ });
257
156
  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: ""
266
- }
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
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
245
+ };
246
+ }
334
247
  };
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("; ");
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
+ };
341
355
  }
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
362
- };
363
- }
364
- };
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,92 +503,301 @@ 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);
496
512
  await this.api.groupApi.kickMember(String(payload.group_id), [uid], payload.reject_add_request === true);
497
513
  return {};
498
514
  }
499
- };
500
- /** quit_group:退出群聊。 */
501
- var QuitGroupAction = class extends MilkyApiAction {
502
- name = "quit_group";
503
- schema = z.object({ ...groupIdField$1 });
504
- async _handle(payload) {
505
- await this.api.groupApi.quitGroup(String(payload.group_id));
506
- return {};
515
+ };
516
+ /** quit_group:退出群聊。 */
517
+ var QuitGroupAction = class extends MilkyApiAction {
518
+ name = "quit_group";
519
+ schema = z.object({ ...groupIdField$2 });
520
+ async _handle(payload) {
521
+ await this.api.groupApi.quitGroup(String(payload.group_id));
522
+ return {};
523
+ }
524
+ };
525
+ /** set_group_avatar:设置群头像(image_uri → 本地路径)。 */
526
+ var SetGroupAvatarAction = class extends MilkyApiAction {
527
+ name = "set_group_avatar";
528
+ schema = z.object({
529
+ ...groupIdField$2,
530
+ image_uri: z.string().min(1)
531
+ });
532
+ async _handle(payload) {
533
+ const imagePath = await resolveUriToPath(payload.image_uri, this.api.mediaDir);
534
+ await this.api.groupApi.setGroupAvatar(String(payload.group_id), imagePath);
535
+ return {};
536
+ }
537
+ };
538
+ /** set_group_member_special_title:设置专属头衔(uin → uid)。 */
539
+ var SetGroupMemberSpecialTitleAction = class extends MilkyApiAction {
540
+ name = "set_group_member_special_title";
541
+ schema = z.object({
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
559
+ });
560
+ async _handle(payload) {
561
+ const groupCode = String(payload.group_id);
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
+ let cause;
645
+ try {
646
+ const uid = (await this.uinToUid([uinStr])).get(uinStr);
647
+ if (uid !== void 0 && uid !== "") return uid;
648
+ } catch (err) {
649
+ cause = err;
650
+ }
651
+ throw kernelError(`用户 ${uinStr} 不存在或 uin→uid 转换失败`, "INVALID_PARAM", cause === void 0 ? void 0 : { cause });
652
+ }
653
+ /**
654
+ * message_scene + 数字 ID → NT Peer。
655
+ * group = 群号直作 peerUid;friend/temp = uin → uid(失败退 uin 原样,交 QQ 端判断)。
656
+ */
657
+ async resolvePeer(scene, id) {
658
+ if (scene === "group") return {
659
+ chatType: ChatType.GROUP,
660
+ peerUid: String(id)
661
+ };
662
+ const uin = String(id);
663
+ let uid;
664
+ try {
665
+ uid = (await this.uinToUid([uin])).get(uin);
666
+ } catch (err) {
667
+ this.logger?.warn({
668
+ uin,
669
+ error: err instanceof Error ? err.message : String(err)
670
+ }, "milky: uin→uid 转换失败,peer 退用 uin 原样");
671
+ }
672
+ return {
673
+ chatType: scene === "friend" ? ChatType.C2C : ChatType.C2C_TEMP,
674
+ peerUid: uid ?? uin
675
+ };
676
+ }
677
+ /**
678
+ * seq → msgId(索引优先,未登记扫描近段历史兜底)。
679
+ * 两层都未命中返回 undefined(调用方抛 NOT_FOUND)。
680
+ */
681
+ async resolveMsgIdBySeq(peer, seq, chatType) {
682
+ const indexed = this.seqIndex.resolveMsgId(chatType, peer.peerUid, seq);
683
+ if (indexed !== void 0) return indexed;
684
+ const hit = (await this.msgApi.fetchMessages(peer, { count: 60 }).catch((err) => {
685
+ this.logger?.debug({
686
+ peer: peer.peerUid,
687
+ seq,
688
+ error: err instanceof Error ? err.message : String(err)
689
+ }, "milky: msgSeq 反查近段历史失败");
690
+ return [];
691
+ })).find((m) => Number(m.msgSeq) === seq);
692
+ if (hit === void 0) return;
693
+ this.seqIndex.record(hit);
694
+ return hit.msgId;
507
695
  }
508
- };
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";
516
- schema = z.object({
517
- ...groupIdField$1,
518
- page_index: z.number().int().min(0),
519
- page_size: z.number().int().min(0)
520
- });
521
- 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);
696
+ /** 发送结果回查:msgId → {message_seq, time}(sendMessage 只回 msgId)。 */
697
+ async resolveSentOutput(peer, msgId) {
698
+ const [sent] = await this.msgApi.fetchMsgsByMsgId(peer, [msgId]);
699
+ if (sent === void 0) throw kernelError("发送结果回查失败(msgId 未命中)", "UNKNOWN");
700
+ this.seqIndex.record(sent);
525
701
  return {
526
- messages: page.map((item) => essenceToEntity(item, payload.group_id)),
527
- is_end: start + page.length >= items.length
702
+ message_seq: Number(sent.msgSeq),
703
+ time: Math.floor(Number(sent.msgTime) / 1e3)
528
704
  };
529
705
  }
530
706
  };
531
- /** set_group_essence_message:设置/取消精华(seq → msgId 反查)。 */
532
- var SetGroupEssenceMessageAction = class extends MilkyApiAction {
533
- name = "set_group_essence_message";
534
- schema = z.object({
535
- ...groupIdField$1,
536
- message_seq: z.number().int().min(0),
537
- is_set: optBool
538
- });
539
- async _handle(payload) {
540
- const groupCode = String(payload.group_id);
541
- const peer = {
542
- chatType: ChatType.GROUP,
543
- peerUid: groupCode
707
+ /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
708
+ const NOTIFY_SEARCH_COUNT$1 = 100;
709
+ /**
710
+ * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
711
+ * 屏序骨架走 core findFirstMatch)。
712
+ * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
713
+ * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
714
+ */
715
+ async function findGroupNotify(api, seq) {
716
+ const hit = await findFirstMatch([() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)], (item) => item.seq === seq);
717
+ if (hit === void 0) throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
718
+ return hit;
719
+ }
720
+ /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
721
+ async function findBuddyReq(api, initiatorUid) {
722
+ const hit = await findFirstMatch([() => api.friendApi.getBuddyReqList()], (req) => req.friendUid === initiatorUid);
723
+ if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
724
+ return hit;
725
+ }
726
+ // src/milky/helper/event/request.ts
727
+ /** BuddyReq → friend_request 事件(comment 取 words 字段,形状待校准,缺省空串)。 */
728
+ function toFriendRequestEvent(req, ctx) {
729
+ const words = req["words"];
730
+ return {
731
+ time: Math.floor(Date.now() / MS_TO_SEC$2),
732
+ self_id: Number(ctx.selfUin),
733
+ event_type: "friend_request",
734
+ data: {
735
+ initiator_id: toUin(req.friendUid, ctx),
736
+ initiator_uid: req.friendUid,
737
+ comment: typeof words === "string" ? words : "",
738
+ via: req.sourceName ?? ""
739
+ }
740
+ };
741
+ }
742
+ /** GroupNotify → Milky 群请求事件(非未处理状态 / 非请求类返回 null)。 */
743
+ function toGroupRequestEvent(notify, doubt, ctx) {
744
+ if (notify.status !== GroupNotifyMsgStatus.KUNHANDLE) return null;
745
+ const groupId = Number(notify.group?.groupCode ?? 0);
746
+ const seq = Number(notify.seq);
747
+ const time = Math.floor(Date.now() / MS_TO_SEC$2);
748
+ const selfId = Number(ctx.selfUin);
749
+ switch (notify.type) {
750
+ case GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS: return {
751
+ time,
752
+ self_id: selfId,
753
+ event_type: "group_join_request",
754
+ data: {
755
+ group_id: groupId,
756
+ notification_seq: seq,
757
+ is_filtered: doubt,
758
+ initiator_id: toUin(notify.user1?.uid, ctx),
759
+ comment: notify.postscript ?? ""
760
+ }
544
761
  };
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
- }
551
- };
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)
762
+ case GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS: return {
763
+ time,
764
+ self_id: selfId,
765
+ event_type: "group_invited_join_request",
766
+ data: {
767
+ group_id: groupId,
768
+ notification_seq: seq,
769
+ initiator_id: toUin(notify.user1?.uid, ctx),
770
+ target_user_id: toUin(notify.user2?.uid, ctx)
771
+ }
566
772
  };
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 {};
773
+ case GroupNotifyMsgType.INVITED_BY_MEMBER: return {
774
+ time,
775
+ self_id: selfId,
776
+ event_type: "group_invitation",
777
+ data: {
778
+ group_id: groupId,
779
+ invitation_seq: seq,
780
+ initiator_id: toUin(notify.user1?.uid, ctx),
781
+ source_group_id: null
782
+ }
783
+ };
784
+ default: return null;
574
785
  }
575
- };
786
+ }
787
+ /**
788
+ * 群通知涉及的 uid 集合(去重;get_group_notifications 与事件广播共用)。
789
+ * kernel GroupEventChannel 的 onGroupNotifiesUpdated 回调参数已类型化
790
+ * (GroupNotify[]),无需防御收窄。
791
+ */
792
+ function collectNotifyUids(notifies) {
793
+ const uids = /* @__PURE__ */ new Set();
794
+ for (const n of notifies) for (const uid of [n.user1?.uid, n.user2?.uid]) if (uid !== void 0 && uid !== "") uids.add(uid);
795
+ return [...uids];
796
+ }
797
+ // src/milky/action/group-notice.ts
798
+ const groupIdField$1 = { group_id: z.number().int().min(10001) };
799
+ const optBool$1 = z.boolean().nullable().optional();
800
+ const optStr = z.string().nullable().optional();
576
801
  /**
577
802
  * get_group_notifications:获取群通知列表。
578
803
  * kernel getSingleScreenNotifies 为单屏快照(无翻页)——start_notification_seq
@@ -582,7 +807,7 @@ var GetGroupNotificationsAction = class extends MilkyApiAction {
582
807
  name = "get_group_notifications";
583
808
  schema = z.object({
584
809
  start_notification_seq: z.number().int().min(0).nullable().optional(),
585
- is_filtered: optBool,
810
+ is_filtered: optBool$1,
586
811
  limit: z.number().int().min(0).nullable().optional()
587
812
  });
588
813
  async _handle(payload) {
@@ -603,7 +828,13 @@ var GetGroupNotificationsAction = class extends MilkyApiAction {
603
828
  async collectUidToUin(notifies) {
604
829
  const uids = collectNotifyUids(notifies);
605
830
  if (uids.length === 0) return /* @__PURE__ */ new Map();
606
- return await this.api.uidToUin(uids).catch(() => /* @__PURE__ */ new Map());
831
+ return await this.api.uidToUin(uids).catch((err) => {
832
+ this.api.logger?.warn({
833
+ count: uids.length,
834
+ error: err instanceof Error ? err.message : String(err)
835
+ }, "milky: 通知 uid→uin 失败,实体 id 兜底 0");
836
+ return /* @__PURE__ */ new Map();
837
+ });
607
838
  }
608
839
  };
609
840
  /** accept/reject 群请求 / 群邀请公共基类:seq → 通知匹配 → handleGroupRequest。 */
@@ -621,7 +852,7 @@ var AcceptGroupRequestAction = class extends HandleGroupNotifyBase {
621
852
  notification_seq: z.number().int().min(0),
622
853
  notification_type: z.enum(["join_request", "invited_join_request"]),
623
854
  ...groupIdField$1,
624
- is_filtered: optBool
855
+ is_filtered: optBool$1
625
856
  });
626
857
  approve = true;
627
858
  async _handle(payload) {
@@ -635,8 +866,8 @@ var RejectGroupRequestAction = class extends HandleGroupNotifyBase {
635
866
  notification_seq: z.number().int().min(0),
636
867
  notification_type: z.enum(["join_request", "invited_join_request"]),
637
868
  ...groupIdField$1,
638
- is_filtered: optBool,
639
- reason: optStr$1
869
+ is_filtered: optBool$1,
870
+ reason: optStr
640
871
  });
641
872
  approve = false;
642
873
  async _handle(payload) {
@@ -654,99 +885,17 @@ var AcceptGroupInvitationAction = class extends HandleGroupNotifyBase {
654
885
  async _handle(payload) {
655
886
  return await this.respond(payload.invitation_seq, false);
656
887
  }
657
- };
658
- /** 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";
888
+ };
889
+ /** reject_group_invitation:拒绝入群邀请。 */
890
+ var RejectGroupInvitationAction = class extends HandleGroupNotifyBase {
891
+ name = "reject_group_invitation";
741
892
  schema = z.object({
742
893
  ...groupIdField$1,
743
- ...userIdField,
744
- special_title: z.string()
894
+ invitation_seq: z.number().int().min(0)
745
895
  });
896
+ approve = false;
746
897
  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 {};
898
+ return await this.respond(payload.invitation_seq, false);
750
899
  }
751
900
  };
752
901
  /** ---------- 内部辅助 ---------- */
@@ -754,58 +903,6 @@ var SetGroupMemberSpecialTitleAction = class extends MilkyApiAction {
754
903
  const NOTIFY_SEARCH_COUNT = 100;
755
904
  /** get_group_notifications 默认 limit(规范 default 20)。 */
756
905
  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
- }
796
- });
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
- }
809
906
  /**
810
907
  * GroupNotify → GroupNotificationEntity(uidToUin 已由调用方批量转换)。
811
908
  * 类型→构造器表:7=入群申请 / 5=成员邀请他人 / 8=设管理 / 12,13=取消管理 /
@@ -873,213 +970,170 @@ function notifyToEntity(notify, isFiltered, uidToUin) {
873
970
  if (entity.type === "join_request") entity.is_filtered = isFiltered;
874
971
  return entity;
875
972
  }
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) {
973
+ // src/milky/helper/message/entities.ts
974
+ /** GroupDetailInfo / Group → GroupEntity(detail 缺失时全兜底)。 */
975
+ function toGroupEntity(detail, groupCode) {
884
976
  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)
977
+ group_id: Number(groupCode),
978
+ group_name: detail?.groupName ?? "",
979
+ member_count: detail?.memberNum ?? 0,
980
+ max_member_count: detail?.maxMemberNum ?? 0,
981
+ remark: detail?.remarkName ?? "",
982
+ created_time: detail?.groupCreateTime ?? 0,
983
+ description: "",
984
+ question: "",
985
+ announcement: ""
891
986
  };
892
987
  }
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) {
988
+ /** 群列表项(GroupCache Group)→ GroupEntity。 */
989
+ function groupListToEntity(group) {
1009
990
  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
991
+ group_id: Number(group.groupCode),
992
+ group_name: group.groupName,
993
+ member_count: group.memberCount,
994
+ max_member_count: group.maxMember,
995
+ remark: "",
996
+ created_time: 0,
997
+ description: "",
998
+ question: "",
999
+ announcement: ""
1019
1000
  };
1020
1001
  }
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;
1002
+ /** GroupMember → GroupMemberEntity(member 缺失时按 uin 兜底最小实体)。 */
1003
+ function toGroupMemberEntity(member, groupCode, uin) {
1004
+ const shutUpSeconds = member?.shutUpTime ?? 0;
1005
+ return {
1006
+ user_id: Number(member?.uin !== void 0 && member.uin !== "" ? member.uin : uin),
1007
+ nickname: member?.nick ?? "",
1008
+ sex: "unknown",
1009
+ group_id: Number(groupCode),
1010
+ card: member?.cardName ?? "",
1011
+ title: member?.memberSpecialTitle ?? "",
1012
+ level: 0,
1013
+ role: GroupApi.roleToString(member?.role ?? 2),
1014
+ join_time: Number(member?.joinTime) || 0,
1015
+ last_sent_time: Number(member?.lastSpeakTime) || 0,
1016
+ shut_up_end_time: shutUpSeconds > 0 ? Math.floor(Date.now() / 1e3) + shutUpSeconds : null
1026
1017
  };
1018
+ }
1019
+ /** Friend → FriendEntity(kernel 无 qid/分类挂载,按最小实体兜底)。 */
1020
+ function toFriendEntity(friend, uin, nick) {
1027
1021
  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")
1022
+ user_id: Number(friend?.uin !== void 0 && friend.uin !== "" ? friend.uin : uin),
1023
+ nickname: friend?.nickname ?? nick,
1024
+ sex: "unknown",
1025
+ qid: "",
1026
+ remark: friend?.remark ?? "",
1027
+ category: {
1028
+ category_id: 0,
1029
+ category_name: ""
1030
+ }
1036
1031
  };
1037
1032
  }
1038
- /**
1039
- * upload_group_file:上传并投递文件(**闪传通道**:分享链接卡片,见文件头语义说明)。
1040
- * file_id 返回闪传文件集 id(非群文件 fileId)。
1041
- */
1042
- var UploadGroupFileAction = class extends MilkyApiAction {
1043
- name = "upload_group_file";
1033
+ // src/milky/action/group-query.ts
1034
+ const groupIdField = { group_id: z.number().int().min(10001) };
1035
+ const userIdField = { user_id: z.number().int().min(10001) };
1036
+ const optBool = z.boolean().nullable().optional();
1037
+ /** get_group_info:获取群信息(GroupCache 详情缓存优先)。 */
1038
+ var GetGroupInfoAction = class extends MilkyApiAction {
1039
+ name = "get_group_info";
1044
1040
  schema = z.object({
1045
1041
  ...groupIdField,
1046
- parent_folder_id: optStr,
1047
- file_uri: z.string().min(1),
1048
- file_name: z.string().min(1)
1042
+ no_cache: optBool
1049
1043
  });
1050
1044
  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 };
1045
+ const groupCode = String(payload.group_id);
1046
+ return { group: toGroupEntity(this.api.groupCache !== void 0 ? await this.api.groupCache.getGroupDetail(groupCode) : await this.api.groupApi.getGroupInfo(groupCode), groupCode) };
1057
1047
  }
1058
1048
  };
1059
- /** get_group_file_download_url:群文件下载链接(url 字段待实机确认,仅根目录)。 */
1060
- var GetGroupFileDownloadUrlAction = class extends MilkyApiAction {
1061
- name = "get_group_file_download_url";
1049
+ /** get_group_member_list:获取群成员列表(GroupCache 惰性回填)。 */
1050
+ var GetGroupMemberListAction = class extends MilkyApiAction {
1051
+ name = "get_group_member_list";
1062
1052
  schema = z.object({
1063
1053
  ...groupIdField,
1064
- ...fileIdField
1054
+ no_cache: optBool
1065
1055
  });
1066
1056
  async _handle(payload) {
1067
- return { download_url: await this.api.richMediaApi.getGroupFileDownloadUrl(String(payload.group_id), payload.file_id) };
1057
+ return { members: (await membersOf(this.api, String(payload.group_id))).map((m) => toGroupMemberEntity(m, String(payload.group_id), m.uin)) };
1068
1058
  }
1069
1059
  };
1070
- /** rename_group_folder:重命名群文件夹(renameGroupFile 同款形态,待校准)。 */
1071
- var RenameGroupFolderAction = class extends MilkyApiAction {
1072
- name = "rename_group_folder";
1060
+ /** get_group_member_info:获取群成员信息(user_id = uin → 成员单查)。 */
1061
+ var GetGroupMemberInfoAction = class extends MilkyApiAction {
1062
+ name = "get_group_member_info";
1073
1063
  schema = z.object({
1074
1064
  ...groupIdField,
1075
- folder_id: z.string().min(1),
1076
- new_folder_name: z.string().min(1)
1065
+ ...userIdField,
1066
+ no_cache: optBool
1077
1067
  });
1078
1068
  async _handle(payload) {
1079
- await this.api.richMediaApi.renameGroupFolder(String(payload.group_id), payload.folder_id, payload.new_folder_name);
1080
- return {};
1069
+ return { member: toGroupMemberEntity(await memberOf(this.api, payload.group_id, payload.user_id), String(payload.group_id), String(payload.user_id)) };
1070
+ }
1071
+ };
1072
+ /** get_group_announcements:获取群公告列表(bulletin 形状待校准,宽松映射)。 */
1073
+ var GetGroupAnnouncementsAction = class extends MilkyApiAction {
1074
+ name = "get_group_announcements";
1075
+ schema = z.object({ ...groupIdField });
1076
+ async _handle(payload) {
1077
+ const groupCode = String(payload.group_id);
1078
+ const bulletins = await this.api.groupApi.getGroupAnnouncements(groupCode);
1079
+ return { announcements: await Promise.all(bulletins.map((b) => bulletinToEntity(b, payload.group_id, this.api))) };
1081
1080
  }
1082
1081
  };
1082
+ /** ---------- 内部辅助 ---------- */
1083
+ /** 成员列表(GroupCache 优先,未装配直查)。 */
1084
+ async function membersOf(api, groupCode) {
1085
+ if (api.groupCache !== void 0) return await api.groupCache.getMembers(groupCode);
1086
+ return await api.groupApi.getGroupMemberList(groupCode, true);
1087
+ }
1088
+ /** 成员单查(user_id = uin;缓存路径经 uid,直查路径按 uin 匹配)。 */
1089
+ async function memberOf(api, groupId, userId) {
1090
+ const groupCode = String(groupId);
1091
+ const uin = String(userId);
1092
+ if (api.groupCache !== void 0) {
1093
+ const uid = await api.resolveUidFromUin(userId).catch((err) => {
1094
+ api.logger?.debug({
1095
+ group: groupCode,
1096
+ uin,
1097
+ error: err instanceof Error ? err.message : String(err)
1098
+ }, "milky: 成员 uin→uid 失败,退用 uin 查缓存");
1099
+ return uin;
1100
+ });
1101
+ const member = await api.groupCache.getMember(groupCode, uid);
1102
+ if (member === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
1103
+ return member;
1104
+ }
1105
+ const hit = (await api.groupApi.getGroupMemberList(groupCode, true)).find((m) => m.uin === uin);
1106
+ if (hit === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
1107
+ return hit;
1108
+ }
1109
+ /** GroupBulletin → 群公告实体(senderUid → uin 反查;无源字段兜底,待校准)。 */
1110
+ async function bulletinToEntity(b, groupId, api) {
1111
+ return {
1112
+ group_id: groupId,
1113
+ announcement_id: b.announcementId ?? "",
1114
+ user_id: await senderUinOf(b, api),
1115
+ time: Number(b.publishTime) || 0,
1116
+ content: b.content ?? "",
1117
+ image_url: picUrlOf(b)
1118
+ };
1119
+ }
1120
+ /** 公告发送者 uid → uin(缺省/转换失败 0 兜底)。 */
1121
+ async function senderUinOf(b, api) {
1122
+ const uid = b.senderUid;
1123
+ if (typeof uid !== "string" || uid === "") return 0;
1124
+ const uins = await api.uidToUin([uid]).catch((err) => {
1125
+ api.logger?.debug({
1126
+ uid,
1127
+ error: err instanceof Error ? err.message : String(err)
1128
+ }, "milky: 公告发送者 uid→uin 失败,兜底 0");
1129
+ });
1130
+ return Number(uins?.get(uid)) || 0;
1131
+ }
1132
+ /** 公告图片 url(缺省 null)。 */
1133
+ function picUrlOf(b) {
1134
+ const url = b.pic?.url;
1135
+ return typeof url === "string" && url !== "" ? url : null;
1136
+ }
1083
1137
  // src/milky/helper/message/segments.ts
1084
1138
  /**
1085
1139
  * Milky 消息段 ↔ canonical 元素转换(纯函数,ADR-008)
@@ -1464,190 +1518,53 @@ function toGroupFileUploadEvent(msg, selfUin) {
1464
1518
  }
1465
1519
  };
1466
1520
  }
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;
1521
+ // src/milky/action/message-query.ts
1522
+ /** get_message / mark_message_as_read 共入参(场景 + 对端 + seq)。 */
1523
+ const peerMessageFields = {
1524
+ message_scene: z.enum([
1525
+ "friend",
1526
+ "group",
1527
+ "temp"
1528
+ ]),
1529
+ peer_id: z.number().int().min(10001),
1530
+ message_seq: z.number().int().min(0)
1531
+ };
1532
+ /** get_message:获取单条消息(seq → msgId 反查 + 实体回填)。 */
1533
+ var GetMessageAction = class extends MilkyApiAction {
1534
+ name = "get_message";
1535
+ schema = z.object({ ...peerMessageFields });
1536
+ async _handle(payload) {
1537
+ const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1538
+ const msgId = await this.api.resolveMsgIdBySeq(peer, payload.message_seq, peer.chatType);
1539
+ if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1540
+ const [msg] = await this.api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
1541
+ if (msg === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1542
+ return { message: await this.translateWithEntities(payload.message_scene, peer, msg) };
1630
1543
  }
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
1637
- };
1638
- if (isRemoteMediaUri(el)) {
1639
- const media = el;
1640
- return {
1641
- ...media,
1642
- path: await resolveMediaUri(media.path, api.mediaDir)
1643
- };
1544
+ /** 实体回填(group 场景 schema 要求完整实体)→ IncomingMessage。 */
1545
+ async translateWithEntities(scene, peer, msg) {
1546
+ const ctx = { selfUin: this.api.self.uin };
1547
+ if (scene === "group") {
1548
+ const [detail, member] = await Promise.all([this.api.groupCache?.getGroupDetail(peer.peerUid).catch((err) => {
1549
+ this.api.logger?.warn({
1550
+ group: peer.peerUid,
1551
+ error: err instanceof Error ? err.message : String(err)
1552
+ }, "milky: 群详情缓存读取失败,实体回填退化");
1553
+ }), this.api.groupCache?.getMember(peer.peerUid, msg.senderUid).catch((err) => {
1554
+ this.api.logger?.debug({
1555
+ group: peer.peerUid,
1556
+ member: msg.senderUid,
1557
+ error: err instanceof Error ? err.message : String(err)
1558
+ }, "milky: 群成员缓存读取失败,实体回填退化");
1559
+ })]);
1560
+ ctx.groupEntity = toGroupEntity(detail, peer.peerUid);
1561
+ ctx.groupMemberEntity = toGroupMemberEntity(member, peer.peerUid, msg.senderUin);
1562
+ }
1563
+ return toMessageReceiveEvent(msg, ctx).data;
1644
1564
  }
1645
- return el;
1646
- }
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://"));
1650
- }
1565
+ };
1566
+ /** 历史消息默认条数(规范 default 20)。 */
1567
+ const HISTORY_DEFAULT_LIMIT = 20;
1651
1568
  /** get_history_messages:获取历史消息(start seq 锚点 → 原生翻页 → 升序输出)。 */
1652
1569
  var GetHistoryMessagesAction = class extends MilkyApiAction {
1653
1570
  name = "get_history_messages";
@@ -1693,7 +1610,18 @@ var GetHistoryMessagesAction = class extends MilkyApiAction {
1693
1610
  detail: void 0,
1694
1611
  members: /* @__PURE__ */ new Map()
1695
1612
  };
1696
- const [detail, members] = await Promise.all([this.api.groupCache.getGroupDetail(groupCode).catch(() => void 0), this.api.groupCache.getMembers(groupCode).catch(() => [])]);
1613
+ const [detail, members] = await Promise.all([this.api.groupCache.getGroupDetail(groupCode).catch((err) => {
1614
+ this.api.logger?.warn({
1615
+ group: groupCode,
1616
+ error: err instanceof Error ? err.message : String(err)
1617
+ }, "milky: 群详情缓存读取失败,历史翻译退化");
1618
+ }), this.api.groupCache.getMembers(groupCode).catch((err) => {
1619
+ this.api.logger?.warn({
1620
+ group: groupCode,
1621
+ error: err instanceof Error ? err.message : String(err)
1622
+ }, "milky: 群成员表缓存读取失败,历史翻译退化");
1623
+ return [];
1624
+ })]);
1697
1625
  const memberByUid = /* @__PURE__ */ new Map();
1698
1626
  for (const m of members) memberByUid.set(m.uid, m);
1699
1627
  return {
@@ -1741,40 +1669,31 @@ var GetForwardedMessagesAction = class extends MilkyApiAction {
1741
1669
  const uids = /* @__PURE__ */ new Set();
1742
1670
  for (const m of msgs) for (const el of toCanonicalElements(m)) if (el.type === "at" && el.target !== "all") uids.add(el.target);
1743
1671
  if (uids.size === 0) return /* @__PURE__ */ new Map();
1744
- return await this.api.uidToUin([...uids]).catch(() => /* @__PURE__ */ new Map());
1672
+ return await this.api.uidToUin([...uids]).catch((err) => {
1673
+ this.api.logger?.warn({
1674
+ count: uids.size,
1675
+ error: err instanceof Error ? err.message : String(err)
1676
+ }, "milky: 历史 at uid→uin 失败,mention 段跳过");
1677
+ return /* @__PURE__ */ new Map();
1678
+ });
1745
1679
  }
1746
1680
  /** 发送者名(群场景成员缓存昵称/名片,失败退 uin 字符串)。 */
1747
1681
  async senderNameOf(msg) {
1748
1682
  if (this.api.groupCache !== void 0 && msg.chatType === ChatType.GROUP) {
1749
- const member = await this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch(() => void 0);
1683
+ const member = await this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch((err) => {
1684
+ this.api.logger?.debug({
1685
+ group: msg.peerUid,
1686
+ member: msg.senderUid,
1687
+ error: err instanceof Error ? err.message : String(err)
1688
+ }, "milky: 发送者成员缓存读取失败,退 uin 字符串");
1689
+ });
1750
1690
  const name = member?.cardName !== void 0 && member.cardName !== "" ? member.cardName : member?.nick;
1751
1691
  if (name !== void 0 && name !== "") return name;
1752
1692
  }
1753
1693
  return msg.senderUin;
1754
1694
  }
1755
1695
  };
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
- };
1696
+ /** ---------- 内部辅助 ---------- */
1778
1697
  /** 单条消息 → 接收段(canonical 映射 + forward 段注入,forward 不经 canonical)。 */
1779
1698
  function receiveSegmentsOf(msg, uidToUin) {
1780
1699
  const segments = canonicalToIncomingSegments(toCanonicalElements(msg), { ...uidToUin.size > 0 ? { uidToUin } : {} });
@@ -1786,6 +1705,48 @@ function receiveSegmentsOf(msg, uidToUin) {
1786
1705
  function avatarUrlOf(uin) {
1787
1706
  return uin === "" ? "" : `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=640`;
1788
1707
  }
1708
+ // src/milky/action/message-ops.ts
1709
+ const recallFields = { message_seq: z.number().int().min(0) };
1710
+ /** recall_private_message:撤回私聊消息。 */
1711
+ var RecallPrivateMessageAction = class extends MilkyApiAction {
1712
+ name = "recall_private_message";
1713
+ schema = z.object({
1714
+ user_id: z.number().int().min(10001),
1715
+ ...recallFields
1716
+ });
1717
+ async _handle(payload) {
1718
+ await recallBySeq(await this.api.resolvePeer("friend", payload.user_id), payload.message_seq, this.api);
1719
+ return {};
1720
+ }
1721
+ };
1722
+ /** recall_group_message:撤回群消息。 */
1723
+ var RecallGroupMessageAction = class extends MilkyApiAction {
1724
+ name = "recall_group_message";
1725
+ schema = z.object({
1726
+ group_id: z.number().int().min(10001),
1727
+ ...recallFields
1728
+ });
1729
+ async _handle(payload) {
1730
+ await recallBySeq(await this.api.resolvePeer("group", payload.group_id), payload.message_seq, this.api);
1731
+ return {};
1732
+ }
1733
+ };
1734
+ /** seq → msgId(反查)→ recallMessage。 */
1735
+ async function recallBySeq(peer, seq, api) {
1736
+ const msgId = await api.resolveMsgIdBySeq(peer, seq, peer.chatType);
1737
+ if (msgId === void 0) throw kernelError(`消息 ${seq} 不存在`, "NOT_FOUND");
1738
+ await api.msgApi.recallMessage(peer, [msgId]);
1739
+ }
1740
+ /** mark_message_as_read:标记会话已读(NT setMsgRead 以会话为粒度,seq 入参仅兼容 schema)。 */
1741
+ var MarkMessageAsReadAction = class extends MilkyApiAction {
1742
+ name = "mark_message_as_read";
1743
+ schema = z.object({ ...peerMessageFields });
1744
+ async _handle(payload) {
1745
+ const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1746
+ await this.api.msgApi.markRead(peer);
1747
+ return {};
1748
+ }
1749
+ };
1789
1750
  /** get_custom_face_url_list:收藏表情链接(queryFavEmojiByDesc 形状待校准)。 */
1790
1751
  var GetCustomFaceUrlListAction = class extends MilkyApiAction {
1791
1752
  name = "get_custom_face_url_list";
@@ -1826,6 +1787,143 @@ var UploadPrivateFileAction = class extends MilkyApiAction {
1826
1787
  return { file_id: (await this.api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1827
1788
  }
1828
1789
  };
1790
+ // src/milky/action/message-send.ts
1791
+ /**
1792
+ * OutgoingSegment 宽松校验:入口只保证「{type, data}」形状,字段级转换在
1793
+ * outgoingSegmentsToCanonical 内做(未知段跳过 = 规范兼容性要求)。
1794
+ */
1795
+ const outgoingSegmentSchema = z.object({
1796
+ type: z.string(),
1797
+ data: z.record(z.string(), z.unknown())
1798
+ }).loose();
1799
+ const sendMessageFields = { message: z.array(outgoingSegmentSchema).min(1).max(200) };
1800
+ /** send_private_message:发送私聊消息。 */
1801
+ var SendPrivateMessageAction = class extends MilkyApiAction {
1802
+ name = "send_private_message";
1803
+ schema = z.object({
1804
+ user_id: z.number().int().min(10001),
1805
+ ...sendMessageFields
1806
+ });
1807
+ async _handle(payload) {
1808
+ return await sendMilkyMessage(await this.api.resolvePeer("friend", payload.user_id), payload.message, this.api);
1809
+ }
1810
+ };
1811
+ /** send_group_message:发送群聊消息。 */
1812
+ var SendGroupMessageAction = class extends MilkyApiAction {
1813
+ name = "send_group_message";
1814
+ schema = z.object({
1815
+ group_id: z.number().int().min(10001),
1816
+ ...sendMessageFields
1817
+ });
1818
+ async _handle(payload) {
1819
+ return await sendMilkyMessage(await this.api.resolvePeer("group", payload.group_id), payload.message, this.api);
1820
+ }
1821
+ };
1822
+ /** ---------- 发送核心与组装链 ---------- */
1823
+ /** 发送核心:segments → canonical(URI/ID 转换)→ sendMessage → 回查输出。
1824
+ * forward 段分流到组装链(P2 批次一,临时消息法)。 */
1825
+ async function sendMilkyMessage(peer, segments, api) {
1826
+ if (segments.some((s) => s.type === "forward")) return await sendForwardComposition(peer, segments, api);
1827
+ const { elements, atUins } = outgoingSegmentsToCanonical(segments);
1828
+ const resolved = await resolveElements(elements, atUins, api);
1829
+ if (resolved.length === 0) throw kernelError("消息内容为空(全部消息段不可用)", "INVALID_PARAM");
1830
+ const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1831
+ return await api.resolveSentOutput(peer, msgId);
1832
+ }
1833
+ /**
1834
+ * forward 段组装链(P2 批次一,milky.md §0.6):仅支持单 forward 单独发。
1835
+ * 临时消息法:逐条发送 messages[i].segments → sendForwardMessage(buildMultiForwardMsg
1836
+ * 以目标 peer 的真实消息组装 → sendMsg)→ best-effort 撤回临时消息 → 回查输出。
1837
+ *
1838
+ * 已知差异(规范语义 vs kernel 出口,待实机联调):节点发送者恒为机器人自己
1839
+ * (user_id / sender_name / time 不参与组装);title / preview / summary / prompt 忽略。
1840
+ */
1841
+ async function sendForwardComposition(peer, segments, api) {
1842
+ if (segments.length !== 1) throw kernelError("forward 段必须单独发送(不支持与其他消息段混发)", "INVALID_PARAM");
1843
+ const [forward] = segments;
1844
+ if (forward === void 0 || forward.type !== "forward") throw kernelError("forward 组装链收到非 forward 段", "UNKNOWN");
1845
+ const messages = narrowForwardMessages(forward);
1846
+ const srcMsgIds = [];
1847
+ for (const [i, item] of messages.entries()) {
1848
+ const { elements, atUins } = outgoingSegmentsToCanonical(item.segments);
1849
+ const resolved = await resolveElements(elements, atUins, api);
1850
+ if (resolved.length === 0) throw kernelError(`forward 第 ${i + 1} 条消息无可用内容段`, "INVALID_PARAM");
1851
+ const { msgId } = await api.msgApi.sendMessage(peer, resolved);
1852
+ srcMsgIds.push(msgId);
1853
+ }
1854
+ const { msgId } = await api.msgApi.sendForwardMessage(peer, peer, srcMsgIds);
1855
+ await recallTempMessages(peer, srcMsgIds, api);
1856
+ return await api.resolveSentOutput(peer, msgId);
1857
+ }
1858
+ /**
1859
+ * forward 段载荷收窄(入口 schema 只保证 data 为 record):messages 非空数组,
1860
+ * 项内 segments 非空数组。user_id / sender_name / time 不参与组装不校验
1861
+ * (丢弃字段不设门槛);title / preview / summary / prompt 忽略。
1862
+ */
1863
+ function narrowForwardMessages(forward) {
1864
+ const raw = forward.data.messages;
1865
+ if (!Array.isArray(raw) || raw.length === 0) throw kernelError("forward 段 messages 必须是非空数组", "INVALID_PARAM");
1866
+ const out = [];
1867
+ for (const item of raw) {
1868
+ if (typeof item !== "object" || item === null) throw kernelError("forward 段 messages 项必须是对象", "INVALID_PARAM");
1869
+ const segments = item.segments;
1870
+ if (!Array.isArray(segments) || segments.length === 0) throw kernelError("forward 段 messages 项的 segments 必须是非空数组", "INVALID_PARAM");
1871
+ out.push(item);
1872
+ }
1873
+ return out;
1874
+ }
1875
+ /** 临时消息清理(best-effort:失败只留可见垃圾,转发已发出——warn 可观测不抛)。 */
1876
+ async function recallTempMessages(peer, msgIds, api) {
1877
+ try {
1878
+ await api.msgApi.recallMessage(peer, msgIds);
1879
+ } catch (e) {
1880
+ api.logger?.warn({
1881
+ peer: peer.peerUid,
1882
+ count: msgIds.length,
1883
+ error: e instanceof Error ? e.message : String(e)
1884
+ }, "milky: forward 临时消息撤回失败(转发已发出)");
1885
+ }
1886
+ }
1887
+ /** ---------- 元素二次解析 ---------- */
1888
+ /** 元素二次解析:at uin→uid + 远程媒体 URI 落盘(reply seq 已在映射层兜底原样)。 */
1889
+ async function resolveElements(elements, atUins, api) {
1890
+ const uinToUid = await resolveAtUins(atUins, api);
1891
+ const out = [];
1892
+ for (const el of elements) out.push(await resolveElement(el, uinToUid, api));
1893
+ return out;
1894
+ }
1895
+ /** at uin→uid 批量转换(失败返回 undefined:at 原样 uin,交 QQ 端判断)。 */
1896
+ async function resolveAtUins(atUins, api) {
1897
+ if (atUins.length === 0) return;
1898
+ try {
1899
+ return await api.uinToUid(atUins);
1900
+ } catch (err) {
1901
+ api.logger?.warn({
1902
+ count: atUins.length,
1903
+ error: err instanceof Error ? err.message : String(err)
1904
+ }, "milky: at uin→uid 失败,at 段原样发送");
1905
+ return;
1906
+ }
1907
+ }
1908
+ /** 单元素解析:at 目标替换 / 远程媒体 URI 落盘 / 其余原样。 */
1909
+ async function resolveElement(el, uinToUid, api) {
1910
+ if (el.type === "at" && el.target !== "all") return {
1911
+ ...el,
1912
+ target: uinToUid?.get(el.target) ?? el.target
1913
+ };
1914
+ if (isRemoteMediaUri(el)) {
1915
+ const media = el;
1916
+ return {
1917
+ ...media,
1918
+ path: await resolveMediaUri(media.path, api.mediaDir)
1919
+ };
1920
+ }
1921
+ return el;
1922
+ }
1923
+ /** 远程媒体元素(image/voice/video 且 path 为需落盘的 URI)。 */
1924
+ function isRemoteMediaUri(el) {
1925
+ return (el.type === "image" || el.type === "voice" || el.type === "video") && (el.path.startsWith("http://") || el.path.startsWith("https://") || el.path.startsWith("base64://"));
1926
+ }
1829
1927
  // src/milky/action/profile.ts
1830
1928
  /**
1831
1929
  * Milky 资料类动作(P1):get_user_profile / get_friend_info / set_avatar /
@@ -1975,7 +2073,13 @@ var GetFriendRequestsAction = class extends MilkyApiAction {
1975
2073
  async _handle(payload) {
1976
2074
  const reqs = await this.api.friendApi.getBuddyReqList();
1977
2075
  let uidToUin = /* @__PURE__ */ new Map();
1978
- if (reqs.length > 0) uidToUin = await this.api.uidToUin(reqs.map((req) => req.friendUid)).catch(() => /* @__PURE__ */ new Map());
2076
+ if (reqs.length > 0) uidToUin = await this.api.uidToUin(reqs.map((req) => req.friendUid)).catch((err) => {
2077
+ this.api.logger?.warn({
2078
+ count: reqs.length,
2079
+ error: err instanceof Error ? err.message : String(err)
2080
+ }, "milky: 好友申请 uid→uin 失败,initiator_id 兜底 0");
2081
+ return /* @__PURE__ */ new Map();
2082
+ });
1979
2083
  const requests = reqs.map((req) => ({
1980
2084
  time: Number(req.reqTime) || 0,
1981
2085
  initiator_id: Number(uidToUin.get(req.friendUid)) || 0,
@@ -2219,7 +2323,12 @@ var MilkyEnrichment = class {
2219
2323
  resolveUidToUin(uids) {
2220
2324
  const unique = [...new Set(uids.filter((uid) => uid !== ""))];
2221
2325
  if (unique.length === 0) return Promise.resolve(void 0);
2222
- return this.api.uidToUin(unique).catch(() => void 0);
2326
+ return this.api.uidToUin(unique).catch((err) => {
2327
+ this.api.logger?.warn({
2328
+ count: unique.length,
2329
+ error: err instanceof Error ? err.message : String(err)
2330
+ }, "milky: uid→uin 批量转换失败,事件退用 uid");
2331
+ });
2223
2332
  }
2224
2333
  /** at uid → uin 批量转换(mention.user_id 用;失败 mention 段跳过)。 */
2225
2334
  async fillMentionUids(elements, ctx) {
@@ -2227,12 +2336,28 @@ var MilkyEnrichment = class {
2227
2336
  if (atUids.length === 0) return;
2228
2337
  try {
2229
2338
  ctx.uidToUin = await this.api.uidToUin(atUids);
2230
- } catch {}
2339
+ } catch (err) {
2340
+ this.api.logger?.warn({
2341
+ count: atUids.length,
2342
+ error: err instanceof Error ? err.message : String(err)
2343
+ }, "milky: at uid→uin 失败,mention 段跳过");
2344
+ }
2231
2345
  }
2232
2346
  /** 群场景实体回填(GroupCache 缓存优先,失败最小实体兜底)。 */
2233
2347
  async fillGroupEntities(msg, ctx) {
2234
2348
  if (msg.chatType !== ChatType.GROUP || this.api.groupCache === void 0) return;
2235
- const [detail, member] = await Promise.all([this.api.groupCache.getGroupDetail(msg.peerUid).catch(() => void 0), this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch(() => void 0)]);
2349
+ const [detail, member] = await Promise.all([this.api.groupCache.getGroupDetail(msg.peerUid).catch((err) => {
2350
+ this.api.logger?.warn({
2351
+ group: msg.peerUid,
2352
+ error: err instanceof Error ? err.message : String(err)
2353
+ }, "milky: 群详情缓存读取失败,实体回填退化");
2354
+ }), this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch((err) => {
2355
+ this.api.logger?.debug({
2356
+ group: msg.peerUid,
2357
+ member: msg.senderUid,
2358
+ error: err instanceof Error ? err.message : String(err)
2359
+ }, "milky: 群成员缓存读取失败,实体回填退化");
2360
+ })]);
2236
2361
  ctx.groupEntity = toGroupEntity(detail, msg.peerUid);
2237
2362
  ctx.groupMemberEntity = toGroupMemberEntity(member, msg.peerUid, msg.senderUin);
2238
2363
  }
@@ -3078,7 +3203,7 @@ function assembleMilkyTransports(opts) {
3078
3203
  const { config, broadcaster, registry, logger } = opts;
3079
3204
  const hub = new MilkyEventHub();
3080
3205
  const token = config.token;
3081
- const authorize = token !== "" ? makeMilkyAuthorize(token) : void 0;
3206
+ const authorize = token !== "" ? makeMilkyAuthorize(token, logger) : void 0;
3082
3207
  const server = new HttpServer({
3083
3208
  host: config.host,
3084
3209
  port: config.port,
@@ -3086,7 +3211,7 @@ function assembleMilkyTransports(opts) {
3086
3211
  });
3087
3212
  hub.attachTo(server, config);
3088
3213
  server.onPathRequest = (ctx, req, respond) => {
3089
- handleMilkyHttpRequest(ctx, req, respond, registry);
3214
+ handleMilkyHttpRequest(ctx, req, respond, registry, logger);
3090
3215
  };
3091
3216
  const adapters = [server, hub];
3092
3217
  for (const url of config.webhooks) {
@@ -3114,7 +3239,7 @@ function assembleMilkyTransports(opts) {
3114
3239
  };
3115
3240
  }
3116
3241
  /** HTTP /api 分发(规范信封 + 404/415 语义)。 */
3117
- function handleMilkyHttpRequest(ctx, req, respond, registry) {
3242
+ function handleMilkyHttpRequest(ctx, req, respond, registry, logger) {
3118
3243
  if (ctx.method !== "POST") {
3119
3244
  respond(void 0, 404);
3120
3245
  return;
@@ -3146,7 +3271,11 @@ function handleMilkyHttpRequest(ctx, req, respond, registry) {
3146
3271
  data: null,
3147
3272
  message: result.message
3148
3273
  });
3149
- }).catch(() => {
3274
+ }).catch((err) => {
3275
+ logger?.warn({
3276
+ path: ctx.path,
3277
+ error: err instanceof Error ? err.message : String(err)
3278
+ }, "milky: 动作分发异常,已回 -500");
3150
3279
  respond({
3151
3280
  status: "failed",
3152
3281
  retcode: -500,
@@ -3156,16 +3285,20 @@ function handleMilkyHttpRequest(ctx, req, respond, registry) {
3156
3285
  });
3157
3286
  }
3158
3287
  /** 鉴权钩子:Bearer 头或 access_token 查询参数(规范允许 SSE/WS 查询参数兜底)。 */
3159
- function makeMilkyAuthorize(token) {
3160
- return (ctx) => tokenMatches(ctx, token);
3288
+ function makeMilkyAuthorize(token, logger) {
3289
+ return (ctx) => tokenMatches(ctx, token, logger);
3161
3290
  }
3162
- /** 请求凭据匹配(头优先,查询参数兜底)。 */
3163
- function tokenMatches(ctx, token) {
3291
+ /** 请求凭据匹配(头优先,查询参数兜底;URL 解析失败 fail-closed 拒绝并 debug 留痕)。 */
3292
+ function tokenMatches(ctx, token, logger) {
3164
3293
  const auth = ctx.headers["authorization"] ?? ctx.headers["Authorization"];
3165
3294
  if (auth?.startsWith(BEARER_PREFIX)) return auth.slice(7) === token;
3166
3295
  try {
3167
3296
  return new URL(ctx.url, "http://localhost").searchParams.get("access_token") === token;
3168
- } catch {
3297
+ } catch (err) {
3298
+ logger?.debug({
3299
+ url: ctx.url,
3300
+ error: err instanceof Error ? err.message : String(err)
3301
+ }, "milky: 鉴权 URL 解析失败,按未授权拒绝");
3169
3302
  return false;
3170
3303
  }
3171
3304
  }