@napuketto/adapter 0.15.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/core/index.d.mts +8 -3
  3. package/dist/core/index.mjs +1 -1
  4. package/dist/core-Byoso-c3.mjs +108 -0
  5. package/dist/core-Byoso-c3.mjs.map +1 -0
  6. package/dist/{core-CxDffqmA.mjs → essence-CYb60NC6.mjs} +164 -255
  7. package/dist/essence-CYb60NC6.mjs.map +1 -0
  8. package/dist/{gray-tip-C0pnbB__.mjs → gray-tip-C7lAbfOf.mjs} +10 -10
  9. package/dist/gray-tip-C7lAbfOf.mjs.map +1 -0
  10. package/dist/index-RMEWjNfV.d.mts +91 -0
  11. package/dist/index-RMEWjNfV.d.mts.map +1 -0
  12. package/dist/kurobot/index.d.mts +6 -6
  13. package/dist/kurobot/index.d.mts.map +1 -1
  14. package/dist/kurobot/index.mjs +18 -17
  15. package/dist/kurobot/index.mjs.map +1 -1
  16. package/dist/media-DMMn74TC.mjs +126 -0
  17. package/dist/media-DMMn74TC.mjs.map +1 -0
  18. package/dist/milky/index.d.mts +20 -23
  19. package/dist/milky/index.d.mts.map +1 -1
  20. package/dist/milky/index.mjs +1286 -1297
  21. package/dist/milky/index.mjs.map +1 -1
  22. package/dist/onebot11/index.d.mts +43 -22
  23. package/dist/onebot11/index.d.mts.map +1 -1
  24. package/dist/onebot11/index.mjs +1280 -1863
  25. package/dist/onebot11/index.mjs.map +1 -1
  26. package/dist/{raw-message-D2vA27kj.mjs → raw-message-DE3sdJg8.mjs} +18 -4
  27. package/dist/raw-message-DE3sdJg8.mjs.map +1 -0
  28. package/dist/satori/index.d.mts +24 -37
  29. package/dist/satori/index.d.mts.map +1 -1
  30. package/dist/satori/index.mjs +396 -564
  31. package/dist/satori/index.mjs.map +1 -1
  32. package/package.json +1 -1
  33. package/dist/core-CxDffqmA.mjs.map +0 -1
  34. package/dist/gray-tip-C0pnbB__.mjs.map +0 -1
  35. package/dist/index-B0AaQNnq.d.mts +0 -261
  36. package/dist/index-B0AaQNnq.d.mts.map +0 -1
  37. package/dist/log-DiPRjA5P.mjs +0 -176
  38. package/dist/log-DiPRjA5P.mjs.map +0 -1
  39. package/dist/lookup-Dw0W04Ng.mjs +0 -22
  40. package/dist/lookup-Dw0W04Ng.mjs.map +0 -1
  41. package/dist/raw-message-D2vA27kj.mjs.map +0 -1
  42. package/dist/transport-schema-BEzr06W3.mjs +0 -29
  43. package/dist/transport-schema-BEzr06W3.mjs.map +0 -1
@@ -1,17 +1,17 @@
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";
2
- import { t as findFirstMatch } from "../lookup-Dw0W04Ng.mjs";
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
- 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";
1
+ import { i as runAction, n as BaseProtocolAdapter, r as ActionRegistry } from "../core-Byoso-c3.mjs";
2
+ 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-C7lAbfOf.mjs";
3
+ import { a as nodeAt, c as textOf, d as logEventFailure, f as sliceRaw, i as narrowSysMsgBlobs, l as varintAt, m as narrowBuddyReqs, n as extractEssenceSetSysMsg, o as processSysMsgBlob, r as narrowEssenceGroupArg, s as recognizeSysMsg, t as EssenceListSync, u as varintOf } from "../essence-CYb60NC6.mjs";
4
+ import { r as subscribeRawMessages, t as forEachRawMessage } from "../raw-message-DE3sdJg8.mjs";
6
5
  import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, kernelError, toCanonicalElements } from "@napuketto/kernel";
7
- import { mkdir, rename, writeFile } from "node:fs/promises";
8
- import { join } from "node:path";
9
- import { detectFileType, downloadUrl, inferExtension } from "@napuketto/media";
10
6
  import { z } from "zod";
11
7
  import { randomUUID } from "node:crypto";
8
+ import { join } from "node:path";
9
+ import { detectFileType, downloadUrl, inferExtension } from "@napuketto/media";
10
+ import { mkdir, rename, writeFile } from "node:fs/promises";
12
11
  import { fileURLToPath } from "node:url";
13
12
  import { HttpClient, HttpServer, createSseResponse, isWsOpen } from "@napuketto/network";
14
- // src/milky/action/error-map.ts
13
+ // src/milky/action/base-action.ts
14
+ /** KernelErrorCode → Milky retcode 映射表(-400/-403 规范语义,其余取常见 HTTP 语义近似负数)。 */
15
15
  const milkyErrorCodeMap = {
16
16
  SEND_FAILED: -500,
17
17
  PERMISSION_DENIED: -405,
@@ -22,118 +22,271 @@ const milkyErrorCodeMap = {
22
22
  INVALID_STATE: -409,
23
23
  UNKNOWN: -500
24
24
  };
25
- // src/milky/action/base-action.ts
26
25
  /** zod 错误摘要(单行,issues 取前 3 条)。 */
27
26
  function zodSummary(error) {
28
27
  const parts = [];
29
28
  for (const issue of error.issues.slice(0, 3)) parts.push(`${issue.path.map(String).join(".")}: ${issue.message}`);
30
29
  return parts.join("; ");
31
30
  }
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
- };
53
- }
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;
65
- }
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);
86
- return {
87
- messages: page.map((item) => essenceToEntity(item, payload.group_id)),
88
- is_end: start + page.length >= items.length
89
- };
90
- }
91
- };
92
- /** set_group_essence_message:设置/取消精华(seq → msgId 反查)。 */
93
- var SetGroupEssenceMessageAction = class extends MilkyApiAction {
94
- name = "set_group_essence_message";
95
- schema = z.object({
96
- ...groupIdField$4,
97
- message_seq: z.number().int().min(0),
98
- is_set: optBool$3
99
- });
100
- async _handle(payload) {
101
- const groupCode = String(payload.group_id);
102
- const peer = {
103
- chatType: ChatType.GROUP,
104
- peerUid: groupCode
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 {};
111
- }
112
- };
113
- /** send_group_message_reaction:消息表情表态(reaction_type face→"1" / emoji→"2")。 */
114
- var SendGroupMessageReactionAction = class extends MilkyApiAction {
115
- name = "send_group_message_reaction";
116
- schema = z.object({
117
- ...groupIdField$4,
118
- message_seq: z.number().int().min(0),
119
- reaction: z.string().min(1),
120
- reaction_type: z.enum(["face", "emoji"]).nullable().optional(),
121
- is_add: z.boolean().nullable().optional()
122
- });
123
- async _handle(payload) {
124
- const peer = {
125
- chatType: ChatType.GROUP,
126
- peerUid: String(payload.group_id)
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
31
+ /** 声明式动作工厂:闭包依赖 + 统一信封与错误映射。 */
32
+ function defineMilkyAction(spec) {
33
+ return {
34
+ name: spec.name,
35
+ schema: spec.schema,
36
+ handle: async (payload) => {
37
+ const outcome = await runAction({
38
+ schema: spec.schema,
39
+ handle: spec.handle,
40
+ errorCodeMap: milkyErrorCodeMap,
41
+ invalidRetcode: -400,
42
+ invalidMessage: (error) => `参数解析失败: ${zodSummary(error)}`
43
+ }, payload);
44
+ return outcome.ok ? {
45
+ status: "ok",
46
+ retcode: 0,
47
+ data: outcome.data,
48
+ message: ""
49
+ } : {
50
+ status: "failed",
51
+ retcode: outcome.retcode,
52
+ data: null,
53
+ message: outcome.message
54
+ };
55
+ }
56
+ };
57
+ }
58
+ // src/milky/helper/message/entities.ts
59
+ /** GroupDetailInfo / Group → GroupEntity(detail 缺失时全兜底)。 */
60
+ function toGroupEntity(detail, groupCode) {
61
+ return {
62
+ group_id: Number(groupCode),
63
+ group_name: detail?.groupName ?? "",
64
+ member_count: detail?.memberNum ?? 0,
65
+ max_member_count: detail?.maxMemberNum ?? 0,
66
+ remark: detail?.remarkName ?? "",
67
+ created_time: detail?.groupCreateTime ?? 0,
68
+ description: "",
69
+ question: "",
70
+ announcement: ""
71
+ };
72
+ }
73
+ /** 群列表项(GroupCache Group)→ GroupEntity。 */
74
+ function groupListToEntity(group) {
75
+ return {
76
+ group_id: Number(group.groupCode),
77
+ group_name: group.groupName,
78
+ member_count: group.memberCount,
79
+ max_member_count: group.maxMember,
80
+ remark: "",
81
+ created_time: 0,
82
+ description: "",
83
+ question: "",
84
+ announcement: ""
85
+ };
86
+ }
87
+ /** GroupMember → GroupMemberEntity(member 缺失时按 uin 兜底最小实体)。 */
88
+ function toGroupMemberEntity(member, groupCode, uin) {
89
+ const shutUpSeconds = member?.shutUpTime ?? 0;
90
+ return {
91
+ user_id: Number(member?.uin !== void 0 && member.uin !== "" ? member.uin : uin),
92
+ nickname: member?.nick ?? "",
93
+ sex: "unknown",
94
+ group_id: Number(groupCode),
95
+ card: member?.cardName ?? "",
96
+ title: member?.memberSpecialTitle ?? "",
97
+ level: 0,
98
+ role: GroupApi.roleToString(member?.role ?? 2),
99
+ join_time: Number(member?.joinTime) || 0,
100
+ last_sent_time: Number(member?.lastSpeakTime) || 0,
101
+ shut_up_end_time: shutUpSeconds > 0 ? Math.floor(Date.now() / 1e3) + shutUpSeconds : null
102
+ };
103
+ }
104
+ /** Friend → FriendEntity(kernel 无 qid/分类挂载,按最小实体兜底)。 */
105
+ function toFriendEntity(friend, uin, nick) {
106
+ return {
107
+ user_id: Number(friend?.uin !== void 0 && friend.uin !== "" ? friend.uin : uin),
108
+ nickname: friend?.nickname ?? nick,
109
+ sex: "unknown",
110
+ qid: "",
111
+ remark: friend?.remark ?? "",
112
+ category: {
113
+ category_id: 0,
114
+ category_name: ""
115
+ }
116
+ };
117
+ }
118
+ // src/milky/action/group-query.ts
119
+ /** 群域共入参(群号 / 成员 uin / 可选布尔;群管理 / 通知 / 精华 / 文件域复用)。 */
120
+ const groupIdField = { group_id: z.number().int().min(10001) };
121
+ const userIdField = { user_id: z.number().int().min(10001) };
122
+ const optBool$1 = z.boolean().nullable().optional();
123
+ /** 群查询域动作工厂(群信息 / 成员列表 / 成员单查 / 公告列表)。 */
124
+ function createGroupQueryActions(api) {
125
+ return [
126
+ defineMilkyAction({
127
+ name: "get_group_info",
128
+ schema: z.object({
129
+ ...groupIdField,
130
+ no_cache: optBool$1
131
+ }),
132
+ handle: async (payload) => {
133
+ const groupCode = String(payload.group_id);
134
+ return { group: toGroupEntity(api.groupCache !== void 0 ? await api.groupCache.getGroupDetail(groupCode) : await api.groupApi.getGroupInfo(groupCode), groupCode) };
135
+ }
136
+ }),
137
+ defineMilkyAction({
138
+ name: "get_group_member_list",
139
+ schema: z.object({
140
+ ...groupIdField,
141
+ no_cache: optBool$1
142
+ }),
143
+ handle: async (payload) => {
144
+ return { members: (await membersOf(api, String(payload.group_id))).map((m) => toGroupMemberEntity(m, String(payload.group_id), m.uin)) };
145
+ }
146
+ }),
147
+ defineMilkyAction({
148
+ name: "get_group_member_info",
149
+ schema: z.object({
150
+ ...groupIdField,
151
+ ...userIdField,
152
+ no_cache: optBool$1
153
+ }),
154
+ handle: async (payload) => {
155
+ return { member: toGroupMemberEntity(await memberOf(api, payload.group_id, payload.user_id), String(payload.group_id), String(payload.user_id)) };
156
+ }
157
+ }),
158
+ defineMilkyAction({
159
+ name: "get_group_announcements",
160
+ schema: z.object({ ...groupIdField }),
161
+ handle: async (payload) => {
162
+ const groupCode = String(payload.group_id);
163
+ const bulletins = await api.groupApi.getGroupAnnouncements(groupCode);
164
+ return { announcements: await Promise.all(bulletins.map((b) => bulletinToEntity(b, payload.group_id, api))) };
165
+ }
166
+ })
167
+ ];
168
+ }
169
+ /** ---------- 内部辅助 ---------- */
170
+ /** 成员列表(GroupCache 优先,未装配直查)。 */
171
+ async function membersOf(api, groupCode) {
172
+ if (api.groupCache !== void 0) return await api.groupCache.getMembers(groupCode);
173
+ return await api.groupApi.getGroupMemberList(groupCode, true);
174
+ }
175
+ /** 成员单查(user_id = uin;缓存路径经 uid,直查路径按 uin 匹配)。 */
176
+ async function memberOf(api, groupId, userId) {
177
+ const groupCode = String(groupId);
178
+ const uin = String(userId);
179
+ if (api.groupCache !== void 0) {
180
+ const uid = await api.resolveUidFromUin(userId).catch((err) => {
181
+ api.logger?.debug({
182
+ group: groupCode,
183
+ uin,
184
+ error: err instanceof Error ? err.message : String(err)
185
+ }, "milky: 成员 uin→uid 失败,退用 uin 查缓存");
186
+ return uin;
133
187
  });
134
- return {};
188
+ const member = await api.groupCache.getMember(groupCode, uid);
189
+ if (member === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
190
+ return member;
135
191
  }
136
- };
192
+ const hit = (await api.groupApi.getGroupMemberList(groupCode, true)).find((m) => m.uin === uin);
193
+ if (hit === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
194
+ return hit;
195
+ }
196
+ /** GroupBulletin → 群公告实体(senderUid → uin 反查;无源字段兜底,待校准)。 */
197
+ async function bulletinToEntity(b, groupId, api) {
198
+ return {
199
+ group_id: groupId,
200
+ announcement_id: b.announcementId ?? "",
201
+ user_id: await senderUinOf(b, api),
202
+ time: Number(b.publishTime) || 0,
203
+ content: b.content ?? "",
204
+ image_url: picUrlOf(b)
205
+ };
206
+ }
207
+ /** 公告发送者 uid → uin(缺省/转换失败 0 兜底)。 */
208
+ async function senderUinOf(b, api) {
209
+ const uid = b.senderUid;
210
+ if (typeof uid !== "string" || uid === "") return 0;
211
+ const uins = await api.uidToUin([uid]).catch((err) => {
212
+ api.logger?.debug({
213
+ uid,
214
+ error: err instanceof Error ? err.message : String(err)
215
+ }, "milky: 公告发送者 uid→uin 失败,兜底 0");
216
+ });
217
+ return Number(uins?.get(uid)) || 0;
218
+ }
219
+ /** 公告图片 url(缺省 null)。 */
220
+ function picUrlOf(b) {
221
+ const url = b.pic?.url;
222
+ return typeof url === "string" && url !== "" ? url : null;
223
+ }
224
+ // src/milky/action/group-essence.ts
225
+ /** 群精华与表态域动作工厂。 */
226
+ function createGroupEssenceActions(api) {
227
+ return [
228
+ defineMilkyAction({
229
+ name: "get_group_essence_messages",
230
+ schema: z.object({
231
+ ...groupIdField,
232
+ page_index: z.number().int().min(0),
233
+ page_size: z.number().int().min(0)
234
+ }),
235
+ handle: async (payload) => {
236
+ const items = await api.webApi.getEssenceMsgList(String(payload.group_id));
237
+ const start = payload.page_index * payload.page_size;
238
+ const page = items.slice(start, start + payload.page_size);
239
+ return {
240
+ messages: page.map((item) => essenceToEntity(item, payload.group_id)),
241
+ is_end: start + page.length >= items.length
242
+ };
243
+ }
244
+ }),
245
+ defineMilkyAction({
246
+ name: "set_group_essence_message",
247
+ schema: z.object({
248
+ ...groupIdField,
249
+ message_seq: z.number().int().min(0),
250
+ is_set: optBool$1
251
+ }),
252
+ handle: async (payload) => {
253
+ const groupCode = String(payload.group_id);
254
+ const peer = {
255
+ chatType: ChatType.GROUP,
256
+ peerUid: groupCode
257
+ };
258
+ const msgId = await api.resolveMsgIdBySeq(peer, payload.message_seq, ChatType.GROUP);
259
+ if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
260
+ if (payload.is_set === false) await api.groupApi.removeGroupEssence(groupCode, msgId);
261
+ else await api.groupApi.addGroupEssence(groupCode, msgId);
262
+ return {};
263
+ }
264
+ }),
265
+ defineMilkyAction({
266
+ name: "send_group_message_reaction",
267
+ schema: z.object({
268
+ ...groupIdField,
269
+ message_seq: z.number().int().min(0),
270
+ reaction: z.string().min(1),
271
+ reaction_type: z.enum(["face", "emoji"]).nullable().optional(),
272
+ is_add: z.boolean().nullable().optional()
273
+ }),
274
+ handle: async (payload) => {
275
+ const peer = {
276
+ chatType: ChatType.GROUP,
277
+ peerUid: String(payload.group_id)
278
+ };
279
+ await api.msgApi.setMsgEmojiLike(peer, {
280
+ msgSeq: String(payload.message_seq),
281
+ emojiId: payload.reaction,
282
+ emojiType: payload.reaction_type === "emoji" ? "2" : "1",
283
+ like: payload.is_add !== false
284
+ });
285
+ return {};
286
+ }
287
+ })
288
+ ];
289
+ }
137
290
  /** ---------- 内部辅助 ---------- */
138
291
  /** 精华项 → GroupEssenceMessage(msg_content 近似翻译:text / image)。 */
139
292
  function essenceToEntity(item, groupId) {
@@ -221,107 +374,142 @@ async function writeBase64(payload, mediaDir) {
221
374
  }
222
375
  }
223
376
  // src/milky/action/group-file.ts
224
- const groupIdField$3 = { group_id: z.number().int().min(10001) };
225
377
  const fileIdField = { file_id: z.string().min(1) };
226
378
  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
- }
247
- };
248
- /** move_group_file:移动文件(target_folder_id 空 = 移到根目录;parent 入参仅 schema 兼容)。 */
249
- var MoveGroupFileAction = class extends MilkyApiAction {
250
- name = "move_group_file";
251
- schema = z.object({
252
- ...groupIdField$3,
253
- ...fileIdField,
254
- parent_folder_id: optStr$2,
255
- target_folder_id: optStr$2
256
- });
257
- async _handle(payload) {
258
- await this.api.richMediaApi.moveGroupFile(String(payload.group_id), [payload.file_id], payload.target_folder_id ?? "");
259
- return {};
260
- }
261
- };
262
- /** rename_group_file:重命名文件。 */
263
- var RenameGroupFileAction = class extends MilkyApiAction {
264
- name = "rename_group_file";
265
- schema = z.object({
266
- ...groupIdField$3,
267
- ...fileIdField,
268
- parent_folder_id: optStr$2,
269
- new_file_name: z.string().min(1)
270
- });
271
- async _handle(payload) {
272
- await this.api.richMediaApi.renameGroupFile(String(payload.group_id), payload.file_id, payload.new_file_name);
273
- return {};
274
- }
275
- };
276
- /** delete_group_file:删除文件。 */
277
- var DeleteGroupFileAction = class extends MilkyApiAction {
278
- name = "delete_group_file";
279
- schema = z.object({
280
- ...groupIdField$3,
281
- ...fileIdField
282
- });
283
- async _handle(payload) {
284
- await this.api.richMediaApi.deleteGroupFile(String(payload.group_id), [payload.file_id]);
285
- return {};
286
- }
287
- };
288
- /**
289
- * persist_group_file:转存文件(RichMediaApi.transGroupFile,转存语义待对齐)。
290
- */
291
- var PersistGroupFileAction = class extends MilkyApiAction {
292
- name = "persist_group_file";
293
- schema = z.object({
294
- ...groupIdField$3,
295
- ...fileIdField
296
- });
297
- async _handle(payload) {
298
- await this.api.richMediaApi.transGroupFile(String(payload.group_id), payload.file_id);
299
- return {};
300
- }
301
- };
302
- /** create_group_folder:创建文件夹(返回 folder_id)。 */
303
- var CreateGroupFolderAction = class extends MilkyApiAction {
304
- name = "create_group_folder";
305
- schema = z.object({
306
- ...groupIdField$3,
307
- folder_name: z.string().min(1)
308
- });
309
- async _handle(payload) {
310
- return { folder_id: await this.api.richMediaApi.createGroupFolder(String(payload.group_id), payload.folder_name) };
311
- }
312
- };
313
- /** delete_group_folder:删除文件夹。 */
314
- var DeleteGroupFolderAction = class extends MilkyApiAction {
315
- name = "delete_group_folder";
316
- schema = z.object({
317
- ...groupIdField$3,
318
- folder_id: z.string().min(1)
319
- });
320
- async _handle(payload) {
321
- await this.api.richMediaApi.deleteGroupFolder(String(payload.group_id), payload.folder_id);
322
- return {};
323
- }
324
- };
379
+ /** 群文件域动作工厂(列表 / 移动 / 重命名 / 删除 / 转存 / 文件夹 / 闪传上传 / 下载链接)。 */
380
+ function createGroupFileActions(api) {
381
+ return [
382
+ defineMilkyAction({
383
+ name: "get_group_files",
384
+ schema: z.object({
385
+ ...groupIdField,
386
+ parent_folder_id: optStr$2
387
+ }),
388
+ handle: async (payload) => {
389
+ const groupCode = String(payload.group_id);
390
+ const parent = payload.parent_folder_id ?? "";
391
+ const items = await api.richMediaApi.getGroupFileList(groupCode, parent);
392
+ const files = [];
393
+ const folders = [];
394
+ for (const item of items) if (item.fileInfo !== void 0) files.push(fileToEntity(item.fileInfo, payload.group_id));
395
+ else if (item.folderInfo !== void 0) folders.push(folderToEntity(item.folderInfo, payload.group_id));
396
+ return {
397
+ files,
398
+ folders
399
+ };
400
+ }
401
+ }),
402
+ defineMilkyAction({
403
+ name: "move_group_file",
404
+ schema: z.object({
405
+ ...groupIdField,
406
+ ...fileIdField,
407
+ parent_folder_id: optStr$2,
408
+ target_folder_id: optStr$2
409
+ }),
410
+ handle: async (payload) => {
411
+ await api.richMediaApi.moveGroupFile(String(payload.group_id), [payload.file_id], payload.target_folder_id ?? "");
412
+ return {};
413
+ }
414
+ }),
415
+ defineMilkyAction({
416
+ name: "rename_group_file",
417
+ schema: z.object({
418
+ ...groupIdField,
419
+ ...fileIdField,
420
+ parent_folder_id: optStr$2,
421
+ new_file_name: z.string().min(1)
422
+ }),
423
+ handle: async (payload) => {
424
+ await api.richMediaApi.renameGroupFile(String(payload.group_id), payload.file_id, payload.new_file_name);
425
+ return {};
426
+ }
427
+ }),
428
+ defineMilkyAction({
429
+ name: "delete_group_file",
430
+ schema: z.object({
431
+ ...groupIdField,
432
+ ...fileIdField
433
+ }),
434
+ handle: async (payload) => {
435
+ await api.richMediaApi.deleteGroupFile(String(payload.group_id), [payload.file_id]);
436
+ return {};
437
+ }
438
+ }),
439
+ defineMilkyAction({
440
+ name: "persist_group_file",
441
+ schema: z.object({
442
+ ...groupIdField,
443
+ ...fileIdField
444
+ }),
445
+ handle: async (payload) => {
446
+ await api.richMediaApi.transGroupFile(String(payload.group_id), payload.file_id);
447
+ return {};
448
+ }
449
+ }),
450
+ defineMilkyAction({
451
+ name: "create_group_folder",
452
+ schema: z.object({
453
+ ...groupIdField,
454
+ folder_name: z.string().min(1)
455
+ }),
456
+ handle: async (payload) => {
457
+ return { folder_id: await api.richMediaApi.createGroupFolder(String(payload.group_id), payload.folder_name) };
458
+ }
459
+ }),
460
+ defineMilkyAction({
461
+ name: "delete_group_folder",
462
+ schema: z.object({
463
+ ...groupIdField,
464
+ folder_id: z.string().min(1)
465
+ }),
466
+ handle: async (payload) => {
467
+ await api.richMediaApi.deleteGroupFolder(String(payload.group_id), payload.folder_id);
468
+ return {};
469
+ }
470
+ }),
471
+ defineMilkyAction({
472
+ name: "upload_group_file",
473
+ schema: z.object({
474
+ ...groupIdField,
475
+ parent_folder_id: optStr$2,
476
+ file_uri: z.string().min(1),
477
+ file_name: z.string().min(1)
478
+ }),
479
+ handle: async (payload) => {
480
+ const path = await resolveUriToPath(payload.file_uri, api.mediaDir);
481
+ const peer = {
482
+ chatType: ChatType.GROUP,
483
+ peerUid: String(payload.group_id)
484
+ };
485
+ return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
486
+ }
487
+ }),
488
+ defineMilkyAction({
489
+ name: "get_group_file_download_url",
490
+ schema: z.object({
491
+ ...groupIdField,
492
+ ...fileIdField
493
+ }),
494
+ handle: async (payload) => {
495
+ return { download_url: await api.richMediaApi.getGroupFileDownloadUrl(String(payload.group_id), payload.file_id) };
496
+ }
497
+ }),
498
+ defineMilkyAction({
499
+ name: "rename_group_folder",
500
+ schema: z.object({
501
+ ...groupIdField,
502
+ folder_id: z.string().min(1),
503
+ new_folder_name: z.string().min(1)
504
+ }),
505
+ handle: async (payload) => {
506
+ await api.richMediaApi.renameGroupFolder(String(payload.group_id), payload.folder_id, payload.new_folder_name);
507
+ return {};
508
+ }
509
+ })
510
+ ];
511
+ }
512
+ /** ---------- 内部辅助 ---------- */
325
513
  /** GroupFileItemInfo → GroupFileEntity(fileSize 原生为字符串;无源字段兜底)。 */
326
514
  function fileToEntity(info, groupId) {
327
515
  return {
@@ -353,231 +541,176 @@ function folderToEntity(info, groupId) {
353
541
  file_count: num("totalFileCount")
354
542
  };
355
543
  }
356
- /**
357
- * upload_group_file:上传并投递文件(**闪传通道**:分享链接卡片,见文件头语义说明)。
358
- * file_id 返回闪传文件集 id(非群文件 fileId)。
359
- */
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
- }
376
- };
377
- /** get_group_file_download_url:群文件下载链接(url 字段待实机确认,仅根目录)。 */
378
- var GetGroupFileDownloadUrlAction = class extends MilkyApiAction {
379
- name = "get_group_file_download_url";
380
- schema = z.object({
381
- ...groupIdField$3,
382
- ...fileIdField
383
- });
384
- async _handle(payload) {
385
- return { download_url: await this.api.richMediaApi.getGroupFileDownloadUrl(String(payload.group_id), payload.file_id) };
386
- }
387
- };
388
- /** rename_group_folder:重命名群文件夹(renameGroupFile 同款形态,待校准)。 */
389
- var RenameGroupFolderAction = class extends MilkyApiAction {
390
- name = "rename_group_folder";
391
- schema = z.object({
392
- ...groupIdField$3,
393
- folder_id: z.string().min(1),
394
- new_folder_name: z.string().min(1)
395
- });
396
- async _handle(payload) {
397
- await this.api.richMediaApi.renameGroupFolder(String(payload.group_id), payload.folder_id, payload.new_folder_name);
398
- return {};
399
- }
400
- };
401
544
  // src/milky/action/group-manage.ts
402
545
  /**
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。
546
+ * Milky 群管理域动作:send_group_nudge / set_group_name / set_group_member_card /
547
+ * set_group_member_admin / set_group_member_mute / set_group_whole_mute /
548
+ * kick_group_member / quit_group / set_group_avatar /
549
+ * set_group_member_special_title / send_group_announcement / delete_group_announcement。
550
+ * 写操作合:成员类操作 user_id(uin) → uid 转换后进 kernel(resolveUidFromUin);
551
+ * 公告 image_uri / 头像 image_uri 落盘后进 kernel。
408
552
  */
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
553
  const optStr$1 = z.string().nullable().optional();
413
554
  /** NTGroupMemberRole 数值(ADMIN=3 / MEMBER=2,setMemberRole 入参)。 */
414
555
  const NTGroupMemberRoleAdmin = 3;
415
556
  const NTGroupMemberRoleMember = 2;
416
- /** send_group_nudge:发送群戳一戳(self.uid 缺失报 INVALID_PARAM)。 */
417
- var SendGroupNudgeAction = class extends MilkyApiAction {
418
- name = "send_group_nudge";
419
- schema = z.object({
420
- ...groupIdField$2,
421
- ...userIdField$1
422
- });
423
- async _handle(payload) {
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 {};
431
- }
432
- };
433
- /** set_group_name:设置群名。 */
434
- var SetGroupNameAction = class extends MilkyApiAction {
435
- name = "set_group_name";
436
- schema = z.object({
437
- ...groupIdField$2,
438
- new_group_name: z.string()
439
- });
440
- async _handle(payload) {
441
- await this.api.groupApi.modifyGroupName(String(payload.group_id), payload.new_group_name);
442
- return {};
443
- }
444
- };
445
- /** set_group_member_card:设置群名片。 */
446
- var SetGroupMemberCardAction = class extends MilkyApiAction {
447
- name = "set_group_member_card";
448
- schema = z.object({
449
- ...groupIdField$2,
450
- ...userIdField$1,
451
- card: z.string()
452
- });
453
- async _handle(payload) {
454
- const uid = await this.api.resolveUidFromUin(payload.user_id);
455
- this.api.groupApi.setMemberCardName(String(payload.group_id), uid, payload.card);
456
- return {};
457
- }
458
- };
459
- /** set_group_member_admin:设置/取消管理员(is_set 缺省 true)。 */
460
- var SetGroupMemberAdminAction = class extends MilkyApiAction {
461
- name = "set_group_member_admin";
462
- schema = z.object({
463
- ...groupIdField$2,
464
- ...userIdField$1,
465
- is_set: optBool$2
466
- });
467
- async _handle(payload) {
468
- const uid = await this.api.resolveUidFromUin(payload.user_id);
469
- this.api.groupApi.setMemberRole(String(payload.group_id), uid, payload.is_set === false ? NTGroupMemberRoleMember : NTGroupMemberRoleAdmin);
470
- return {};
471
- }
472
- };
473
- /** set_group_member_mute:禁言成员(duration 秒,0 解除)。 */
474
- var SetGroupMemberMuteAction = class extends MilkyApiAction {
475
- name = "set_group_member_mute";
476
- schema = z.object({
477
- ...groupIdField$2,
478
- ...userIdField$1,
479
- duration: z.number().int().min(0).nullable().optional()
480
- });
481
- async _handle(payload) {
482
- const uid = await this.api.resolveUidFromUin(payload.user_id);
483
- await this.api.groupApi.setMemberShutUp(String(payload.group_id), [{
484
- uid,
485
- duration: payload.duration ?? 0
486
- }]);
487
- return {};
488
- }
489
- };
490
- /** set_group_whole_mute:全员禁言开关(is_mute 缺省 true)。 */
491
- var SetGroupWholeMuteAction = class extends MilkyApiAction {
492
- name = "set_group_whole_mute";
493
- schema = z.object({
494
- ...groupIdField$2,
495
- is_mute: optBool$2
496
- });
497
- async _handle(payload) {
498
- await this.api.groupApi.setGroupShutUp(String(payload.group_id), payload.is_mute !== false);
499
- return {};
500
- }
501
- };
502
- /** kick_group_member:移除成员(reject_add_request 默认 false)。 */
503
- var KickGroupMemberAction = class extends MilkyApiAction {
504
- name = "kick_group_member";
505
- schema = z.object({
506
- ...groupIdField$2,
507
- ...userIdField$1,
508
- reject_add_request: optBool$2
509
- });
510
- async _handle(payload) {
511
- const uid = await this.api.resolveUidFromUin(payload.user_id);
512
- await this.api.groupApi.kickMember(String(payload.group_id), [uid], payload.reject_add_request === true);
513
- return {};
514
- }
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
- /** ---------- 内部辅助 ---------- */
557
+ /** 群管理域动作工厂(群设置 / 成员管理 / 公告 / 戳一戳)。 */
558
+ function createGroupManageActions(api) {
559
+ return [
560
+ defineMilkyAction({
561
+ name: "send_group_nudge",
562
+ schema: z.object({
563
+ ...groupIdField,
564
+ ...userIdField
565
+ }),
566
+ handle: async (payload) => {
567
+ const receiverUid = await api.resolveUidFromUin(payload.user_id);
568
+ const peer = await api.resolvePeer("group", payload.group_id);
569
+ await api.msgApi.sendNudge(peer, {
570
+ receiverUid,
571
+ callerUid: requireSelfUid$1(api)
572
+ });
573
+ return {};
574
+ }
575
+ }),
576
+ defineMilkyAction({
577
+ name: "set_group_name",
578
+ schema: z.object({
579
+ ...groupIdField,
580
+ new_group_name: z.string()
581
+ }),
582
+ handle: async (payload) => {
583
+ await api.groupApi.modifyGroupName(String(payload.group_id), payload.new_group_name);
584
+ return {};
585
+ }
586
+ }),
587
+ defineMilkyAction({
588
+ name: "set_group_member_card",
589
+ schema: z.object({
590
+ ...groupIdField,
591
+ ...userIdField,
592
+ card: z.string()
593
+ }),
594
+ handle: async (payload) => {
595
+ const uid = await api.resolveUidFromUin(payload.user_id);
596
+ api.groupApi.setMemberCardName(String(payload.group_id), uid, payload.card);
597
+ return {};
598
+ }
599
+ }),
600
+ defineMilkyAction({
601
+ name: "set_group_member_admin",
602
+ schema: z.object({
603
+ ...groupIdField,
604
+ ...userIdField,
605
+ is_set: optBool$1
606
+ }),
607
+ handle: async (payload) => {
608
+ const uid = await api.resolveUidFromUin(payload.user_id);
609
+ api.groupApi.setMemberRole(String(payload.group_id), uid, payload.is_set === false ? NTGroupMemberRoleMember : NTGroupMemberRoleAdmin);
610
+ return {};
611
+ }
612
+ }),
613
+ defineMilkyAction({
614
+ name: "set_group_member_mute",
615
+ schema: z.object({
616
+ ...groupIdField,
617
+ ...userIdField,
618
+ duration: z.number().int().min(0).nullable().optional()
619
+ }),
620
+ handle: async (payload) => {
621
+ const uid = await api.resolveUidFromUin(payload.user_id);
622
+ await api.groupApi.setMemberShutUp(String(payload.group_id), [{
623
+ uid,
624
+ duration: payload.duration ?? 0
625
+ }]);
626
+ return {};
627
+ }
628
+ }),
629
+ defineMilkyAction({
630
+ name: "set_group_whole_mute",
631
+ schema: z.object({
632
+ ...groupIdField,
633
+ is_mute: optBool$1
634
+ }),
635
+ handle: async (payload) => {
636
+ await api.groupApi.setGroupShutUp(String(payload.group_id), payload.is_mute !== false);
637
+ return {};
638
+ }
639
+ }),
640
+ defineMilkyAction({
641
+ name: "kick_group_member",
642
+ schema: z.object({
643
+ ...groupIdField,
644
+ ...userIdField,
645
+ reject_add_request: optBool$1
646
+ }),
647
+ handle: async (payload) => {
648
+ const uid = await api.resolveUidFromUin(payload.user_id);
649
+ await api.groupApi.kickMember(String(payload.group_id), [uid], payload.reject_add_request === true);
650
+ return {};
651
+ }
652
+ }),
653
+ defineMilkyAction({
654
+ name: "quit_group",
655
+ schema: z.object({ ...groupIdField }),
656
+ handle: async (payload) => {
657
+ await api.groupApi.quitGroup(String(payload.group_id));
658
+ return {};
659
+ }
660
+ }),
661
+ defineMilkyAction({
662
+ name: "set_group_avatar",
663
+ schema: z.object({
664
+ ...groupIdField,
665
+ image_uri: z.string().min(1)
666
+ }),
667
+ handle: async (payload) => {
668
+ const imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir);
669
+ await api.groupApi.setGroupAvatar(String(payload.group_id), imagePath);
670
+ return {};
671
+ }
672
+ }),
673
+ defineMilkyAction({
674
+ name: "set_group_member_special_title",
675
+ schema: z.object({
676
+ ...groupIdField,
677
+ ...userIdField,
678
+ special_title: z.string()
679
+ }),
680
+ handle: async (payload) => {
681
+ const uid = await api.resolveUidFromUin(payload.user_id);
682
+ await api.groupApi.setMemberSpecialTitle(String(payload.group_id), uid, payload.special_title);
683
+ return {};
684
+ }
685
+ }),
686
+ defineMilkyAction({
687
+ name: "send_group_announcement",
688
+ schema: z.object({
689
+ ...groupIdField,
690
+ content: z.string().min(1),
691
+ image_uri: optStr$1
692
+ }),
693
+ handle: async (payload) => {
694
+ const groupCode = String(payload.group_id);
695
+ let imagePath;
696
+ if (payload.image_uri !== void 0 && payload.image_uri !== null && payload.image_uri !== "") imagePath = await resolveUriToPath(payload.image_uri, api.mediaDir);
697
+ await api.groupApi.publishGroupAnnouncement(groupCode, payload.content, imagePath);
698
+ return {};
699
+ }
700
+ }),
701
+ defineMilkyAction({
702
+ name: "delete_group_announcement",
703
+ schema: z.object({
704
+ ...groupIdField,
705
+ announcement_id: z.string().min(1)
706
+ }),
707
+ handle: async (payload) => {
708
+ await api.groupApi.deleteGroupAnnouncement(String(payload.group_id), payload.announcement_id);
709
+ return {};
710
+ }
711
+ })
712
+ ];
713
+ }
581
714
  /** self.uid 必备(nudge 发送的 callerUid;缺配置报 INVALID_PARAM)。 */
582
715
  function requireSelfUid$1(api) {
583
716
  const uid = api.self.uid;
@@ -641,11 +774,14 @@ var MilkyApi = class {
641
774
  */
642
775
  async resolveUidFromUin(uin) {
643
776
  const uinStr = String(uin);
777
+ let cause;
644
778
  try {
645
779
  const uid = (await this.uinToUid([uinStr])).get(uinStr);
646
780
  if (uid !== void 0 && uid !== "") return uid;
647
- } catch {}
648
- throw kernelError(`用户 ${uinStr} 不存在或 uin→uid 转换失败`, "INVALID_PARAM");
781
+ } catch (err) {
782
+ cause = err;
783
+ }
784
+ throw kernelError(`用户 ${uinStr} 不存在或 uin→uid 转换失败`, "INVALID_PARAM", cause === void 0 ? void 0 : { cause });
649
785
  }
650
786
  /**
651
787
  * message_scene + 数字 ID → NT Peer。
@@ -660,7 +796,12 @@ var MilkyApi = class {
660
796
  let uid;
661
797
  try {
662
798
  uid = (await this.uinToUid([uin])).get(uin);
663
- } catch {}
799
+ } catch (err) {
800
+ this.logger?.warn({
801
+ uin,
802
+ error: err instanceof Error ? err.message : String(err)
803
+ }, "milky: uin→uid 转换失败,peer 退用 uin 原样");
804
+ }
664
805
  return {
665
806
  chatType: scene === "friend" ? ChatType.C2C : ChatType.C2C_TEMP,
666
807
  peerUid: uid ?? uin
@@ -673,7 +814,14 @@ var MilkyApi = class {
673
814
  async resolveMsgIdBySeq(peer, seq, chatType) {
674
815
  const indexed = this.seqIndex.resolveMsgId(chatType, peer.peerUid, seq);
675
816
  if (indexed !== void 0) return indexed;
676
- const hit = (await this.msgApi.fetchMessages(peer, { count: 60 }).catch(() => [])).find((m) => Number(m.msgSeq) === seq);
817
+ const hit = (await this.msgApi.fetchMessages(peer, { count: 60 }).catch((err) => {
818
+ this.logger?.debug({
819
+ peer: peer.peerUid,
820
+ seq,
821
+ error: err instanceof Error ? err.message : String(err)
822
+ }, "milky: msgSeq 反查近段历史失败");
823
+ return [];
824
+ })).find((m) => Number(m.msgSeq) === seq);
677
825
  if (hit === void 0) return;
678
826
  this.seqIndex.record(hit);
679
827
  return hit.msgId;
@@ -692,19 +840,22 @@ var MilkyApi = class {
692
840
  /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
693
841
  const NOTIFY_SEARCH_COUNT$1 = 100;
694
842
  /**
695
- * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
696
- * 屏序骨架走 core findFirstMatch)。
843
+ * 按通知 seq 查找群通知(先非可疑后可疑两屏依序,OB11 set_group_add_request
844
+ * 同路径)。屏序惰性拉取:前一屏命中则不拉后续屏(群通知规范序)。
697
845
  * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
698
846
  * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
699
847
  */
700
848
  async function findGroupNotify(api, seq) {
701
- const hit = await findFirstMatch([() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)], (item) => item.seq === seq);
702
- if (hit === void 0) throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
703
- return hit;
849
+ const screens = [() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)];
850
+ for (const fetchScreen of screens) {
851
+ const hit = (await fetchScreen()).find((item) => item.seq === seq);
852
+ if (hit !== void 0) return hit;
853
+ }
854
+ throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
704
855
  }
705
856
  /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
706
857
  async function findBuddyReq(api, initiatorUid) {
707
- const hit = await findFirstMatch([() => api.friendApi.getBuddyReqList()], (req) => req.friendUid === initiatorUid);
858
+ const hit = (await api.friendApi.getBuddyReqList()).find((req) => req.friendUid === initiatorUid);
708
859
  if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
709
860
  return hit;
710
861
  }
@@ -780,108 +931,96 @@ function collectNotifyUids(notifies) {
780
931
  return [...uids];
781
932
  }
782
933
  // src/milky/action/group-notice.ts
783
- const groupIdField$1 = { group_id: z.number().int().min(10001) };
784
- const optBool$1 = z.boolean().nullable().optional();
785
934
  const optStr = z.string().nullable().optional();
786
- /**
787
- * get_group_notifications:获取群通知列表。
788
- * kernel getSingleScreenNotifies 为单屏快照(无翻页)——start_notification_seq
789
- * 作客户端过滤(取 seq 更小的记录);next = 本页最小 seq(仍有余量时)。
790
- */
791
- var GetGroupNotificationsAction = class extends MilkyApiAction {
792
- name = "get_group_notifications";
793
- schema = z.object({
794
- start_notification_seq: z.number().int().min(0).nullable().optional(),
795
- is_filtered: optBool$1,
796
- limit: z.number().int().min(0).nullable().optional()
797
- });
798
- async _handle(payload) {
799
- const notifies = await this.api.groupNotifyApi.getSingleScreenNotifies(payload.is_filtered === true, NOTIFY_SEARCH_COUNT);
800
- const start = payload.start_notification_seq;
801
- const filtered = notifies.filter((n) => start === void 0 || start === null || Number(n.seq) < start);
802
- const uidToUin = await this.collectUidToUin(filtered);
803
- const entities = filtered.map((n) => notifyToEntity(n, payload.is_filtered === true, uidToUin)).filter((e) => e !== null);
804
- const limit = payload.limit ?? NOTIFICATIONS_DEFAULT_LIMIT;
805
- const page = entities.slice(0, limit);
806
- const minSeq = page.reduce((acc, e) => acc === null ? e.notification_seq : Math.min(acc, e.notification_seq), null);
807
- return {
808
- notifications: page,
809
- next_notification_seq: entities.length > page.length && minSeq !== null ? minSeq : null
810
- };
811
- }
812
- /** 通知 user1/user2 uid → uin 批量转换(失败退空 Map,实体 id 兜底 0)。 */
813
- async collectUidToUin(notifies) {
814
- const uids = collectNotifyUids(notifies);
815
- if (uids.length === 0) return /* @__PURE__ */ new Map();
816
- return await this.api.uidToUin(uids).catch(() => /* @__PURE__ */ new Map());
817
- }
818
- };
819
- /** accept/reject 群请求 / 群邀请公共基类:seq → 通知匹配 → handleGroupRequest。 */
820
- var HandleGroupNotifyBase = class extends MilkyApiAction {
821
- async respond(seq, doubt) {
822
- const notify = await findGroupNotify(this.api, String(seq));
823
- await this.api.groupNotifyApi.handleGroupRequest(doubt, notify, this.approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE, " ");
824
- return {};
825
- }
826
- };
827
- /** accept_group_request:同意入群请求(notification_type/group_id 仅 schema 校验)。 */
828
- var AcceptGroupRequestAction = class extends HandleGroupNotifyBase {
829
- name = "accept_group_request";
830
- schema = z.object({
831
- notification_seq: z.number().int().min(0),
832
- notification_type: z.enum(["join_request", "invited_join_request"]),
833
- ...groupIdField$1,
834
- is_filtered: optBool$1
835
- });
836
- approve = true;
837
- async _handle(payload) {
838
- return await this.respond(payload.notification_seq, payload.is_filtered === true);
839
- }
840
- };
841
- /** reject_group_request:拒绝入群请求(reason 无源,kernel postscript 占位空格)。 */
842
- var RejectGroupRequestAction = class extends HandleGroupNotifyBase {
843
- name = "reject_group_request";
844
- schema = z.object({
845
- notification_seq: z.number().int().min(0),
846
- notification_type: z.enum(["join_request", "invited_join_request"]),
847
- ...groupIdField$1,
848
- is_filtered: optBool$1,
849
- reason: optStr
850
- });
851
- approve = false;
852
- async _handle(payload) {
853
- return await this.respond(payload.notification_seq, payload.is_filtered === true);
854
- }
855
- };
856
- /** accept_group_invitation:接受入群邀请(按 invitation_seq 匹配)。 */
857
- var AcceptGroupInvitationAction = class extends HandleGroupNotifyBase {
858
- name = "accept_group_invitation";
859
- schema = z.object({
860
- ...groupIdField$1,
861
- invitation_seq: z.number().int().min(0)
862
- });
863
- approve = true;
864
- async _handle(payload) {
865
- return await this.respond(payload.invitation_seq, false);
866
- }
867
- };
868
- /** reject_group_invitation:拒绝入群邀请。 */
869
- var RejectGroupInvitationAction = class extends HandleGroupNotifyBase {
870
- name = "reject_group_invitation";
871
- schema = z.object({
872
- ...groupIdField$1,
873
- invitation_seq: z.number().int().min(0)
874
- });
875
- approve = false;
876
- async _handle(payload) {
877
- return await this.respond(payload.invitation_seq, false);
878
- }
879
- };
880
- /** ---------- 内部辅助 ---------- */
881
935
  /** 通知查找数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
882
936
  const NOTIFY_SEARCH_COUNT = 100;
883
937
  /** get_group_notifications 默认 limit(规范 default 20)。 */
884
938
  const NOTIFICATIONS_DEFAULT_LIMIT = 20;
939
+ /** 群通知域动作工厂(通知列表 + 应答四动作)。 */
940
+ function createGroupNoticeActions(api) {
941
+ return [
942
+ defineMilkyAction({
943
+ name: "get_group_notifications",
944
+ schema: z.object({
945
+ start_notification_seq: z.number().int().min(0).nullable().optional(),
946
+ is_filtered: optBool$1,
947
+ limit: z.number().int().min(0).nullable().optional()
948
+ }),
949
+ handle: async (payload) => {
950
+ const notifies = await api.groupNotifyApi.getSingleScreenNotifies(payload.is_filtered === true, NOTIFY_SEARCH_COUNT);
951
+ const start = payload.start_notification_seq;
952
+ const filtered = notifies.filter((n) => start === void 0 || start === null || Number(n.seq) < start);
953
+ const uidToUin = await collectUidToUin$1(api, filtered);
954
+ const entities = filtered.map((n) => notifyToEntity(n, payload.is_filtered === true, uidToUin)).filter((e) => e !== null);
955
+ const limit = payload.limit ?? NOTIFICATIONS_DEFAULT_LIMIT;
956
+ const page = entities.slice(0, limit);
957
+ const minSeq = page.reduce((acc, e) => acc === null ? e.notification_seq : Math.min(acc, e.notification_seq), null);
958
+ return {
959
+ notifications: page,
960
+ next_notification_seq: entities.length > page.length && minSeq !== null ? minSeq : null
961
+ };
962
+ }
963
+ }),
964
+ defineMilkyAction({
965
+ name: "accept_group_request",
966
+ schema: respondRequestSchema,
967
+ handle: async (payload) => respondGroupNotify(api, payload.notification_seq, payload.is_filtered === true, true)
968
+ }),
969
+ defineMilkyAction({
970
+ name: "reject_group_request",
971
+ schema: rejectRequestSchema,
972
+ handle: async (payload) => respondGroupNotify(api, payload.notification_seq, payload.is_filtered === true, false)
973
+ }),
974
+ defineMilkyAction({
975
+ name: "accept_group_invitation",
976
+ schema: invitationSchema,
977
+ handle: async (payload) => respondGroupNotify(api, payload.invitation_seq, false, true)
978
+ }),
979
+ defineMilkyAction({
980
+ name: "reject_group_invitation",
981
+ schema: invitationSchema,
982
+ handle: async (payload) => respondGroupNotify(api, payload.invitation_seq, false, false)
983
+ })
984
+ ];
985
+ }
986
+ /** accept_group_request 入参(notification_type 仅 schema 校验)。 */
987
+ const respondRequestSchema = z.object({
988
+ notification_seq: z.number().int().min(0),
989
+ notification_type: z.enum(["join_request", "invited_join_request"]),
990
+ ...groupIdField,
991
+ is_filtered: optBool$1
992
+ });
993
+ /** reject_group_request 入参(reason 无源)。 */
994
+ const rejectRequestSchema = z.object({
995
+ notification_seq: z.number().int().min(0),
996
+ notification_type: z.enum(["join_request", "invited_join_request"]),
997
+ ...groupIdField,
998
+ is_filtered: optBool$1,
999
+ reason: optStr
1000
+ });
1001
+ /** accept/reject_group_invitation 入参。 */
1002
+ const invitationSchema = z.object({
1003
+ ...groupIdField,
1004
+ invitation_seq: z.number().int().min(0)
1005
+ });
1006
+ /** 应答公共路径:seq → 通知匹配 → handleGroupRequest。 */
1007
+ async function respondGroupNotify(api, seq, doubt, approve) {
1008
+ const notify = await findGroupNotify(api, String(seq));
1009
+ await api.groupNotifyApi.handleGroupRequest(doubt, notify, approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE, " ");
1010
+ return {};
1011
+ }
1012
+ /** 通知 user1/user2 uid → uin 批量转换(失败退空 Map,实体 id 兜底 0)。 */
1013
+ async function collectUidToUin$1(api, notifies) {
1014
+ const uids = collectNotifyUids(notifies);
1015
+ if (uids.length === 0) return /* @__PURE__ */ new Map();
1016
+ return await api.uidToUin(uids).catch((err) => {
1017
+ api.logger?.warn({
1018
+ count: uids.length,
1019
+ error: err instanceof Error ? err.message : String(err)
1020
+ }, "milky: 通知 uid→uin 失败,实体 id 兜底 0");
1021
+ return /* @__PURE__ */ new Map();
1022
+ });
1023
+ }
885
1024
  /**
886
1025
  * GroupNotify → GroupNotificationEntity(uidToUin 已由调用方批量转换)。
887
1026
  * 类型→构造器表:7=入群申请 / 5=成员邀请他人 / 8=设管理 / 12,13=取消管理 /
@@ -918,192 +1057,40 @@ const NOTIFY_ENTITY_BUILDERS = {
918
1057
  notification_seq: Number(n.seq),
919
1058
  target_user_id: uinOf(n.user1?.uid)
920
1059
  })
921
- };
922
- /** admin_change 实体(8/12/13 共用)。 */
923
- function adminChangeEntity(n, uinOf, isSet) {
924
- return {
925
- type: "admin_change",
926
- group_id: Number(n.group?.groupCode ?? 0),
927
- notification_seq: Number(n.seq),
928
- target_user_id: uinOf(n.user1?.uid),
929
- is_set: isSet,
930
- operator_id: uinOf(n.user2?.uid)
931
- };
932
- }
933
- /** kick 实体(9/10 共用)。 */
934
- function kickEntity(n, uinOf) {
935
- return {
936
- type: "kick",
937
- group_id: Number(n.group?.groupCode ?? 0),
938
- notification_seq: Number(n.seq),
939
- target_user_id: uinOf(n.user1?.uid),
940
- operator_id: uinOf(n.user2?.uid)
941
- };
942
- }
943
- /** GroupNotify → 实体(isFiltered 透传给 join_request;未识别类型 null)。 */
944
- function notifyToEntity(notify, isFiltered, uidToUin) {
945
- const uinOf = (uid) => uid === void 0 || uid === "" ? 0 : Number(uidToUin.get(uid) ?? 0) || 0;
946
- const builder = NOTIFY_ENTITY_BUILDERS[notify.type];
947
- if (builder === void 0) return null;
948
- const entity = builder(notify, uinOf);
949
- if (entity.type === "join_request") entity.is_filtered = isFiltered;
950
- return entity;
951
- }
952
- // src/milky/helper/message/entities.ts
953
- /** GroupDetailInfo / Group → GroupEntity(detail 缺失时全兜底)。 */
954
- function toGroupEntity(detail, groupCode) {
955
- return {
956
- group_id: Number(groupCode),
957
- group_name: detail?.groupName ?? "",
958
- member_count: detail?.memberNum ?? 0,
959
- max_member_count: detail?.maxMemberNum ?? 0,
960
- remark: detail?.remarkName ?? "",
961
- created_time: detail?.groupCreateTime ?? 0,
962
- description: "",
963
- question: "",
964
- announcement: ""
965
- };
966
- }
967
- /** 群列表项(GroupCache Group)→ GroupEntity。 */
968
- function groupListToEntity(group) {
969
- return {
970
- group_id: Number(group.groupCode),
971
- group_name: group.groupName,
972
- member_count: group.memberCount,
973
- max_member_count: group.maxMember,
974
- remark: "",
975
- created_time: 0,
976
- description: "",
977
- question: "",
978
- announcement: ""
979
- };
980
- }
981
- /** GroupMember → GroupMemberEntity(member 缺失时按 uin 兜底最小实体)。 */
982
- function toGroupMemberEntity(member, groupCode, uin) {
983
- const shutUpSeconds = member?.shutUpTime ?? 0;
984
- return {
985
- user_id: Number(member?.uin !== void 0 && member.uin !== "" ? member.uin : uin),
986
- nickname: member?.nick ?? "",
987
- sex: "unknown",
988
- group_id: Number(groupCode),
989
- card: member?.cardName ?? "",
990
- title: member?.memberSpecialTitle ?? "",
991
- level: 0,
992
- role: GroupApi.roleToString(member?.role ?? 2),
993
- join_time: Number(member?.joinTime) || 0,
994
- last_sent_time: Number(member?.lastSpeakTime) || 0,
995
- shut_up_end_time: shutUpSeconds > 0 ? Math.floor(Date.now() / 1e3) + shutUpSeconds : null
996
- };
997
- }
998
- /** Friend → FriendEntity(kernel 无 qid/分类挂载,按最小实体兜底)。 */
999
- function toFriendEntity(friend, uin, nick) {
1060
+ };
1061
+ /** admin_change 实体(8/12/13 共用)。 */
1062
+ function adminChangeEntity(n, uinOf, isSet) {
1000
1063
  return {
1001
- user_id: Number(friend?.uin !== void 0 && friend.uin !== "" ? friend.uin : uin),
1002
- nickname: friend?.nickname ?? nick,
1003
- sex: "unknown",
1004
- qid: "",
1005
- remark: friend?.remark ?? "",
1006
- category: {
1007
- category_id: 0,
1008
- category_name: ""
1009
- }
1064
+ type: "admin_change",
1065
+ group_id: Number(n.group?.groupCode ?? 0),
1066
+ notification_seq: Number(n.seq),
1067
+ target_user_id: uinOf(n.user1?.uid),
1068
+ is_set: isSet,
1069
+ operator_id: uinOf(n.user2?.uid)
1010
1070
  };
1011
1071
  }
1012
- // src/milky/action/group-query.ts
1013
- const groupIdField = { group_id: z.number().int().min(10001) };
1014
- const userIdField = { user_id: z.number().int().min(10001) };
1015
- const optBool = z.boolean().nullable().optional();
1016
- /** get_group_info:获取群信息(GroupCache 详情缓存优先)。 */
1017
- var GetGroupInfoAction = class extends MilkyApiAction {
1018
- name = "get_group_info";
1019
- schema = z.object({
1020
- ...groupIdField,
1021
- no_cache: optBool
1022
- });
1023
- async _handle(payload) {
1024
- const groupCode = String(payload.group_id);
1025
- return { group: toGroupEntity(this.api.groupCache !== void 0 ? await this.api.groupCache.getGroupDetail(groupCode) : await this.api.groupApi.getGroupInfo(groupCode), groupCode) };
1026
- }
1027
- };
1028
- /** get_group_member_list:获取群成员列表(GroupCache 惰性回填)。 */
1029
- var GetGroupMemberListAction = class extends MilkyApiAction {
1030
- name = "get_group_member_list";
1031
- schema = z.object({
1032
- ...groupIdField,
1033
- no_cache: optBool
1034
- });
1035
- async _handle(payload) {
1036
- return { members: (await membersOf(this.api, String(payload.group_id))).map((m) => toGroupMemberEntity(m, String(payload.group_id), m.uin)) };
1037
- }
1038
- };
1039
- /** get_group_member_info:获取群成员信息(user_id = uin → 成员单查)。 */
1040
- var GetGroupMemberInfoAction = class extends MilkyApiAction {
1041
- name = "get_group_member_info";
1042
- schema = z.object({
1043
- ...groupIdField,
1044
- ...userIdField,
1045
- no_cache: optBool
1046
- });
1047
- async _handle(payload) {
1048
- return { member: toGroupMemberEntity(await memberOf(this.api, payload.group_id, payload.user_id), String(payload.group_id), String(payload.user_id)) };
1049
- }
1050
- };
1051
- /** get_group_announcements:获取群公告列表(bulletin 形状待校准,宽松映射)。 */
1052
- var GetGroupAnnouncementsAction = class extends MilkyApiAction {
1053
- name = "get_group_announcements";
1054
- schema = z.object({ ...groupIdField });
1055
- async _handle(payload) {
1056
- const groupCode = String(payload.group_id);
1057
- const bulletins = await this.api.groupApi.getGroupAnnouncements(groupCode);
1058
- return { announcements: await Promise.all(bulletins.map((b) => bulletinToEntity(b, payload.group_id, this.api))) };
1059
- }
1060
- };
1061
- /** ---------- 内部辅助 ---------- */
1062
- /** 成员列表(GroupCache 优先,未装配直查)。 */
1063
- async function membersOf(api, groupCode) {
1064
- if (api.groupCache !== void 0) return await api.groupCache.getMembers(groupCode);
1065
- return await api.groupApi.getGroupMemberList(groupCode, true);
1066
- }
1067
- /** 成员单查(user_id = uin;缓存路径经 uid,直查路径按 uin 匹配)。 */
1068
- async function memberOf(api, groupId, userId) {
1069
- const groupCode = String(groupId);
1070
- const uin = String(userId);
1071
- if (api.groupCache !== void 0) {
1072
- const uid = await api.resolveUidFromUin(userId).catch(() => uin);
1073
- const member = await api.groupCache.getMember(groupCode, uid);
1074
- if (member === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
1075
- return member;
1076
- }
1077
- const hit = (await api.groupApi.getGroupMemberList(groupCode, true)).find((m) => m.uin === uin);
1078
- if (hit === void 0) throw kernelError(`成员 ${uin} 不在群 ${groupCode}`, "NOT_FOUND");
1079
- return hit;
1080
- }
1081
- /** GroupBulletin → 群公告实体(senderUid → uin 反查;无源字段兜底,待校准)。 */
1082
- async function bulletinToEntity(b, groupId, api) {
1072
+ /** kick 实体(9/10 共用)。 */
1073
+ function kickEntity(n, uinOf) {
1083
1074
  return {
1084
- group_id: groupId,
1085
- announcement_id: b.announcementId ?? "",
1086
- user_id: await senderUinOf(b, api),
1087
- time: Number(b.publishTime) || 0,
1088
- content: b.content ?? "",
1089
- image_url: picUrlOf(b)
1075
+ type: "kick",
1076
+ group_id: Number(n.group?.groupCode ?? 0),
1077
+ notification_seq: Number(n.seq),
1078
+ target_user_id: uinOf(n.user1?.uid),
1079
+ operator_id: uinOf(n.user2?.uid)
1090
1080
  };
1091
1081
  }
1092
- /** 公告发送者 uid → uin(缺省/转换失败 0 兜底)。 */
1093
- async function senderUinOf(b, api) {
1094
- const uid = b.senderUid;
1095
- if (typeof uid !== "string" || uid === "") return 0;
1096
- const uins = await api.uidToUin([uid]).catch(() => void 0);
1097
- return Number(uins?.get(uid)) || 0;
1098
- }
1099
- /** 公告图片 url(缺省 null)。 */
1100
- function picUrlOf(b) {
1101
- const url = b.pic?.url;
1102
- return typeof url === "string" && url !== "" ? url : null;
1082
+ /** GroupNotify → 实体(isFiltered 透传给 join_request;未识别类型 null)。 */
1083
+ function notifyToEntity(notify, isFiltered, uidToUin) {
1084
+ const uinOf = (uid) => uid === void 0 || uid === "" ? 0 : Number(uidToUin.get(uid) ?? 0) || 0;
1085
+ const builder = NOTIFY_ENTITY_BUILDERS[notify.type];
1086
+ if (builder === void 0) return null;
1087
+ const entity = builder(notify, uinOf);
1088
+ if (entity.type === "join_request") entity.is_filtered = isFiltered;
1089
+ return entity;
1103
1090
  }
1104
1091
  // src/milky/helper/message/segments.ts
1105
1092
  /**
1106
- * Milky 消息段 ↔ canonical 元素转换(纯函数,ADR-008)
1093
+ * Milky 消息段 ↔ canonical 元素转换(纯函数)
1107
1094
  *
1108
1095
  * 接收方向:canonical → IncomingSegment(规范 14 种中映射 12 种;market_face /
1109
1096
  * markdown 无 canonical 对应(MFACE/MARKDOWN 原始元素形状未探测),unknown 一律
@@ -1245,7 +1232,7 @@ function fileToIncoming(el) {
1245
1232
  };
1246
1233
  }
1247
1234
  /**
1248
- * 合并转发 → forward 段(P1)。
1235
+ * 合并转发 → forward 段。
1249
1236
  * 接收方向 canonical 不承载 MULTI_FORWARD(kernel toCanonicalElement 无此分支),
1250
1237
  * 由 adapter 从 RawMessage 提取 resId 后调用本函数经 ctx 注入(翻译保持纯函数)。
1251
1238
  * title 取 NT fileName(转发卡片标题语义)。
@@ -1286,7 +1273,7 @@ function rawToPayload(raw) {
1286
1273
  * OutgoingSegment 数组 → canonical 元素(同步映射;媒体 URI 解析与 at uin→uid
1287
1274
  * 由调用方在返回值上继续处理)。
1288
1275
  * forward 在此报错:顶层 forward 已由 sendMilkyMessage 分流到组装链(message.ts,
1289
- * P2 批次一),命中本分支 = forward 与其他段混发漏网或嵌套 forward(组装链内逐项
1276
+ *),命中本分支 = forward 与其他段混发漏网或嵌套 forward(组装链内逐项
1290
1277
  * 转换经过此处)——均显式拒绝。
1291
1278
  */
1292
1279
  function outgoingSegmentsToCanonical(segments) {
@@ -1382,9 +1369,9 @@ function fileUriToPath(uri) {
1382
1369
  }
1383
1370
  // src/milky/helper/event/translate.ts
1384
1371
  /**
1385
- * Milky 事件翻译(RawMessage → Milky 事件,纯函数,ADR-008)
1372
+ * Milky 事件翻译(RawMessage → Milky 事件,纯函数)
1386
1373
  *
1387
- * P0 事件两种:message_receive(onRecvMsg)/ message_recall(grayTip REVOKE)。
1374
+ * 事件两种:message_receive(onRecvMsg)/ message_recall(grayTip REVOKE)。
1388
1375
  * 实体与 reply 回填在广播路径异步取得后经 ctx 注入(翻译保持纯函数);
1389
1376
  * 撤回事件的 sender_id 取 RawMessage.senderUin(grayTip 系统消息的 sender
1390
1377
  * 即被撤回原消息的发送者,口径待真实事件校准)。
@@ -1496,137 +1483,173 @@ const peerMessageFields = {
1496
1483
  peer_id: z.number().int().min(10001),
1497
1484
  message_seq: z.number().int().min(0)
1498
1485
  };
1499
- /** get_message:获取单条消息(seq → msgId 反查 + 实体回填)。 */
1500
- var GetMessageAction = class extends MilkyApiAction {
1501
- name = "get_message";
1502
- schema = z.object({ ...peerMessageFields });
1503
- async _handle(payload) {
1504
- const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1505
- const msgId = await this.api.resolveMsgIdBySeq(peer, payload.message_seq, peer.chatType);
1506
- if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1507
- const [msg] = await this.api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
1508
- if (msg === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1509
- return { message: await this.translateWithEntities(payload.message_scene, peer, msg) };
1510
- }
1511
- /** 实体回填(group 场景 schema 要求完整实体)→ IncomingMessage。 */
1512
- async translateWithEntities(scene, peer, msg) {
1513
- const ctx = { selfUin: this.api.self.uin };
1514
- if (scene === "group") {
1515
- const [detail, member] = await Promise.all([this.api.groupCache?.getGroupDetail(peer.peerUid).catch(() => void 0), this.api.groupCache?.getMember(peer.peerUid, msg.senderUid).catch(() => void 0)]);
1516
- ctx.groupEntity = toGroupEntity(detail, peer.peerUid);
1517
- ctx.groupMemberEntity = toGroupMemberEntity(member, peer.peerUid, msg.senderUin);
1518
- }
1519
- return toMessageReceiveEvent(msg, ctx).data;
1520
- }
1521
- };
1522
1486
  /** 历史消息默认条数(规范 default 20)。 */
1523
1487
  const HISTORY_DEFAULT_LIMIT = 20;
1524
- /** get_history_messages:获取历史消息(start seq 锚点 → 原生翻页 → 升序输出)。 */
1525
- var GetHistoryMessagesAction = class extends MilkyApiAction {
1526
- name = "get_history_messages";
1527
- schema = z.object({
1528
- message_scene: z.enum([
1529
- "friend",
1530
- "group",
1531
- "temp"
1532
- ]),
1533
- peer_id: z.number().int().min(10001),
1534
- start_message_seq: z.number().int().min(0).nullable().optional(),
1535
- limit: z.number().int().min(0).nullable().optional()
1536
- });
1537
- async _handle(payload) {
1538
- const limit = payload.limit ?? HISTORY_DEFAULT_LIMIT;
1539
- const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1540
- const anchor = await this.resolveAnchor(peer, payload.start_message_seq);
1541
- const msgs = await this.api.msgApi.fetchMessages(peer, {
1542
- count: limit,
1543
- ...anchor !== void 0 ? { msgId: anchor } : {}
1544
- });
1545
- for (const m of msgs) this.api.seqIndex.record(m);
1546
- const groupData = payload.message_scene === "group" ? await this.loadGroupData(peer.peerUid) : null;
1547
- const ordered = [...msgs].reverse();
1548
- const messages = ordered.map((m) => this.translateHistoryMessage(m, peer.peerUid, groupData));
1549
- const hasMore = msgs.length >= limit;
1550
- const oldest = ordered[0];
1551
- return {
1552
- messages,
1553
- next_message_seq: hasMore && oldest !== void 0 ? Number(oldest.msgSeq) : null
1554
- };
1555
- }
1556
- /** start_message_seq → 锚点 msgId(给了 seq 却反查不到 = NOT_FOUND)。 */
1557
- async resolveAnchor(peer, startSeq) {
1558
- if (startSeq === void 0 || startSeq === null) return;
1559
- const msgId = await this.api.resolveMsgIdBySeq(peer, startSeq, peer.chatType);
1560
- if (msgId === void 0) throw kernelError(`起始消息 ${startSeq} 不存在`, "NOT_FOUND");
1561
- return msgId;
1562
- }
1563
- /** 群场景回填数据(详情 + 成员表;缓存未装配返回空数据)。 */
1564
- async loadGroupData(groupCode) {
1565
- if (this.api.groupCache === void 0) return {
1566
- detail: void 0,
1567
- members: /* @__PURE__ */ new Map()
1568
- };
1569
- const [detail, members] = await Promise.all([this.api.groupCache.getGroupDetail(groupCode).catch(() => void 0), this.api.groupCache.getMembers(groupCode).catch(() => [])]);
1570
- const memberByUid = /* @__PURE__ */ new Map();
1571
- for (const m of members) memberByUid.set(m.uid, m);
1572
- return {
1573
- detail,
1574
- members: memberByUid
1575
- };
1576
- }
1577
- /** 单条历史消息 → IncomingMessage(群场景注入实体,fail-soft)。 */
1578
- translateHistoryMessage(msg, peerUid, groupData) {
1579
- const ctx = { selfUin: this.api.self.uin };
1580
- if (groupData !== null) {
1581
- if (groupData.detail !== void 0) ctx.groupEntity = toGroupEntity(groupData.detail, peerUid);
1582
- const member = groupData.members.get(msg.senderUid);
1583
- if (member !== void 0) ctx.groupMemberEntity = toGroupMemberEntity(member, peerUid, msg.senderUin);
1584
- }
1585
- return toMessageReceiveEvent(msg, ctx).data;
1488
+ /** 消息查询域动作工厂(get_message / get_history_messages / get_forwarded_messages)。 */
1489
+ function createMessageQueryActions(api) {
1490
+ return [
1491
+ defineMilkyAction({
1492
+ name: "get_message",
1493
+ schema: z.object({ ...peerMessageFields }),
1494
+ handle: async (payload) => {
1495
+ const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
1496
+ const msgId = await api.resolveMsgIdBySeq(peer, payload.message_seq, peer.chatType);
1497
+ if (msgId === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1498
+ const [msg] = await api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
1499
+ if (msg === void 0) throw kernelError(`消息 ${payload.message_seq} 不存在`, "NOT_FOUND");
1500
+ return { message: await translateWithEntities(api, payload.message_scene, peer, msg) };
1501
+ }
1502
+ }),
1503
+ defineMilkyAction({
1504
+ name: "get_history_messages",
1505
+ schema: z.object({
1506
+ message_scene: z.enum([
1507
+ "friend",
1508
+ "group",
1509
+ "temp"
1510
+ ]),
1511
+ peer_id: z.number().int().min(10001),
1512
+ start_message_seq: z.number().int().min(0).nullable().optional(),
1513
+ limit: z.number().int().min(0).nullable().optional()
1514
+ }),
1515
+ handle: async (payload) => {
1516
+ const limit = payload.limit ?? HISTORY_DEFAULT_LIMIT;
1517
+ const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
1518
+ const anchor = await resolveAnchor(api, peer, payload.start_message_seq);
1519
+ const msgs = await api.msgApi.fetchMessages(peer, {
1520
+ count: limit,
1521
+ ...anchor !== void 0 ? { msgId: anchor } : {}
1522
+ });
1523
+ for (const m of msgs) api.seqIndex.record(m);
1524
+ const groupData = payload.message_scene === "group" ? await loadGroupData(api, peer.peerUid) : null;
1525
+ const ordered = [...msgs].reverse();
1526
+ const messages = ordered.map((m) => translateHistoryMessage(api, m, peer.peerUid, groupData));
1527
+ const hasMore = msgs.length >= limit;
1528
+ const oldest = ordered[0];
1529
+ return {
1530
+ messages,
1531
+ next_message_seq: hasMore && oldest !== void 0 ? Number(oldest.msgSeq) : null
1532
+ };
1533
+ }
1534
+ }),
1535
+ defineMilkyAction({
1536
+ name: "get_forwarded_messages",
1537
+ schema: z.object({ forward_id: z.string().min(1) }),
1538
+ handle: async (payload) => {
1539
+ const entry = api.seqIndex.resolveForward(payload.forward_id);
1540
+ if (entry === void 0) throw kernelError(`转发消息 ${payload.forward_id} 不存在(未登记)`, "NOT_FOUND");
1541
+ const peer = {
1542
+ chatType: entry.chatType,
1543
+ peerUid: entry.peerUid
1544
+ };
1545
+ const msgs = await api.msgApi.fetchForwardMessage(peer, entry.msgId);
1546
+ for (const m of msgs) api.seqIndex.record(m);
1547
+ const uidToUin = await collectUidToUin(api, msgs);
1548
+ const messages = [];
1549
+ for (const m of msgs) messages.push({
1550
+ message_seq: Number(m.msgSeq),
1551
+ sender_name: await senderNameOf(api, m),
1552
+ avatar_url: avatarUrlOf(m.senderUin),
1553
+ time: Math.floor(Number(m.msgTime) / 1e3),
1554
+ segments: receiveSegmentsOf(m, uidToUin)
1555
+ });
1556
+ return { messages };
1557
+ }
1558
+ })
1559
+ ];
1560
+ }
1561
+ /** ---------- 内部辅助 ---------- */
1562
+ /** 实体回填(group 场景 schema 要求完整实体)→ IncomingMessage。 */
1563
+ async function translateWithEntities(api, scene, peer, msg) {
1564
+ const ctx = { selfUin: api.self.uin };
1565
+ if (scene === "group") {
1566
+ const [detail, member] = await Promise.all([api.groupCache?.getGroupDetail(peer.peerUid).catch((err) => {
1567
+ api.logger?.warn({
1568
+ group: peer.peerUid,
1569
+ error: err instanceof Error ? err.message : String(err)
1570
+ }, "milky: 群详情缓存读取失败,实体回填退化");
1571
+ }), api.groupCache?.getMember(peer.peerUid, msg.senderUid).catch((err) => {
1572
+ api.logger?.debug({
1573
+ group: peer.peerUid,
1574
+ member: msg.senderUid,
1575
+ error: err instanceof Error ? err.message : String(err)
1576
+ }, "milky: 群成员缓存读取失败,实体回填退化");
1577
+ })]);
1578
+ ctx.groupEntity = toGroupEntity(detail, peer.peerUid);
1579
+ ctx.groupMemberEntity = toGroupMemberEntity(member, peer.peerUid, msg.senderUin);
1580
+ }
1581
+ return toMessageReceiveEvent(msg, ctx).data;
1582
+ }
1583
+ /** start_message_seq → 锚点 msgId(给了 seq 却反查不到 = NOT_FOUND)。 */
1584
+ async function resolveAnchor(api, peer, startSeq) {
1585
+ if (startSeq === void 0 || startSeq === null) return;
1586
+ const msgId = await api.resolveMsgIdBySeq(peer, startSeq, peer.chatType);
1587
+ if (msgId === void 0) throw kernelError(`起始消息 ${startSeq} 不存在`, "NOT_FOUND");
1588
+ return msgId;
1589
+ }
1590
+ /** 群场景回填数据(详情 + 成员表;缓存未装配返回空数据)。 */
1591
+ async function loadGroupData(api, groupCode) {
1592
+ if (api.groupCache === void 0) return {
1593
+ detail: void 0,
1594
+ members: /* @__PURE__ */ new Map()
1595
+ };
1596
+ const [detail, members] = await Promise.all([api.groupCache.getGroupDetail(groupCode).catch((err) => {
1597
+ api.logger?.warn({
1598
+ group: groupCode,
1599
+ error: err instanceof Error ? err.message : String(err)
1600
+ }, "milky: 群详情缓存读取失败,历史翻译退化");
1601
+ }), api.groupCache.getMembers(groupCode).catch((err) => {
1602
+ api.logger?.warn({
1603
+ group: groupCode,
1604
+ error: err instanceof Error ? err.message : String(err)
1605
+ }, "milky: 群成员表缓存读取失败,历史翻译退化");
1606
+ return [];
1607
+ })]);
1608
+ const memberByUid = /* @__PURE__ */ new Map();
1609
+ for (const m of members) memberByUid.set(m.uid, m);
1610
+ return {
1611
+ detail,
1612
+ members: memberByUid
1613
+ };
1614
+ }
1615
+ /** 单条历史消息 → IncomingMessage(群场景注入实体,fail-soft)。 */
1616
+ function translateHistoryMessage(api, msg, peerUid, groupData) {
1617
+ const ctx = { selfUin: api.self.uin };
1618
+ if (groupData !== null) {
1619
+ if (groupData.detail !== void 0) ctx.groupEntity = toGroupEntity(groupData.detail, peerUid);
1620
+ const member = groupData.members.get(msg.senderUid);
1621
+ if (member !== void 0) ctx.groupMemberEntity = toGroupMemberEntity(member, peerUid, msg.senderUin);
1586
1622
  }
1587
- };
1588
- /** get_forwarded_messages:获取合并转发内容(resId → 转发索引 → fetchForwardMessage)。 */
1589
- var GetForwardedMessagesAction = class extends MilkyApiAction {
1590
- name = "get_forwarded_messages";
1591
- schema = z.object({ forward_id: z.string().min(1) });
1592
- async _handle(payload) {
1593
- const entry = this.api.seqIndex.resolveForward(payload.forward_id);
1594
- if (entry === void 0) throw kernelError(`转发消息 ${payload.forward_id} 不存在(未登记)`, "NOT_FOUND");
1595
- const peer = {
1596
- chatType: entry.chatType,
1597
- peerUid: entry.peerUid
1598
- };
1599
- const msgs = await this.api.msgApi.fetchForwardMessage(peer, entry.msgId);
1600
- for (const m of msgs) this.api.seqIndex.record(m);
1601
- const uidToUin = await this.collectUidToUin(msgs);
1602
- const messages = [];
1603
- for (const m of msgs) messages.push({
1604
- message_seq: Number(m.msgSeq),
1605
- sender_name: await this.senderNameOf(m),
1606
- avatar_url: avatarUrlOf(m.senderUin),
1607
- time: Math.floor(Number(m.msgTime) / 1e3),
1608
- segments: receiveSegmentsOf(m, uidToUin)
1623
+ return toMessageReceiveEvent(msg, ctx).data;
1624
+ }
1625
+ /** at 段 uid → uin 批量转换(mention 翻译;失败退空 Map)。 */
1626
+ async function collectUidToUin(api, msgs) {
1627
+ const uids = /* @__PURE__ */ new Set();
1628
+ for (const m of msgs) for (const el of toCanonicalElements(m)) if (el.type === "at" && el.target !== "all") uids.add(el.target);
1629
+ if (uids.size === 0) return /* @__PURE__ */ new Map();
1630
+ return await api.uidToUin([...uids]).catch((err) => {
1631
+ api.logger?.warn({
1632
+ count: uids.size,
1633
+ error: err instanceof Error ? err.message : String(err)
1634
+ }, "milky: 历史 at uid→uin 失败,mention 段跳过");
1635
+ return /* @__PURE__ */ new Map();
1636
+ });
1637
+ }
1638
+ /** 发送者名(群场景成员缓存昵称/名片,失败退 uin 字符串)。 */
1639
+ async function senderNameOf(api, msg) {
1640
+ if (api.groupCache !== void 0 && msg.chatType === ChatType.GROUP) {
1641
+ const member = await api.groupCache.getMember(msg.peerUid, msg.senderUid).catch((err) => {
1642
+ api.logger?.debug({
1643
+ group: msg.peerUid,
1644
+ member: msg.senderUid,
1645
+ error: err instanceof Error ? err.message : String(err)
1646
+ }, "milky: 发送者成员缓存读取失败,退 uin 字符串");
1609
1647
  });
1610
- return { messages };
1611
- }
1612
- /** at 段 uid → uin 批量转换(mention 翻译;失败退空 Map)。 */
1613
- async collectUidToUin(msgs) {
1614
- const uids = /* @__PURE__ */ new Set();
1615
- for (const m of msgs) for (const el of toCanonicalElements(m)) if (el.type === "at" && el.target !== "all") uids.add(el.target);
1616
- if (uids.size === 0) return /* @__PURE__ */ new Map();
1617
- return await this.api.uidToUin([...uids]).catch(() => /* @__PURE__ */ new Map());
1618
- }
1619
- /** 发送者名(群场景成员缓存昵称/名片,失败退 uin 字符串)。 */
1620
- async senderNameOf(msg) {
1621
- if (this.api.groupCache !== void 0 && msg.chatType === ChatType.GROUP) {
1622
- const member = await this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch(() => void 0);
1623
- const name = member?.cardName !== void 0 && member.cardName !== "" ? member.cardName : member?.nick;
1624
- if (name !== void 0 && name !== "") return name;
1625
- }
1626
- return msg.senderUin;
1648
+ const name = member?.cardName !== void 0 && member.cardName !== "" ? member.cardName : member?.nick;
1649
+ if (name !== void 0 && name !== "") return name;
1627
1650
  }
1628
- };
1629
- /** ---------- 内部辅助 ---------- */
1651
+ return msg.senderUin;
1652
+ }
1630
1653
  /** 单条消息 → 接收段(canonical 映射 + forward 段注入,forward 不经 canonical)。 */
1631
1654
  function receiveSegmentsOf(msg, uidToUin) {
1632
1655
  const segments = canonicalToIncomingSegments(toCanonicalElements(msg), { ...uidToUin.size > 0 ? { uidToUin } : {} });
@@ -1640,86 +1663,75 @@ function avatarUrlOf(uin) {
1640
1663
  }
1641
1664
  // src/milky/action/message-ops.ts
1642
1665
  const recallFields = { message_seq: z.number().int().min(0) };
1643
- /** recall_private_message:撤回私聊消息。 */
1644
- var RecallPrivateMessageAction = class extends MilkyApiAction {
1645
- name = "recall_private_message";
1646
- schema = z.object({
1647
- user_id: z.number().int().min(10001),
1648
- ...recallFields
1649
- });
1650
- async _handle(payload) {
1651
- await recallBySeq(await this.api.resolvePeer("friend", payload.user_id), payload.message_seq, this.api);
1652
- return {};
1653
- }
1654
- };
1655
- /** recall_group_message:撤回群消息。 */
1656
- var RecallGroupMessageAction = class extends MilkyApiAction {
1657
- name = "recall_group_message";
1658
- schema = z.object({
1659
- group_id: z.number().int().min(10001),
1660
- ...recallFields
1661
- });
1662
- async _handle(payload) {
1663
- await recallBySeq(await this.api.resolvePeer("group", payload.group_id), payload.message_seq, this.api);
1664
- return {};
1665
- }
1666
- };
1666
+ /** 消息操作域动作工厂(recall×2 / mark_read / 收藏表情 / 资源反查 / 私聊文件上传)。 */
1667
+ function createMessageOpsActions(api) {
1668
+ return [
1669
+ defineMilkyAction({
1670
+ name: "recall_private_message",
1671
+ schema: z.object({
1672
+ user_id: z.number().int().min(10001),
1673
+ ...recallFields
1674
+ }),
1675
+ handle: async (payload) => {
1676
+ await recallBySeq(await api.resolvePeer("friend", payload.user_id), payload.message_seq, api);
1677
+ return {};
1678
+ }
1679
+ }),
1680
+ defineMilkyAction({
1681
+ name: "recall_group_message",
1682
+ schema: z.object({
1683
+ group_id: z.number().int().min(10001),
1684
+ ...recallFields
1685
+ }),
1686
+ handle: async (payload) => {
1687
+ await recallBySeq(await api.resolvePeer("group", payload.group_id), payload.message_seq, api);
1688
+ return {};
1689
+ }
1690
+ }),
1691
+ defineMilkyAction({
1692
+ name: "mark_message_as_read",
1693
+ schema: z.object({ ...peerMessageFields }),
1694
+ handle: async (payload) => {
1695
+ const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
1696
+ await api.msgApi.markRead(peer);
1697
+ return {};
1698
+ }
1699
+ }),
1700
+ defineMilkyAction({
1701
+ name: "get_custom_face_url_list",
1702
+ schema: z.object({}),
1703
+ handle: async () => ({ urls: await api.msgApi.queryFavEmojis() })
1704
+ }),
1705
+ defineMilkyAction({
1706
+ name: "get_resource_temp_url",
1707
+ schema: z.object({ resource_id: z.string().min(1) }),
1708
+ handle: async (payload) => {
1709
+ const id = payload.resource_id;
1710
+ if (id.startsWith("http://") || id.startsWith("https://") || id.startsWith("base64://")) return { url: id };
1711
+ throw kernelError(`资源 ${id} 无临时链接(resource_id 非链接形态)`, "NOT_FOUND");
1712
+ }
1713
+ }),
1714
+ defineMilkyAction({
1715
+ name: "upload_private_file",
1716
+ schema: z.object({
1717
+ user_id: z.number().int().min(10001),
1718
+ file_uri: z.string().min(1),
1719
+ file_name: z.string().min(1)
1720
+ }),
1721
+ handle: async (payload) => {
1722
+ const path = await resolveUriToPath(payload.file_uri, api.mediaDir);
1723
+ const peer = await api.resolvePeer("friend", payload.user_id);
1724
+ return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1725
+ }
1726
+ })
1727
+ ];
1728
+ }
1667
1729
  /** seq → msgId(反查)→ recallMessage。 */
1668
1730
  async function recallBySeq(peer, seq, api) {
1669
1731
  const msgId = await api.resolveMsgIdBySeq(peer, seq, peer.chatType);
1670
1732
  if (msgId === void 0) throw kernelError(`消息 ${seq} 不存在`, "NOT_FOUND");
1671
1733
  await api.msgApi.recallMessage(peer, [msgId]);
1672
1734
  }
1673
- /** mark_message_as_read:标记会话已读(NT setMsgRead 以会话为粒度,seq 入参仅兼容 schema)。 */
1674
- var MarkMessageAsReadAction = class extends MilkyApiAction {
1675
- name = "mark_message_as_read";
1676
- schema = z.object({ ...peerMessageFields });
1677
- async _handle(payload) {
1678
- const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
1679
- await this.api.msgApi.markRead(peer);
1680
- return {};
1681
- }
1682
- };
1683
- /** get_custom_face_url_list:收藏表情链接(queryFavEmojiByDesc 形状待校准)。 */
1684
- var GetCustomFaceUrlListAction = class extends MilkyApiAction {
1685
- name = "get_custom_face_url_list";
1686
- schema = z.object({});
1687
- async _handle() {
1688
- return { urls: await this.api.msgApi.queryFavEmojis() };
1689
- }
1690
- };
1691
- /**
1692
- * get_resource_temp_url:资源临时链接。
1693
- * 已知差异(P0 模型):接收段 resource_id 即临时链接(本地路径优先 url 兜底),
1694
- * 无独立资源索引——http(s)/base64 形态原样返回,其余 NOT_FOUND。
1695
- */
1696
- var GetResourceTempUrlAction = class extends MilkyApiAction {
1697
- name = "get_resource_temp_url";
1698
- schema = z.object({ resource_id: z.string().min(1) });
1699
- async _handle(payload) {
1700
- const id = payload.resource_id;
1701
- if (id.startsWith("http://") || id.startsWith("https://") || id.startsWith("base64://")) return { url: id };
1702
- throw kernelError(`资源 ${id} 无临时链接(resource_id 非链接形态)`, "NOT_FOUND");
1703
- }
1704
- };
1705
- /**
1706
- * upload_private_file:上传并投递私聊文件(**闪传通道**:分享链接卡片)。
1707
- * file_id 返回闪传文件集 id(非文件消息 fileUuid)。语义降级同 upload_group_file:
1708
- * 对端收到的是分享链接卡片而不是 fileElement 文件消息(kernel design §15)。
1709
- */
1710
- var UploadPrivateFileAction = class extends MilkyApiAction {
1711
- name = "upload_private_file";
1712
- schema = z.object({
1713
- user_id: z.number().int().min(10001),
1714
- file_uri: z.string().min(1),
1715
- file_name: z.string().min(1)
1716
- });
1717
- async _handle(payload) {
1718
- const path = await resolveUriToPath(payload.file_uri, this.api.mediaDir);
1719
- const peer = await this.api.resolvePeer("friend", payload.user_id);
1720
- return { file_id: (await this.api.flashTransferApi.sendFile(peer, [path], { name: payload.file_name })).fileSetId };
1721
- }
1722
- };
1723
1735
  // src/milky/action/message-send.ts
1724
1736
  /**
1725
1737
  * OutgoingSegment 宽松校验:入口只保证「{type, data}」形状,字段级转换在
@@ -1730,31 +1742,31 @@ const outgoingSegmentSchema = z.object({
1730
1742
  data: z.record(z.string(), z.unknown())
1731
1743
  }).loose();
1732
1744
  const sendMessageFields = { message: z.array(outgoingSegmentSchema).min(1).max(200) };
1733
- /** send_private_message:发送私聊消息。 */
1734
- var SendPrivateMessageAction = class extends MilkyApiAction {
1735
- name = "send_private_message";
1736
- schema = z.object({
1737
- user_id: z.number().int().min(10001),
1738
- ...sendMessageFields
1739
- });
1740
- async _handle(payload) {
1741
- return await sendMilkyMessage(await this.api.resolvePeer("friend", payload.user_id), payload.message, this.api);
1742
- }
1743
- };
1744
- /** send_group_message:发送群聊消息。 */
1745
- var SendGroupMessageAction = class extends MilkyApiAction {
1746
- name = "send_group_message";
1747
- schema = z.object({
1748
- group_id: z.number().int().min(10001),
1749
- ...sendMessageFields
1750
- });
1751
- async _handle(payload) {
1752
- return await sendMilkyMessage(await this.api.resolvePeer("group", payload.group_id), payload.message, this.api);
1753
- }
1754
- };
1745
+ /** 消息发送域动作工厂(send_private_message / send_group_message)。 */
1746
+ function createMessageSendActions(api) {
1747
+ return [defineMilkyAction({
1748
+ name: "send_private_message",
1749
+ schema: z.object({
1750
+ user_id: z.number().int().min(10001),
1751
+ ...sendMessageFields
1752
+ }),
1753
+ handle: async (payload) => {
1754
+ return await sendMilkyMessage(await api.resolvePeer("friend", payload.user_id), payload.message, api);
1755
+ }
1756
+ }), defineMilkyAction({
1757
+ name: "send_group_message",
1758
+ schema: z.object({
1759
+ group_id: z.number().int().min(10001),
1760
+ ...sendMessageFields
1761
+ }),
1762
+ handle: async (payload) => {
1763
+ return await sendMilkyMessage(await api.resolvePeer("group", payload.group_id), payload.message, api);
1764
+ }
1765
+ })];
1766
+ }
1755
1767
  /** ---------- 发送核心与组装链 ---------- */
1756
1768
  /** 发送核心:segments → canonical(URI/ID 转换)→ sendMessage → 回查输出。
1757
- * forward 段分流到组装链(P2 批次一,临时消息法)。 */
1769
+ * forward 段分流到组装链(临时消息法)。 */
1758
1770
  async function sendMilkyMessage(peer, segments, api) {
1759
1771
  if (segments.some((s) => s.type === "forward")) return await sendForwardComposition(peer, segments, api);
1760
1772
  const { elements, atUins } = outgoingSegmentsToCanonical(segments);
@@ -1764,7 +1776,7 @@ async function sendMilkyMessage(peer, segments, api) {
1764
1776
  return await api.resolveSentOutput(peer, msgId);
1765
1777
  }
1766
1778
  /**
1767
- * forward 段组装链(P2 批次一,milky.md §0.6):仅支持单 forward 单独发。
1779
+ * forward 段组装链(milky.md §0.6):仅支持单 forward 单独发。
1768
1780
  * 临时消息法:逐条发送 messages[i].segments → sendForwardMessage(buildMultiForwardMsg
1769
1781
  * 以目标 peer 的真实消息组装 → sendMsg)→ best-effort 撤回临时消息 → 回查输出。
1770
1782
  *
@@ -1830,7 +1842,11 @@ async function resolveAtUins(atUins, api) {
1830
1842
  if (atUins.length === 0) return;
1831
1843
  try {
1832
1844
  return await api.uinToUid(atUins);
1833
- } catch {
1845
+ } catch (err) {
1846
+ api.logger?.warn({
1847
+ count: atUins.length,
1848
+ error: err instanceof Error ? err.message : String(err)
1849
+ }, "milky: at uin→uid 失败,at 段原样发送");
1834
1850
  return;
1835
1851
  }
1836
1852
  }
@@ -1855,8 +1871,8 @@ function isRemoteMediaUri(el) {
1855
1871
  }
1856
1872
  // src/milky/action/profile.ts
1857
1873
  /**
1858
- * Milky 资料类动作(P1):get_user_profile / get_friend_info / set_avatar /
1859
- * set_nickname / set_bio / get_cookies / get_csrf_token
1874
+ * Milky 资料类动作:get_user_profile / get_friend_info / set_avatar /
1875
+ * set_nickname / set_bio / get_cookies / get_csrf_token。
1860
1876
  *
1861
1877
  * set_avatar 的 uri 经 media-uri 解析(本地路径 / file:// 直用,http(s)/base64
1862
1878
  * 落盘 mediaDir);get_cookies 输出规范为单字符串(k=v 分号拼接);
@@ -1864,236 +1880,229 @@ function isRemoteMediaUri(el) {
1864
1880
  */
1865
1881
  /** CSRF 计算域名(bkn 口径,OB11 get_csrf_token 同源)。 */
1866
1882
  const CSRF_DOMAIN = "qun.qq.com";
1867
- /** get_user_profile:获取用户个人信息(陌生人信息 API;country/city/school 无源空兜底)。 */
1868
- var GetUserProfileAction = class extends MilkyApiAction {
1869
- name = "get_user_profile";
1870
- schema = z.object({ user_id: z.number().int().min(10001) });
1871
- async _handle(payload) {
1872
- const info = await this.api.profileApi.getStrangerInfo(String(payload.user_id));
1873
- return {
1874
- nickname: info.nickname,
1875
- qid: info.qid,
1876
- age: info.age,
1877
- sex: info.sex,
1878
- remark: info.remark,
1879
- bio: info.long_nick,
1880
- level: info.qq_level,
1881
- country: "",
1882
- city: "",
1883
- school: ""
1884
- };
1885
- }
1886
- };
1887
- /** get_friend_info:获取好友信息(好友列表单查)。 */
1888
- var GetFriendInfoAction = class extends MilkyApiAction {
1889
- name = "get_friend_info";
1890
- schema = z.object({
1891
- user_id: z.number().int().min(10001),
1892
- no_cache: z.boolean().nullable().optional()
1893
- });
1894
- async _handle(payload) {
1895
- const uin = String(payload.user_id);
1896
- const friend = (await this.api.friendApi.getFriendList()).find((f) => f.uin === uin);
1897
- if (friend === void 0) throw kernelError(`好友 ${uin} 不存在`, "NOT_FOUND");
1898
- return { friend: toFriendEntity(friend, friend.uin, friend.nickname) };
1899
- }
1900
- };
1901
- /** set_avatar:设置头像(uri → 本地路径)。 */
1902
- var SetAvatarAction = class extends MilkyApiAction {
1903
- name = "set_avatar";
1904
- schema = z.object({ uri: z.string().min(1) });
1905
- async _handle(payload) {
1906
- const path = await resolveMediaUri(payload.uri, this.api.mediaDir);
1907
- await this.api.profileApi.setHeader(path);
1908
- return {};
1909
- }
1910
- };
1911
- /** set_nickname:设置昵称。 */
1912
- var SetNicknameAction = class extends MilkyApiAction {
1913
- name = "set_nickname";
1914
- schema = z.object({ new_nickname: z.string() });
1915
- async _handle(payload) {
1916
- await this.api.profileApi.setNickName(payload.new_nickname);
1917
- return {};
1918
- }
1919
- };
1920
- /** set_bio:设置个性签名。 */
1921
- var SetBioAction = class extends MilkyApiAction {
1922
- name = "set_bio";
1923
- schema = z.object({ new_bio: z.string() });
1924
- async _handle(payload) {
1925
- await this.api.profileApi.setLongNick(payload.new_bio);
1926
- return {};
1927
- }
1928
- };
1929
- /** get_cookies:获取 cookies(规范输出为 k=v 分号拼接字符串)。 */
1930
- var GetCookiesAction = class extends MilkyApiAction {
1931
- name = "get_cookies";
1932
- schema = z.object({ domain: z.string().min(1) });
1933
- async _handle(payload) {
1934
- const cookies = await this.api.ticketApi.getCookies(payload.domain, this.api.self.uin);
1935
- return { cookies: Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ") };
1936
- }
1937
- };
1938
- /** get_csrf_token:bkn(qun.qq.com skey 派生,OB11 get_csrf_token 同口径)。 */
1939
- var GetCSRFTokenAction = class extends MilkyApiAction {
1940
- name = "get_csrf_token";
1941
- schema = z.object({}).strict();
1942
- async _handle() {
1943
- const cookies = await this.api.ticketApi.getCookies(CSRF_DOMAIN, this.api.self.uin);
1944
- return { csrf_token: TicketApi.getBkn(cookies["skey"] ?? "") };
1945
- }
1946
- };
1883
+ /** 资料类动作工厂(资料读取 / 头像昵称签名设置 / cookies 与 bkn)。 */
1884
+ function createProfileActions(api) {
1885
+ return [
1886
+ defineMilkyAction({
1887
+ name: "get_user_profile",
1888
+ schema: z.object({ user_id: z.number().int().min(10001) }),
1889
+ handle: async (payload) => {
1890
+ const info = await api.profileApi.getStrangerInfo(String(payload.user_id));
1891
+ return {
1892
+ nickname: info.nickname,
1893
+ qid: info.qid,
1894
+ age: info.age,
1895
+ sex: info.sex,
1896
+ remark: info.remark,
1897
+ bio: info.long_nick,
1898
+ level: info.qq_level,
1899
+ country: "",
1900
+ city: "",
1901
+ school: ""
1902
+ };
1903
+ }
1904
+ }),
1905
+ defineMilkyAction({
1906
+ name: "get_friend_info",
1907
+ schema: z.object({
1908
+ user_id: z.number().int().min(10001),
1909
+ no_cache: z.boolean().nullable().optional()
1910
+ }),
1911
+ handle: async (payload) => {
1912
+ const uin = String(payload.user_id);
1913
+ const friend = (await api.friendApi.getFriendList()).find((f) => f.uin === uin);
1914
+ if (friend === void 0) throw kernelError(`好友 ${uin} 不存在`, "NOT_FOUND");
1915
+ return { friend: toFriendEntity(friend, friend.uin, friend.nickname) };
1916
+ }
1917
+ }),
1918
+ defineMilkyAction({
1919
+ name: "set_avatar",
1920
+ schema: z.object({ uri: z.string().min(1) }),
1921
+ handle: async (payload) => {
1922
+ const path = await resolveMediaUri(payload.uri, api.mediaDir);
1923
+ await api.profileApi.setHeader(path);
1924
+ return {};
1925
+ }
1926
+ }),
1927
+ defineMilkyAction({
1928
+ name: "set_nickname",
1929
+ schema: z.object({ new_nickname: z.string() }),
1930
+ handle: async (payload) => {
1931
+ await api.profileApi.setNickName(payload.new_nickname);
1932
+ return {};
1933
+ }
1934
+ }),
1935
+ defineMilkyAction({
1936
+ name: "set_bio",
1937
+ schema: z.object({ new_bio: z.string() }),
1938
+ handle: async (payload) => {
1939
+ await api.profileApi.setLongNick(payload.new_bio);
1940
+ return {};
1941
+ }
1942
+ }),
1943
+ defineMilkyAction({
1944
+ name: "get_cookies",
1945
+ schema: z.object({ domain: z.string().min(1) }),
1946
+ handle: async (payload) => {
1947
+ const cookies = await api.ticketApi.getCookies(payload.domain, api.self.uin);
1948
+ return { cookies: Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ") };
1949
+ }
1950
+ }),
1951
+ defineMilkyAction({
1952
+ name: "get_csrf_token",
1953
+ schema: z.object({}).strict(),
1954
+ handle: async () => {
1955
+ const cookies = await api.ticketApi.getCookies(CSRF_DOMAIN, api.self.uin);
1956
+ return { csrf_token: TicketApi.getBkn(cookies["skey"] ?? "") };
1957
+ }
1958
+ })
1959
+ ];
1960
+ }
1947
1961
  // src/milky/action/social.ts
1948
- const emptySchema$1 = z.object({}).strict();
1949
- /** get_friend_list:获取好友列表。 */
1950
- var GetFriendListAction = class extends MilkyApiAction {
1951
- name = "get_friend_list";
1952
- schema = emptySchema$1;
1953
- async _handle() {
1954
- return { friends: (await this.api.friendApi.getFriendList()).map((f) => toFriendEntity(f, f.uin, f.nickname)) };
1955
- }
1956
- };
1957
- /** get_group_list:获取群列表。
1958
- * 实测校准(2026-08-08,OB11 同款):原生 getGroupList 返回值无数据,列表经
1959
- * onGroupListUpdate 事件进 GroupCache——缓存优先,为空触发刷新回填。
1960
- */
1961
- var GetGroupListAction = class extends MilkyApiAction {
1962
- name = "get_group_list";
1963
- schema = emptySchema$1;
1964
- async _handle() {
1965
- return { groups: (this.api.groupCache !== void 0 ? await this.api.groupCache.listGroupsRefreshed() : await this.api.groupApi.getGroupList(true)).map(groupListToEntity) };
1966
- }
1967
- };
1968
- /** send_profile_like:发送好友赞(count 缺省 1,规范 default 同值)。 */
1969
- var SendProfileLikeAction = class extends MilkyApiAction {
1970
- name = "send_profile_like";
1971
- schema = z.object({
1972
- user_id: z.number().int().min(10001),
1973
- count: z.number().int().min(0).nullable().optional()
1974
- });
1975
- async _handle(payload) {
1976
- const uid = await this.api.resolveUidFromUin(payload.user_id);
1977
- await this.api.profileLikeApi.sendLike(uid, payload.count ?? 1);
1978
- return {};
1979
- }
1980
- };
1981
- /** delete_friend:删除好友。 */
1982
- var DeleteFriendAction = class extends MilkyApiAction {
1983
- name = "delete_friend";
1984
- schema = z.object({ user_id: z.number().int().min(10001) });
1985
- async _handle(payload) {
1986
- const uid = await this.api.resolveUidFromUin(payload.user_id);
1987
- await this.api.friendApi.deleteFriend(uid);
1988
- return {};
1989
- }
1990
- };
1991
- /**
1992
- * get_friend_requests:获取好友请求列表。
1993
- * kernel getBuddyReqList 无过滤/数量参数——is_filtered 入参仅作 schema 兼容
1994
- * (全量返回);state 无源字段恒 pending(真实状态待探测校准)。
1995
- */
1996
- var GetFriendRequestsAction = class extends MilkyApiAction {
1997
- name = "get_friend_requests";
1998
- schema = z.object({
1999
- limit: z.number().int().min(0).nullable().optional(),
2000
- is_filtered: z.boolean().nullable().optional()
2001
- });
2002
- async _handle(payload) {
2003
- const reqs = await this.api.friendApi.getBuddyReqList();
2004
- let uidToUin = /* @__PURE__ */ new Map();
2005
- if (reqs.length > 0) uidToUin = await this.api.uidToUin(reqs.map((req) => req.friendUid)).catch(() => /* @__PURE__ */ new Map());
2006
- const requests = reqs.map((req) => ({
2007
- time: Number(req.reqTime) || 0,
2008
- initiator_id: Number(uidToUin.get(req.friendUid)) || 0,
2009
- initiator_uid: req.friendUid,
2010
- target_user_id: Number(this.api.self.uin),
2011
- target_user_uid: this.api.self.uid ?? "",
2012
- state: "pending",
2013
- comment: typeof req["words"] === "string" ? req["words"] : "",
2014
- via: req.sourceName ?? "",
2015
- is_filtered: false
2016
- }));
2017
- const limit = payload.limit ?? requests.length;
2018
- return { requests: requests.slice(0, limit) };
2019
- }
2020
- };
2021
- /**
2022
- * accept/reject_friend_request 公共基类:initiator_uid → 查申请 → 应答。
2023
- * kernel handleFriendRequest 无 reason 参数(拒绝理由无源,入参仅 schema 兼容)。
2024
- */
2025
- var HandleFriendRequestBase = class extends MilkyApiAction {
2026
- schema = z.object({
2027
- initiator_uid: z.string().min(1),
2028
- is_filtered: z.boolean().nullable().optional(),
2029
- reason: z.string().nullable().optional()
2030
- });
2031
- async _handle(payload) {
2032
- const notify = await findBuddyReq(this.api, payload.initiator_uid);
2033
- await this.api.friendApi.handleFriendRequest(notify, this.accept);
2034
- return {};
2035
- }
2036
- };
2037
- /** accept_friend_request:同意好友申请。 */
2038
- var AcceptFriendRequestAction = class extends HandleFriendRequestBase {
2039
- name = "accept_friend_request";
2040
- accept = true;
2041
- };
2042
- /** reject_friend_request:拒绝好友申请。 */
2043
- var RejectFriendRequestAction = class extends HandleFriendRequestBase {
2044
- name = "reject_friend_request";
2045
- accept = false;
2046
- };
2047
- /** send_friend_nudge:发送好友戳一戳(is_self=true 戳自己)。 */
2048
- var SendFriendNudgeAction = class extends MilkyApiAction {
2049
- name = "send_friend_nudge";
2050
- schema = z.object({
2051
- user_id: z.number().int().min(10001),
2052
- is_self: optBoolNudge
2053
- });
2054
- async _handle(payload) {
2055
- const callerUid = requireSelfUid(this.api);
2056
- const receiverUid = payload.is_self === true ? callerUid : await this.api.resolveUidFromUin(payload.user_id);
2057
- const peer = await this.api.resolvePeer("friend", payload.user_id);
2058
- await this.api.msgApi.sendNudge(peer, {
2059
- receiverUid,
2060
- callerUid
2061
- });
2062
- return {};
2063
- }
2064
- };
2065
- /** get_peer_pins:获取置顶会话(RecentContactApi isTop 过滤,实体经现有翻译)。 */
2066
- var GetPeerPinsAction = class extends MilkyApiAction {
2067
- name = "get_peer_pins";
2068
- schema = z.object({});
2069
- async _handle() {
2070
- const pinned = await this.api.recentContactApi.getPinnedContacts();
2071
- const friendUids = pinned.filter((p) => p.scene === "friend").map((p) => p.peerUid);
2072
- const groupCodes = pinned.filter((p) => p.scene === "group").map((p) => p.peerUid);
2073
- return {
2074
- friends: await pinnedFriendEntities(this.api, friendUids),
2075
- groups: await pinnedGroupEntities(this.api, groupCodes)
2076
- };
2077
- }
2078
- };
2079
- /** set_peer_pin:设置/取消会话置顶(is_pinned 缺省 true)。 */
2080
- var SetPeerPinAction = class extends MilkyApiAction {
2081
- name = "set_peer_pin";
2082
- schema = z.object({
2083
- message_scene: z.enum([
2084
- "friend",
2085
- "group",
2086
- "temp"
2087
- ]),
2088
- peer_id: z.number().int().min(10001),
2089
- is_pinned: optBoolNudge
2090
- });
2091
- async _handle(payload) {
2092
- const peer = await this.api.resolvePeer(payload.message_scene, payload.peer_id);
2093
- await this.api.msgApi.setContactTop(peer, payload.is_pinned ?? true);
2094
- return {};
2095
- }
2096
- };
1962
+ /** 可选布尔(nudge / pin 入参共用口径)。 */
1963
+ const optBool = z.boolean().nullable().optional();
1964
+ /** 社交类动作工厂(好友/群列表、赞、删好友、申请处理、戳一戳、会话置顶)。 */
1965
+ function createSocialActions(api) {
1966
+ return [
1967
+ defineMilkyAction({
1968
+ name: "get_friend_list",
1969
+ schema: z.object({}).strict(),
1970
+ handle: async () => {
1971
+ return { friends: (await api.friendApi.getFriendList()).map((f) => toFriendEntity(f, f.uin, f.nickname)) };
1972
+ }
1973
+ }),
1974
+ defineMilkyAction({
1975
+ name: "get_group_list",
1976
+ schema: z.object({}).strict(),
1977
+ handle: async () => {
1978
+ return { groups: (api.groupCache !== void 0 ? await api.groupCache.listGroupsRefreshed() : await api.groupApi.getGroupList(true)).map(groupListToEntity) };
1979
+ }
1980
+ }),
1981
+ defineMilkyAction({
1982
+ name: "send_profile_like",
1983
+ schema: z.object({
1984
+ user_id: z.number().int().min(10001),
1985
+ count: z.number().int().min(0).nullable().optional()
1986
+ }),
1987
+ handle: async (payload) => {
1988
+ const uid = await api.resolveUidFromUin(payload.user_id);
1989
+ await api.profileLikeApi.sendLike(uid, payload.count ?? 1);
1990
+ return {};
1991
+ }
1992
+ }),
1993
+ defineMilkyAction({
1994
+ name: "delete_friend",
1995
+ schema: z.object({ user_id: z.number().int().min(10001) }),
1996
+ handle: async (payload) => {
1997
+ const uid = await api.resolveUidFromUin(payload.user_id);
1998
+ await api.friendApi.deleteFriend(uid);
1999
+ return {};
2000
+ }
2001
+ }),
2002
+ defineMilkyAction({
2003
+ name: "get_friend_requests",
2004
+ schema: z.object({
2005
+ limit: z.number().int().min(0).nullable().optional(),
2006
+ is_filtered: z.boolean().nullable().optional()
2007
+ }),
2008
+ handle: async (payload) => {
2009
+ const reqs = await api.friendApi.getBuddyReqList();
2010
+ let uidToUin = /* @__PURE__ */ new Map();
2011
+ if (reqs.length > 0) uidToUin = await api.uidToUin(reqs.map((req) => req.friendUid)).catch((err) => {
2012
+ api.logger?.warn({
2013
+ count: reqs.length,
2014
+ error: err instanceof Error ? err.message : String(err)
2015
+ }, "milky: 好友申请 uid→uin 失败,initiator_id 兜底 0");
2016
+ return /* @__PURE__ */ new Map();
2017
+ });
2018
+ const requests = reqs.map((req) => ({
2019
+ time: Number(req.reqTime) || 0,
2020
+ initiator_id: Number(uidToUin.get(req.friendUid)) || 0,
2021
+ initiator_uid: req.friendUid,
2022
+ target_user_id: Number(api.self.uin),
2023
+ target_user_uid: api.self.uid ?? "",
2024
+ state: "pending",
2025
+ comment: typeof req["words"] === "string" ? req["words"] : "",
2026
+ via: req.sourceName ?? "",
2027
+ is_filtered: false
2028
+ }));
2029
+ const limit = payload.limit ?? requests.length;
2030
+ return { requests: requests.slice(0, limit) };
2031
+ }
2032
+ }),
2033
+ defineMilkyAction({
2034
+ name: "accept_friend_request",
2035
+ schema: friendRequestRespondSchema,
2036
+ handle: async (payload) => {
2037
+ const notify = await findBuddyReq(api, payload.initiator_uid);
2038
+ await api.friendApi.handleFriendRequest(notify, true);
2039
+ return {};
2040
+ }
2041
+ }),
2042
+ defineMilkyAction({
2043
+ name: "reject_friend_request",
2044
+ schema: friendRequestRespondSchema,
2045
+ handle: async (payload) => {
2046
+ const notify = await findBuddyReq(api, payload.initiator_uid);
2047
+ await api.friendApi.handleFriendRequest(notify, false);
2048
+ return {};
2049
+ }
2050
+ }),
2051
+ defineMilkyAction({
2052
+ name: "send_friend_nudge",
2053
+ schema: z.object({
2054
+ user_id: z.number().int().min(10001),
2055
+ is_self: optBool
2056
+ }),
2057
+ handle: async (payload) => {
2058
+ const callerUid = requireSelfUid(api);
2059
+ const receiverUid = payload.is_self === true ? callerUid : await api.resolveUidFromUin(payload.user_id);
2060
+ const peer = await api.resolvePeer("friend", payload.user_id);
2061
+ await api.msgApi.sendNudge(peer, {
2062
+ receiverUid,
2063
+ callerUid
2064
+ });
2065
+ return {};
2066
+ }
2067
+ }),
2068
+ defineMilkyAction({
2069
+ name: "get_peer_pins",
2070
+ schema: z.object({}),
2071
+ handle: async () => {
2072
+ const pinned = await api.recentContactApi.getPinnedContacts();
2073
+ const friendUids = pinned.filter((p) => p.scene === "friend").map((p) => p.peerUid);
2074
+ const groupCodes = pinned.filter((p) => p.scene === "group").map((p) => p.peerUid);
2075
+ return {
2076
+ friends: await pinnedFriendEntities(api, friendUids),
2077
+ groups: await pinnedGroupEntities(api, groupCodes)
2078
+ };
2079
+ }
2080
+ }),
2081
+ defineMilkyAction({
2082
+ name: "set_peer_pin",
2083
+ schema: z.object({
2084
+ message_scene: z.enum([
2085
+ "friend",
2086
+ "group",
2087
+ "temp"
2088
+ ]),
2089
+ peer_id: z.number().int().min(10001),
2090
+ is_pinned: optBool
2091
+ }),
2092
+ handle: async (payload) => {
2093
+ const peer = await api.resolvePeer(payload.message_scene, payload.peer_id);
2094
+ await api.msgApi.setContactTop(peer, payload.is_pinned ?? true);
2095
+ return {};
2096
+ }
2097
+ })
2098
+ ];
2099
+ }
2100
+ /** accept/reject_friend_request 共入参(is_filtered / reason 仅 schema 兼容)。 */
2101
+ const friendRequestRespondSchema = z.object({
2102
+ initiator_uid: z.string().min(1),
2103
+ is_filtered: z.boolean().nullable().optional(),
2104
+ reason: z.string().nullable().optional()
2105
+ });
2097
2106
  /** 置顶好友实体(uid 匹配全量好友列表;未命中跳过)。 */
2098
2107
  async function pinnedFriendEntities(api, uids) {
2099
2108
  if (uids.length === 0) return [];
@@ -2120,119 +2129,61 @@ function requireSelfUid(api) {
2120
2129
  if (uid === void 0 || uid === "") throw kernelError("登录身份缺 uid(无法发起戳一戳)", "INVALID_PARAM");
2121
2130
  return uid;
2122
2131
  }
2123
- /** 可选布尔(social.ts 本文件原无 optBool,本地定义避免全局重名)。 */
2124
- const optBoolNudge = z.boolean().nullable().optional();
2125
2132
  // src/milky/action/system.ts
2126
2133
  /**
2127
- * Milky 系统类动作(P0):get_login_info / get_impl_info
2134
+ * Milky 系统类动作:get_login_info / get_impl_info
2128
2135
  *
2129
2136
  * get_impl_info 是 Milky 的版本协商面(规范 §compatibility):milky_version
2130
2137
  * 固定 "1.3"(目标协议版本 1.3.0),qq_protocol_type 固定 windows(自建宿主)。
2131
2138
  */
2132
2139
  /** Milky 协议版本(docs/protocols/milky.md:目标 1.3.0)。 */
2133
2140
  const MILKY_VERSION = "1.3";
2134
- const emptySchema = z.object({}).strict();
2135
- /** get_login_info:获取登录信息。 */
2136
- var GetLoginInfoAction = class extends MilkyApiAction {
2137
- name = "get_login_info";
2138
- schema = emptySchema;
2139
- async _handle() {
2140
- return {
2141
- uin: Number(this.api.self.uin),
2142
- nickname: this.api.self.nickname
2143
- };
2144
- }
2145
- };
2146
- /** get_impl_info:获取协议端信息(版本协商)。 */
2147
- var GetImplInfoAction = class extends MilkyApiAction {
2148
- name = "get_impl_info";
2149
- schema = emptySchema;
2150
- async _handle() {
2151
- return {
2141
+ /** 系统类动作工厂(login_info / impl_info)。 */
2142
+ function createSystemActions(api) {
2143
+ return [defineMilkyAction({
2144
+ name: "get_login_info",
2145
+ schema: z.object({}).strict(),
2146
+ handle: async () => ({
2147
+ uin: Number(api.self.uin),
2148
+ nickname: api.self.nickname
2149
+ })
2150
+ }), defineMilkyAction({
2151
+ name: "get_impl_info",
2152
+ schema: z.object({}).strict(),
2153
+ handle: async () => ({
2152
2154
  impl_name: "napukettoqq",
2153
- impl_version: this.api.implVersion,
2154
- qq_protocol_version: this.api.qqVersion,
2155
+ impl_version: api.implVersion,
2156
+ qq_protocol_version: api.qqVersion,
2155
2157
  qq_protocol_type: "windows",
2156
2158
  milky_version: MILKY_VERSION
2157
- };
2158
- }
2159
- };
2159
+ })
2160
+ })];
2161
+ }
2160
2162
  // src/milky/action/index.ts
2161
2163
  /**
2162
- * Milky 动作注册表(P0 9 + P1 40 + P2 批次二 15 = 64 个)
2164
+ * Milky 动作注册表:动作按领域文件组织(每文件一个 create*Actions 工厂),
2165
+ * 本入口按固定顺序遍历注册——新增动作在领域文件的工厂里登记即可。
2163
2166
  *
2164
- * P0/P1 面 = docs/protocols/milky.md §9 清单;批次二 = §0.7(nudge / 公告 /
2165
- * 头衔 / 群头像 / peer_pins / 上传 / download_url / rename_folder / 收藏表情 /
2166
- * resource 反查)。
2167
+ * 64 动作 = docs/protocols/milky.md §9 清单全量。
2167
2168
  */
2168
- /** Milky 动作注册表(P0+P1 49 动作)。 */
2169
+ /** Milky 动作域工厂(注册顺序即列表顺序:system → message → social/profile → group)。 */
2170
+ const ACTION_FACTORIES = [
2171
+ createSystemActions,
2172
+ createMessageSendActions,
2173
+ createMessageQueryActions,
2174
+ createMessageOpsActions,
2175
+ createSocialActions,
2176
+ createProfileActions,
2177
+ createGroupQueryActions,
2178
+ createGroupManageActions,
2179
+ createGroupEssenceActions,
2180
+ createGroupNoticeActions,
2181
+ createGroupFileActions
2182
+ ];
2183
+ /** 构建 Milky 动作注册表(64 个动作,领域工厂遍历注册)。 */
2169
2184
  function createMilkyActionRegistry(opts) {
2170
2185
  const registry = new ActionRegistry();
2171
- const { api } = opts;
2172
- registry.register(new GetLoginInfoAction(api));
2173
- registry.register(new GetImplInfoAction(api));
2174
- registry.register(new SendPrivateMessageAction(api));
2175
- registry.register(new SendGroupMessageAction(api));
2176
- registry.register(new GetMessageAction(api));
2177
- registry.register(new RecallPrivateMessageAction(api));
2178
- registry.register(new RecallGroupMessageAction(api));
2179
- registry.register(new GetFriendListAction(api));
2180
- registry.register(new GetGroupListAction(api));
2181
- registry.register(new GetUserProfileAction(api));
2182
- registry.register(new GetFriendInfoAction(api));
2183
- registry.register(new SetAvatarAction(api));
2184
- registry.register(new SetNicknameAction(api));
2185
- registry.register(new SetBioAction(api));
2186
- registry.register(new GetCookiesAction(api));
2187
- registry.register(new GetCSRFTokenAction(api));
2188
- registry.register(new SendProfileLikeAction(api));
2189
- registry.register(new DeleteFriendAction(api));
2190
- registry.register(new GetFriendRequestsAction(api));
2191
- registry.register(new AcceptFriendRequestAction(api));
2192
- registry.register(new RejectFriendRequestAction(api));
2193
- registry.register(new GetHistoryMessagesAction(api));
2194
- registry.register(new GetForwardedMessagesAction(api));
2195
- registry.register(new MarkMessageAsReadAction(api));
2196
- registry.register(new GetGroupInfoAction(api));
2197
- registry.register(new GetGroupMemberListAction(api));
2198
- registry.register(new GetGroupMemberInfoAction(api));
2199
- registry.register(new SetGroupNameAction(api));
2200
- registry.register(new SetGroupMemberCardAction(api));
2201
- registry.register(new SetGroupMemberAdminAction(api));
2202
- registry.register(new SetGroupMemberMuteAction(api));
2203
- registry.register(new SetGroupWholeMuteAction(api));
2204
- registry.register(new KickGroupMemberAction(api));
2205
- registry.register(new QuitGroupAction(api));
2206
- registry.register(new GetGroupEssenceMessagesAction(api));
2207
- registry.register(new SetGroupEssenceMessageAction(api));
2208
- registry.register(new SendGroupMessageReactionAction(api));
2209
- registry.register(new GetGroupNotificationsAction(api));
2210
- registry.register(new AcceptGroupRequestAction(api));
2211
- registry.register(new RejectGroupRequestAction(api));
2212
- registry.register(new AcceptGroupInvitationAction(api));
2213
- registry.register(new RejectGroupInvitationAction(api));
2214
- registry.register(new GetGroupFilesAction(api));
2215
- registry.register(new MoveGroupFileAction(api));
2216
- registry.register(new RenameGroupFileAction(api));
2217
- registry.register(new DeleteGroupFileAction(api));
2218
- registry.register(new PersistGroupFileAction(api));
2219
- registry.register(new CreateGroupFolderAction(api));
2220
- registry.register(new DeleteGroupFolderAction(api));
2221
- registry.register(new SendFriendNudgeAction(api));
2222
- registry.register(new GetPeerPinsAction(api));
2223
- registry.register(new SetPeerPinAction(api));
2224
- registry.register(new SendGroupNudgeAction(api));
2225
- registry.register(new GetGroupAnnouncementsAction(api));
2226
- registry.register(new SendGroupAnnouncementAction(api));
2227
- registry.register(new DeleteGroupAnnouncementAction(api));
2228
- registry.register(new SetGroupAvatarAction(api));
2229
- registry.register(new SetGroupMemberSpecialTitleAction(api));
2230
- registry.register(new GetCustomFaceUrlListAction(api));
2231
- registry.register(new GetResourceTempUrlAction(api));
2232
- registry.register(new UploadPrivateFileAction(api));
2233
- registry.register(new UploadGroupFileAction(api));
2234
- registry.register(new GetGroupFileDownloadUrlAction(api));
2235
- registry.register(new RenameGroupFolderAction(api));
2186
+ for (const factory of ACTION_FACTORIES) for (const action of factory(opts.api)) registry.register(action);
2236
2187
  return registry;
2237
2188
  }
2238
2189
  // src/milky/enrichment.ts
@@ -2246,7 +2197,12 @@ var MilkyEnrichment = class {
2246
2197
  resolveUidToUin(uids) {
2247
2198
  const unique = [...new Set(uids.filter((uid) => uid !== ""))];
2248
2199
  if (unique.length === 0) return Promise.resolve(void 0);
2249
- return this.api.uidToUin(unique).catch(() => void 0);
2200
+ return this.api.uidToUin(unique).catch((err) => {
2201
+ this.api.logger?.warn({
2202
+ count: unique.length,
2203
+ error: err instanceof Error ? err.message : String(err)
2204
+ }, "milky: uid→uin 批量转换失败,事件退用 uid");
2205
+ });
2250
2206
  }
2251
2207
  /** at uid → uin 批量转换(mention.user_id 用;失败 mention 段跳过)。 */
2252
2208
  async fillMentionUids(elements, ctx) {
@@ -2254,12 +2210,28 @@ var MilkyEnrichment = class {
2254
2210
  if (atUids.length === 0) return;
2255
2211
  try {
2256
2212
  ctx.uidToUin = await this.api.uidToUin(atUids);
2257
- } catch {}
2213
+ } catch (err) {
2214
+ this.api.logger?.warn({
2215
+ count: atUids.length,
2216
+ error: err instanceof Error ? err.message : String(err)
2217
+ }, "milky: at uid→uin 失败,mention 段跳过");
2218
+ }
2258
2219
  }
2259
2220
  /** 群场景实体回填(GroupCache 缓存优先,失败最小实体兜底)。 */
2260
2221
  async fillGroupEntities(msg, ctx) {
2261
2222
  if (msg.chatType !== ChatType.GROUP || this.api.groupCache === void 0) return;
2262
- 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)]);
2223
+ const [detail, member] = await Promise.all([this.api.groupCache.getGroupDetail(msg.peerUid).catch((err) => {
2224
+ this.api.logger?.warn({
2225
+ group: msg.peerUid,
2226
+ error: err instanceof Error ? err.message : String(err)
2227
+ }, "milky: 群详情缓存读取失败,实体回填退化");
2228
+ }), this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch((err) => {
2229
+ this.api.logger?.debug({
2230
+ group: msg.peerUid,
2231
+ member: msg.senderUid,
2232
+ error: err instanceof Error ? err.message : String(err)
2233
+ }, "milky: 群成员缓存读取失败,实体回填退化");
2234
+ })]);
2263
2235
  ctx.groupEntity = toGroupEntity(detail, msg.peerUid);
2264
2236
  ctx.groupMemberEntity = toGroupMemberEntity(member, msg.peerUid, msg.senderUin);
2265
2237
  }
@@ -2271,13 +2243,21 @@ var MilkyEventPipeline = class {
2271
2243
  constructor(deps) {
2272
2244
  this.deps = deps;
2273
2245
  }
2274
- /** 订阅 kernel 事件(消息 + 群 + 好友 + 批次三,幂等;路由到 inbound/)。 */
2246
+ /** 事件链异步失败兜底(单条/整批丢弃,warn 留痕不打断订阅)。 */
2247
+ logFailure(kind, err) {
2248
+ logEventFailure(this.deps.logger, `milky: ${kind} 翻译失败(丢弃)`, err);
2249
+ }
2250
+ /** 订阅 kernel 事件(消息 + 群 + 好友 + ,幂等;路由到 inbound/)。 */
2275
2251
  subscribe() {
2276
2252
  if (this.unsubscribes.length > 0) return;
2277
2253
  const { msgChannel, groupChannel, buddyChannel, recentContactChannel, loginChannel } = this.deps;
2278
- this.unsubscribes.push(subscribeRawMessages(msgChannel, (msg) => void this.deps.message.handle(msg)), msgChannel.on("Msg/onRecvSysMsg", (a) => this.deps.sysMsg.handleRawArg(a)), msgChannel.on("Msg/onRecvOfflineFileMsg", (m) => this.deps.fileNotice.fileMessages(m)), msgChannel.on("Msg/onFileMsgCome", (m) => this.deps.fileNotice.fileMessages(m)));
2254
+ this.unsubscribes.push(subscribeRawMessages(msgChannel, (msg) => this.deps.message.handle(msg).catch((err) => {
2255
+ this.logFailure("message_receive", err);
2256
+ })), msgChannel.on("Msg/onRecvSysMsg", (a) => this.deps.sysMsg.handleRawArg(a)), msgChannel.on("Msg/onRecvOfflineFileMsg", (m) => this.deps.fileNotice.fileMessages(m)), msgChannel.on("Msg/onFileMsgCome", (m) => this.deps.fileNotice.fileMessages(m)));
2279
2257
  if (groupChannel !== void 0) this.unsubscribes.push(groupChannel.on("Group/onGroupNotifiesUpdated", (doubt, notifies) => {
2280
- this.deps.request.groupNotifies(doubt, notifies);
2258
+ this.deps.request.groupNotifies(doubt, notifies).catch((err) => {
2259
+ this.logFailure("group request", err);
2260
+ });
2281
2261
  }), groupChannel.on("Group/onGroupEssenceListChange", (a) => this.deps.essence.change(a)));
2282
2262
  if (buddyChannel !== void 0) this.unsubscribes.push(buddyChannel.on("Buddy/onBuddyReqChange", (a) => this.deps.request.buddyReqs(a)));
2283
2263
  if (recentContactChannel !== void 0) {
@@ -2306,7 +2286,7 @@ var MessageSeqIndex = class {
2306
2286
  seqToMsg = /* @__PURE__ */ new Map();
2307
2287
  /** msgId → seq 元信息。 */
2308
2288
  msgToMeta = /* @__PURE__ */ new Map();
2309
- /** 合并转发 resId → 定位信息(P1:get_forwarded_messages)。 */
2289
+ /** 合并转发 resId → 定位信息(get_forwarded_messages)。 */
2310
2290
  forwards = /* @__PURE__ */ new Map();
2311
2291
  /** 接收链路登记(一条消息双向写入;重复 msgId 覆盖)。 */
2312
2292
  record(msg) {
@@ -2377,7 +2357,7 @@ var MessageSeqIndex = class {
2377
2357
  };
2378
2358
  // src/milky/helper/state/recent-keys.ts
2379
2359
  /**
2380
- * 带过期去重键缓存(Milky 批次三)
2360
+ * 带过期去重键缓存(Milky)
2381
2361
  *
2382
2362
  * 两个场景共用:friend_file_upload 双回调(onRecvOfflineFileMsg / onFileMsgCome
2383
2363
  * 同载荷,按 msgId 去重)与 group_essence_message_change 双路径(732:1 快路径
@@ -2466,7 +2446,7 @@ var MilkyInboundEssence = class {
2466
2446
  };
2467
2447
  // src/milky/helper/event/file-upload.ts
2468
2448
  /**
2469
- * friend_file_upload 翻译(Milky 批次三,2026-11-01 录制定型)
2449
+ * friend_file_upload 翻译(Milky ,录制定型)
2470
2450
  *
2471
2451
  * 源:Msg/onRecvOfflineFileMsg 与 Msg/onFileMsgCome(同载荷 RawMessage 数组,
2472
2452
  * 双回调按 msgId 在适配器去重);fileElement{fileName, fileSize 字符串,
@@ -2494,13 +2474,13 @@ function toFriendFileUploadData(msg, selfUin, uidToUin) {
2494
2474
  }
2495
2475
  // src/milky/helper/event/peer-pin.ts
2496
2476
  /**
2497
- * peer_pin_change 翻译(Milky 批次三,RecentContact/onRecentContactListChangedVer2)
2477
+ * peer_pin_change 翻译(Milky ,RecentContact/onRecentContactListChangedVer2)
2498
2478
  *
2499
2479
  * 回调随消息活动高频快照(含 topFlag 的全量条目 + chatType=7 影子条目),
2500
2480
  * 不能见条目就广播——按「同会话 topFlag 前后值翻转」检测(PinWatch)。
2501
2481
  * 启动期以 getPinnedContacts 播种基线(重启后首个取消置顶也能观测到)。
2502
2482
  *
2503
- * 证据:2026-11-01 set_peer_pin 自触发翻转实验——changedList 条目
2483
+ * 证据:set_peer_pin 自触发翻转实验——changedList 条目
2504
2484
  * {chatType, peerUin, topFlag(1/0), topFlagTime(秒级 unix 字符串)},与操作
2505
2485
  * 一一对应(milky.md §0.8.6)。
2506
2486
  */
@@ -2554,7 +2534,7 @@ function toPeerPinChangeData(entry) {
2554
2534
  /** Milky 置顶域处理器(翻转检测 + 播种基线 + peer_pin_change 广播)。 */
2555
2535
  var MilkyInboundPin = class {
2556
2536
  deps;
2557
- /** peer_pin 翻转检测(批次三;启动期 getPinnedContacts 播种)。 */
2537
+ /** peer_pin 翻转检测(启动期 getPinnedContacts 播种)。 */
2558
2538
  pinWatch = new PinWatch();
2559
2539
  constructor(deps) {
2560
2540
  this.deps = deps;
@@ -2564,7 +2544,7 @@ var MilkyInboundPin = class {
2564
2544
  const arr = Array.isArray(lists) ? lists : [lists];
2565
2545
  for (const list of arr) for (const entry of changedListOf(list)) this.handleEntry(entry);
2566
2546
  }
2567
- /** 启动基线:置顶会话播种(2026-11-14 起失败补 debug 日志,不再静默)。 */
2547
+ /** 启动基线:置顶会话播种(失败补 debug 日志,不再静默)。 */
2568
2548
  seed() {
2569
2549
  this.deps.api.recentContactApi.getPinnedContacts().then((pins) => {
2570
2550
  this.pinWatch.seed(pins);
@@ -2881,7 +2861,7 @@ var MilkyInboundRequest = class {
2881
2861
  }
2882
2862
  /** 好友请求通道:Buddy/onBuddyReqChange(防御收窄,未知形状 raw 日志)。 */
2883
2863
  buddyReqs(arg) {
2884
- this.broadcastBuddyReqs(arg);
2864
+ this.broadcastBuddyReqs(arg).catch((err) => logEventFailure(this.deps.logger, "milky: friend request 翻译失败(整批丢弃)", err));
2885
2865
  }
2886
2866
  async broadcastBuddyReqs(arg) {
2887
2867
  const reqs = narrowBuddyReqs(arg);
@@ -2903,7 +2883,7 @@ var MilkyInboundRequest = class {
2903
2883
  };
2904
2884
  // src/milky/helper/event/sysmsg.ts
2905
2885
  /**
2906
- * Milky sysmsg 识别表(批次三,2026-11-01;识别机制共享自 core/sysmsg.ts)
2886
+ * Milky sysmsg 识别表(识别机制共享自 core/sysmsg.ts)
2907
2887
  *
2908
2888
  * 键 = 原生分发键 "msgType:subType",规则产出事件 data 体(信封 time/self_id/
2909
2889
  * event_type 由适配器统一包装)。路径依据 = 三轮录制 wire bytes 全量解码
@@ -3105,7 +3085,7 @@ function assembleMilkyTransports(opts) {
3105
3085
  const { config, broadcaster, registry, logger } = opts;
3106
3086
  const hub = new MilkyEventHub();
3107
3087
  const token = config.token;
3108
- const authorize = token !== "" ? makeMilkyAuthorize(token) : void 0;
3088
+ const authorize = token !== "" ? makeMilkyAuthorize(token, logger) : void 0;
3109
3089
  const server = new HttpServer({
3110
3090
  host: config.host,
3111
3091
  port: config.port,
@@ -3113,7 +3093,7 @@ function assembleMilkyTransports(opts) {
3113
3093
  });
3114
3094
  hub.attachTo(server, config);
3115
3095
  server.onPathRequest = (ctx, req, respond) => {
3116
- handleMilkyHttpRequest(ctx, req, respond, registry);
3096
+ handleMilkyHttpRequest(ctx, req, respond, registry, logger);
3117
3097
  };
3118
3098
  const adapters = [server, hub];
3119
3099
  for (const url of config.webhooks) {
@@ -3141,7 +3121,7 @@ function assembleMilkyTransports(opts) {
3141
3121
  };
3142
3122
  }
3143
3123
  /** HTTP /api 分发(规范信封 + 404/415 语义)。 */
3144
- function handleMilkyHttpRequest(ctx, req, respond, registry) {
3124
+ function handleMilkyHttpRequest(ctx, req, respond, registry, logger) {
3145
3125
  if (ctx.method !== "POST") {
3146
3126
  respond(void 0, 404);
3147
3127
  return;
@@ -3173,7 +3153,11 @@ function handleMilkyHttpRequest(ctx, req, respond, registry) {
3173
3153
  data: null,
3174
3154
  message: result.message
3175
3155
  });
3176
- }).catch(() => {
3156
+ }).catch((err) => {
3157
+ logger?.warn({
3158
+ path: ctx.path,
3159
+ error: err instanceof Error ? err.message : String(err)
3160
+ }, "milky: 动作分发异常,已回 -500");
3177
3161
  respond({
3178
3162
  status: "failed",
3179
3163
  retcode: -500,
@@ -3183,16 +3167,20 @@ function handleMilkyHttpRequest(ctx, req, respond, registry) {
3183
3167
  });
3184
3168
  }
3185
3169
  /** 鉴权钩子:Bearer 头或 access_token 查询参数(规范允许 SSE/WS 查询参数兜底)。 */
3186
- function makeMilkyAuthorize(token) {
3187
- return (ctx) => tokenMatches(ctx, token);
3170
+ function makeMilkyAuthorize(token, logger) {
3171
+ return (ctx) => tokenMatches(ctx, token, logger);
3188
3172
  }
3189
- /** 请求凭据匹配(头优先,查询参数兜底)。 */
3190
- function tokenMatches(ctx, token) {
3173
+ /** 请求凭据匹配(头优先,查询参数兜底;URL 解析失败 fail-closed 拒绝并 debug 留痕)。 */
3174
+ function tokenMatches(ctx, token, logger) {
3191
3175
  const auth = ctx.headers["authorization"] ?? ctx.headers["Authorization"];
3192
3176
  if (auth?.startsWith(BEARER_PREFIX)) return auth.slice(7) === token;
3193
3177
  try {
3194
3178
  return new URL(ctx.url, "http://localhost").searchParams.get("access_token") === token;
3195
- } catch {
3179
+ } catch (err) {
3180
+ logger?.debug({
3181
+ url: ctx.url,
3182
+ error: err instanceof Error ? err.message : String(err)
3183
+ }, "milky: 鉴权 URL 解析失败,按未授权拒绝");
3196
3184
  return false;
3197
3185
  }
3198
3186
  }
@@ -3213,7 +3201,7 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3213
3201
  seqIndex = new MessageSeqIndex();
3214
3202
  /** 动作注册表(公共只读:装配方/测试枚举)。 */
3215
3203
  registry;
3216
- /** 收链路事件管道(订阅 / 过滤 / 去重 / 翻译派发,2026-11-14 拆出)。 */
3204
+ /** 收链路事件管道(订阅 / 过滤 / 去重 / 翻译派发,拆出)。 */
3217
3205
  pipeline;
3218
3206
  stopTransports = null;
3219
3207
  constructor(opts) {
@@ -3256,7 +3244,8 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3256
3244
  enrich
3257
3245
  }),
3258
3246
  fileNotice: new MilkyInboundFileNotice(base),
3259
- pin: new MilkyInboundPin(base)
3247
+ pin: new MilkyInboundPin(base),
3248
+ logger: opts.logger
3260
3249
  });
3261
3250
  this.registry = createMilkyActionRegistry({ api: this.api });
3262
3251
  }
@@ -3300,7 +3289,7 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
3300
3289
  };
3301
3290
  // src/milky/config.ts
3302
3291
  /**
3303
- * Milky 协议配置(zod schema,归属本包,ADR-012)
3292
+ * Milky 协议配置(zod schema,归属本包)
3304
3293
  *
3305
3294
  * 单一 TOML 的 `[accounts.milky]` 账号段(docs/protocols/milky.md §4):
3306
3295
  * 单端口 HTTP 模型(/api + /event 同端口),`enabled` 缺省 false = 不启用。