@napuketto/adapter 0.14.2 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,9 @@
1
- import { S as ActionRegistry, a as extractSysMsgEnvelope, c as narrowSysMsgBlobs, d as textOf, f as toHex, l as nodeAt, m as varintOf, p as varintAt, r as decodeProtoTree, u as recognizeSysMsg, y as BaseProtocolAdapter } from "../core-CECIwO6s.mjs";
2
- import { a as MS_TO_SEC$2, i as narrowBuddyReqs, n as extractEssenceSetSysMsg, o as resolveUin, r as narrowEssenceGroupArg, t as diffEssenceList } from "../essence-Bdms4trk.mjs";
3
- import { n as firstUntranslatedGrayTip, t as collectGrayTipUids } from "../gray-tip-ByF-MKeV.mjs";
1
+ import { C as runAction, S as ActionRegistry, b as BaseProtocolAdapter, c as narrowSysMsgBlobs, d as recognizeSysMsg, f as textOf, h as varintOf, l as nodeAt, m as varintAt, u as processSysMsgBlob } from "../core-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
4
  import { r as subscribeRawMessages, t as forEachRawMessage } from "../raw-message-D2vA27kj.mjs";
5
- import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, isKernelError, kernelError, toCanonicalElements } from "@napuketto/kernel";
5
+ import { a as narrowEssenceGroupArg, i as extractEssenceSetSysMsg, o as narrowBuddyReqs, r as EssenceListSync, t as sliceRaw } from "../log-DiPRjA5P.mjs";
6
+ import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, kernelError, toCanonicalElements } from "@napuketto/kernel";
6
7
  import { mkdir, rename, writeFile } from "node:fs/promises";
7
8
  import { join } from "node:path";
8
9
  import { detectFileType, downloadUrl, inferExtension } from "@napuketto/media";
@@ -118,28 +119,23 @@ var MilkyApi = class {
118
119
  /** 通知查找默认搜索数量(单屏全量,OB11 DEFAULT_COUNT 同值)。 */
119
120
  const NOTIFY_SEARCH_COUNT$1 = 100;
120
121
  /**
121
- * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径)。
122
+ * 按通知 seq 查找群通知(先非可疑后可疑,OB11 set_group_add_request 同路径;
123
+ * 屏序骨架走 core findFirstMatch)。
122
124
  * 未找到抛 NOT_FOUND(应答动作的 seq 无效或已过期)。
123
125
  * 模块级函数(非类成员):应答动作的公共入口,OB11 同路径。
124
126
  */
125
127
  async function findGroupNotify(api, seq) {
126
- const hit = (await api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1)).find((item) => item.seq === seq);
127
- if (hit !== void 0) return hit;
128
- const doubtHit = (await api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)).find((item) => item.seq === seq);
129
- if (doubtHit !== void 0) return doubtHit;
130
- throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
128
+ const hit = await findFirstMatch([() => api.groupNotifyApi.getSingleScreenNotifies(false, NOTIFY_SEARCH_COUNT$1), () => api.groupNotifyApi.getSingleScreenNotifies(true, NOTIFY_SEARCH_COUNT$1)], (item) => item.seq === seq);
129
+ if (hit === void 0) throw kernelError(`未找到通知 ${seq}(无效或已过期)`, "NOT_FOUND");
130
+ return hit;
131
131
  }
132
132
  /** 按发起者 uid 查找好友申请(getBuddyReqList 匹配 friendUid);未找到抛 NOT_FOUND。 */
133
133
  async function findBuddyReq(api, initiatorUid) {
134
- const hit = (await api.friendApi.getBuddyReqList()).find((req) => req.friendUid === initiatorUid);
134
+ const hit = await findFirstMatch([() => api.friendApi.getBuddyReqList()], (req) => req.friendUid === initiatorUid);
135
135
  if (hit === void 0) throw kernelError(`未找到来自 ${initiatorUid} 的好友申请`, "NOT_FOUND");
136
136
  return hit;
137
137
  }
138
138
  // src/milky/helper/event/request.ts
139
- /** uid → uin(core 共享解析;ctx 携带映射)。 */
140
- function toUin$1(uid, ctx) {
141
- return resolveUin(uid, ctx.uidToUin);
142
- }
143
139
  /** BuddyReq → friend_request 事件(comment 取 words 字段,形状待校准,缺省空串)。 */
144
140
  function toFriendRequestEvent(req, ctx) {
145
141
  const words = req["words"];
@@ -148,7 +144,7 @@ function toFriendRequestEvent(req, ctx) {
148
144
  self_id: Number(ctx.selfUin),
149
145
  event_type: "friend_request",
150
146
  data: {
151
- initiator_id: toUin$1(req.friendUid, ctx),
147
+ initiator_id: toUin(req.friendUid, ctx),
152
148
  initiator_uid: req.friendUid,
153
149
  comment: typeof words === "string" ? words : "",
154
150
  via: req.sourceName ?? ""
@@ -171,7 +167,7 @@ function toGroupRequestEvent(notify, doubt, ctx) {
171
167
  group_id: groupId,
172
168
  notification_seq: seq,
173
169
  is_filtered: doubt,
174
- initiator_id: toUin$1(notify.user1?.uid, ctx),
170
+ initiator_id: toUin(notify.user1?.uid, ctx),
175
171
  comment: notify.postscript ?? ""
176
172
  }
177
173
  };
@@ -182,8 +178,8 @@ function toGroupRequestEvent(notify, doubt, ctx) {
182
178
  data: {
183
179
  group_id: groupId,
184
180
  notification_seq: seq,
185
- initiator_id: toUin$1(notify.user1?.uid, ctx),
186
- target_user_id: toUin$1(notify.user2?.uid, ctx)
181
+ initiator_id: toUin(notify.user1?.uid, ctx),
182
+ target_user_id: toUin(notify.user2?.uid, ctx)
187
183
  }
188
184
  };
189
185
  case GroupNotifyMsgType.INVITED_BY_MEMBER: return {
@@ -193,7 +189,7 @@ function toGroupRequestEvent(notify, doubt, ctx) {
193
189
  data: {
194
190
  group_id: groupId,
195
191
  invitation_seq: seq,
196
- initiator_id: toUin$1(notify.user1?.uid, ctx),
192
+ initiator_id: toUin(notify.user1?.uid, ctx),
197
193
  source_group_id: null
198
194
  }
199
195
  };
@@ -337,13 +333,6 @@ const milkyErrorCodeMap = {
337
333
  UNKNOWN: -500
338
334
  };
339
335
  // src/milky/action/base-action.ts
340
- /**
341
- * MilkyAction:Milky 动作基类(zod 校验 + KernelError → 负数 retcode)
342
- *
343
- * 与 OB11 BaseAction 分离的原因:Milky 响应信封无 echo、参数解析失败恒
344
- * retcode=-400(规范),不复用 OB11 的 400/1400 语义。
345
- * 响应信封由 transport 组装(status/retcode/data/message)。
346
- */
347
336
  /** zod 错误摘要(单行,issues 取前 3 条)。 */
348
337
  function zodSummary(error) {
349
338
  const parts = [];
@@ -353,34 +342,24 @@ function zodSummary(error) {
353
342
  var MilkyAction = class {
354
343
  /** 校验并执行(HTTP /api 入口;WS /event 不承载动作)。 */
355
344
  async handle(payload) {
356
- const parsed = this.schema.safeParse(payload);
357
- if (!parsed.success) return {
345
+ const outcome = await runAction({
346
+ schema: this.schema,
347
+ handle: (parsed) => this._handle(parsed),
348
+ errorCodeMap: this.errorCodeMap,
349
+ invalidRetcode: -400,
350
+ invalidMessage: (error) => `参数解析失败: ${zodSummary(error)}`
351
+ }, payload);
352
+ return outcome.ok ? {
353
+ status: "ok",
354
+ retcode: 0,
355
+ data: outcome.data,
356
+ message: ""
357
+ } : {
358
358
  status: "failed",
359
- retcode: -400,
359
+ retcode: outcome.retcode,
360
360
  data: null,
361
- message: `参数解析失败: ${zodSummary(parsed.error)}`
361
+ message: outcome.message
362
362
  };
363
- try {
364
- return {
365
- status: "ok",
366
- retcode: 0,
367
- data: await this._handle(parsed.data),
368
- message: ""
369
- };
370
- } catch (err) {
371
- if (isKernelError(err)) return {
372
- status: "failed",
373
- retcode: this.errorCodeMap[err.code] ?? this.errorCodeMap.UNKNOWN,
374
- data: null,
375
- message: err.message
376
- };
377
- return {
378
- status: "failed",
379
- retcode: this.errorCodeMap.UNKNOWN,
380
- data: null,
381
- message: err instanceof Error ? err.message : "未知错误"
382
- };
383
- }
384
363
  }
385
364
  };
386
365
  /**
@@ -2229,6 +2208,235 @@ function createMilkyActionRegistry(opts) {
2229
2208
  registry.register(new RenameGroupFolderAction(api));
2230
2209
  return registry;
2231
2210
  }
2211
+ // src/milky/enrichment.ts
2212
+ /** Milky 收链路异步回填器。 */
2213
+ var MilkyEnrichment = class {
2214
+ api;
2215
+ constructor(deps) {
2216
+ this.api = deps.api;
2217
+ }
2218
+ /** uid 批量 → uin(空集/失败返回 undefined 语义:调用方用空 Map)。 */
2219
+ resolveUidToUin(uids) {
2220
+ const unique = [...new Set(uids.filter((uid) => uid !== ""))];
2221
+ if (unique.length === 0) return Promise.resolve(void 0);
2222
+ return this.api.uidToUin(unique).catch(() => void 0);
2223
+ }
2224
+ /** at uid → uin 批量转换(mention.user_id 用;失败 mention 段跳过)。 */
2225
+ async fillMentionUids(elements, ctx) {
2226
+ const atUids = elements.filter((el) => el.type === "at" && el.target !== "all").map((el) => el.target);
2227
+ if (atUids.length === 0) return;
2228
+ try {
2229
+ ctx.uidToUin = await this.api.uidToUin(atUids);
2230
+ } catch {}
2231
+ }
2232
+ /** 群场景实体回填(GroupCache 缓存优先,失败最小实体兜底)。 */
2233
+ async fillGroupEntities(msg, ctx) {
2234
+ if (msg.chatType !== ChatType.GROUP || this.api.groupCache === void 0) return;
2235
+ const [detail, member] = await Promise.all([this.api.groupCache.getGroupDetail(msg.peerUid).catch(() => void 0), this.api.groupCache.getMember(msg.peerUid, msg.senderUid).catch(() => void 0)]);
2236
+ ctx.groupEntity = toGroupEntity(detail, msg.peerUid);
2237
+ ctx.groupMemberEntity = toGroupMemberEntity(member, msg.peerUid, msg.senderUin);
2238
+ }
2239
+ };
2240
+ // src/milky/event-pipeline.ts
2241
+ var MilkyEventPipeline = class {
2242
+ deps;
2243
+ unsubscribes = [];
2244
+ constructor(deps) {
2245
+ this.deps = deps;
2246
+ }
2247
+ /** 订阅 kernel 事件(消息 + 群 + 好友 + 批次三,幂等;路由到 inbound/)。 */
2248
+ subscribe() {
2249
+ if (this.unsubscribes.length > 0) return;
2250
+ const { msgChannel, groupChannel, buddyChannel, recentContactChannel, loginChannel } = this.deps;
2251
+ 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)));
2252
+ if (groupChannel !== void 0) this.unsubscribes.push(groupChannel.on("Group/onGroupNotifiesUpdated", (doubt, notifies) => {
2253
+ this.deps.request.groupNotifies(doubt, notifies);
2254
+ }), groupChannel.on("Group/onGroupEssenceListChange", (a) => this.deps.essence.change(a)));
2255
+ if (buddyChannel !== void 0) this.unsubscribes.push(buddyChannel.on("Buddy/onBuddyReqChange", (a) => this.deps.request.buddyReqs(a)));
2256
+ if (recentContactChannel !== void 0) {
2257
+ this.unsubscribes.push(recentContactChannel.on("RecentContact/onRecentContactListChangedVer2", (lists) => {
2258
+ this.deps.pin.handleChanges(lists);
2259
+ }));
2260
+ this.deps.pin.seed();
2261
+ }
2262
+ if (loginChannel !== void 0) this.unsubscribes.push(loginChannel.on("Login/onLoginDisConnected", (...args) => {
2263
+ this.deps.fileNotice.botOffline("disconnected", args);
2264
+ }), loginChannel.on("Login/onLogoutSucceed", (...args) => {
2265
+ this.deps.fileNotice.botOffline("logout", args);
2266
+ }));
2267
+ }
2268
+ /** 退订(幂等)。 */
2269
+ unsubscribeAll() {
2270
+ for (const off of this.unsubscribes) off();
2271
+ this.unsubscribes = [];
2272
+ }
2273
+ };
2274
+ // src/milky/helper/state/seq-index.ts
2275
+ /** 单方向最大条目数(测试用例引用容量语义)。 */
2276
+ const MAX_ENTRIES = 4096;
2277
+ var MessageSeqIndex = class {
2278
+ /** `${chatType}:${peerUid}:${seq}` → msgId。 */
2279
+ seqToMsg = /* @__PURE__ */ new Map();
2280
+ /** msgId → seq 元信息。 */
2281
+ msgToMeta = /* @__PURE__ */ new Map();
2282
+ /** 合并转发 resId → 定位信息(P1:get_forwarded_messages)。 */
2283
+ forwards = /* @__PURE__ */ new Map();
2284
+ /** 接收链路登记(一条消息双向写入;重复 msgId 覆盖)。 */
2285
+ record(msg) {
2286
+ const seq = Number(msg.msgSeq);
2287
+ if (!Number.isFinite(seq) || seq < 0) return;
2288
+ this.seqToMsg.set(this.key(msg.chatType, msg.peerUid, seq), msg.msgId);
2289
+ this.msgToMeta.set(msg.msgId, {
2290
+ seq,
2291
+ senderUin: msg.senderUin,
2292
+ timeSec: Math.floor(Number(msg.msgTime) / 1e3)
2293
+ });
2294
+ this.evict();
2295
+ }
2296
+ /** seq → msgId(反查;未登记返回 undefined)。 */
2297
+ resolveMsgId(chatType, peerUid, seq) {
2298
+ return this.seqToMsg.get(this.key(chatType, peerUid, seq));
2299
+ }
2300
+ /**
2301
+ * 批量回填 reply 引用元信息(msgId → Milky reply 段 data 所需三元组)。
2302
+ * 未命中的 id 不进表(翻译层按 0 兜底)。
2303
+ */
2304
+ collectReplyMeta(msgIds) {
2305
+ const out = /* @__PURE__ */ new Map();
2306
+ for (const id of msgIds) {
2307
+ const m = this.msgToMeta.get(id);
2308
+ if (m !== void 0) out.set(id, {
2309
+ messageSeq: m.seq,
2310
+ senderId: Number(m.senderUin) || 0,
2311
+ time: m.timeSec
2312
+ });
2313
+ }
2314
+ return out;
2315
+ }
2316
+ /** key 规则(chatType 数值 + peerUid + seq;peerUid 群聊=群号,C2C=uid)。 */
2317
+ key(chatType, peerUid, seq) {
2318
+ return `${chatType}:${peerUid}:${seq}`;
2319
+ }
2320
+ /**
2321
+ * 登记合并转发(接收链路:消息含 multiForwardMsgElement 时调用)。
2322
+ * resId 是 Milky forward_id 的来源;同一 resId 重复覆盖。
2323
+ */
2324
+ recordForward(resId, entry) {
2325
+ if (resId === "") return;
2326
+ this.forwards.set(resId, entry);
2327
+ while (this.forwards.size > MAX_ENTRIES) {
2328
+ const oldest = this.forwards.keys().next().value;
2329
+ if (oldest === void 0) break;
2330
+ this.forwards.delete(oldest);
2331
+ }
2332
+ }
2333
+ /** resId → 转发定位(get_forwarded_messages;未登记返回 undefined)。 */
2334
+ resolveForward(resId) {
2335
+ return this.forwards.get(resId);
2336
+ }
2337
+ /** FIFO 淘汰到容量上限内。 */
2338
+ evict() {
2339
+ while (this.seqToMsg.size > MAX_ENTRIES) {
2340
+ const oldest = this.seqToMsg.keys().next().value;
2341
+ if (oldest === void 0) break;
2342
+ this.seqToMsg.delete(oldest);
2343
+ }
2344
+ while (this.msgToMeta.size > MAX_ENTRIES) {
2345
+ const oldest = this.msgToMeta.keys().next().value;
2346
+ if (oldest === void 0) break;
2347
+ this.msgToMeta.delete(oldest);
2348
+ }
2349
+ }
2350
+ };
2351
+ // src/milky/helper/state/recent-keys.ts
2352
+ /**
2353
+ * 带过期去重键缓存(Milky 批次三)
2354
+ *
2355
+ * 两个场景共用:friend_file_upload 双回调(onRecvOfflineFileMsg / onFileMsgCome
2356
+ * 同载荷,按 msgId 去重)与 group_essence_message_change 双路径(732:1 快路径
2357
+ * vs 列表 diff,按 群:seq:方向 去重)。claim 语义 = 未登记过(或已过期)则登记
2358
+ * 并返回 true——调用方据此决定是否广播。
2359
+ */
2360
+ var RecentKeyCache = class {
2361
+ entries = /* @__PURE__ */ new Map();
2362
+ ttlMs;
2363
+ constructor(ttlMs) {
2364
+ this.ttlMs = ttlMs;
2365
+ }
2366
+ /** 未命中则登记并返回 true(应广播);命中(窗口内重复)返回 false。 */
2367
+ claim(key, now = Date.now()) {
2368
+ this.prune(now);
2369
+ const expiry = this.entries.get(key);
2370
+ if (expiry !== void 0 && expiry > now) return false;
2371
+ this.entries.set(key, now + this.ttlMs);
2372
+ return true;
2373
+ }
2374
+ /** 惰性清理过期键(每次 claim 顺带执行,量级小无需定时器)。 */
2375
+ prune(now) {
2376
+ for (const [key, expiry] of this.entries) if (expiry <= now) this.entries.delete(key);
2377
+ }
2378
+ };
2379
+ // src/milky/inbound/essence.ts
2380
+ /** Milky 精华域处理器(双路径去重 + 串行 diff 同步 + group_essence 事件广播)。 */
2381
+ var MilkyInboundEssence = class {
2382
+ deps;
2383
+ essenceKeys = new RecentKeyCache(3e5);
2384
+ essenceSync;
2385
+ constructor(deps) {
2386
+ this.deps = deps;
2387
+ this.essenceSync = new EssenceListSync({
2388
+ fetchList: (groupCode) => deps.api.webApi.getEssenceMsgList(groupCode),
2389
+ onAdded: (groupCode, added) => this.broadcastAdded(groupCode, added),
2390
+ onRemoved: (groupCode, removed) => this.broadcastRemoved(groupCode, removed),
2391
+ onFetchError: (g, err) => deps.logger?.warn({
2392
+ group: g,
2393
+ err: String(err)
2394
+ }, "milky: 精华列表拉取失败(diff 跳过)")
2395
+ });
2396
+ }
2397
+ /** sysmsg 732:1 快路径去重守卫:非精华恒 true;精华 claim 失败(diff 已抢发)→ false。 */
2398
+ claimFastPath(ruleKind, data) {
2399
+ if (ruleKind !== "group_essence_message_change") return true;
2400
+ const rec = data;
2401
+ if (typeof rec.group_id !== "number" || typeof rec.message_seq !== "number") return true;
2402
+ return this.claimChange(rec.group_id, rec.message_seq, true);
2403
+ }
2404
+ /** 精华列表变更:拉全量列表 diff(remove 路径 + operator 回填;串行防乱序)。 */
2405
+ change(arg) {
2406
+ const groupCode = narrowEssenceGroupArg(arg);
2407
+ if (groupCode === null) {
2408
+ this.deps.logger?.warn({ raw: sliceRaw(JSON.stringify(arg)) }, "milky: onGroupEssenceListChange 未知参数形状");
2409
+ return;
2410
+ }
2411
+ this.essenceSync.enqueue(groupCode);
2412
+ }
2413
+ /** diff 广播:add(operator = add_digest_uin,快路径已发则跳过)→ remove(operator 省略)。 */
2414
+ broadcastAdded(groupCode, added) {
2415
+ const now = Math.floor(Date.now() / 1e3);
2416
+ for (const item of added) if (this.claimChange(groupCode, item.messageSeq, true)) this.broadcastChange(groupCode, item.messageSeq, true, numericUin(item.operatorUin), now);
2417
+ }
2418
+ broadcastRemoved(groupCode, removed) {
2419
+ const now = Math.floor(Date.now() / 1e3);
2420
+ for (const seq of removed) if (this.claimChange(groupCode, seq, false)) this.broadcastChange(groupCode, seq, false, null, now);
2421
+ }
2422
+ broadcastChange(groupCode, seq, isSet, operatorId, time) {
2423
+ this.deps.broadcast({
2424
+ time,
2425
+ self_id: Number(this.deps.api.self.uin),
2426
+ event_type: "group_essence_message_change",
2427
+ data: {
2428
+ group_id: Number(groupCode),
2429
+ message_seq: seq,
2430
+ is_set: isSet,
2431
+ ...operatorId !== null ? { operator_id: operatorId } : {}
2432
+ }
2433
+ });
2434
+ }
2435
+ /** 双路径 claim(键 群:seq:方向;true = 未广播过,可发)。 */
2436
+ claimChange(groupCode, seq, isSet) {
2437
+ return this.essenceKeys.claim(`${groupCode}:${seq}:${isSet ? 1 : 0}`);
2438
+ }
2439
+ };
2232
2440
  // src/milky/helper/event/file-upload.ts
2233
2441
  /**
2234
2442
  * friend_file_upload 翻译(Milky 批次三,2026-11-01 录制定型)
@@ -2257,42 +2465,203 @@ function toFriendFileUploadData(msg, selfUin, uidToUin) {
2257
2465
  is_self: isSelf
2258
2466
  };
2259
2467
  }
2260
- // src/milky/helper/event/notice.ts
2261
- /** 毫秒 → 秒(Unix 时间戳)。 */
2262
- const MS_TO_SEC = 1e3;
2263
- /** uid → uin(core 共享解析;ctx 携带映射)。 */
2264
- function toUin(uid, ctx) {
2265
- return resolveUin(uid, ctx.uidToUin);
2468
+ // src/milky/helper/event/peer-pin.ts
2469
+ /**
2470
+ * peer_pin_change 翻译(Milky 批次三,RecentContact/onRecentContactListChangedVer2)
2471
+ *
2472
+ * 回调随消息活动高频快照(含 topFlag 的全量条目 + chatType=7 影子条目),
2473
+ * 不能见条目就广播——按「同会话 topFlag 前后值翻转」检测(PinWatch)。
2474
+ * 启动期以 getPinnedContacts 播种基线(重启后首个取消置顶也能观测到)。
2475
+ *
2476
+ * 证据:2026-11-01 set_peer_pin 自触发翻转实验——changedList 条目
2477
+ * {chatType, peerUin, topFlag(1/0), topFlagTime(秒级 unix 字符串)},与操作
2478
+ * 一一对应(milky.md §0.8.6)。
2479
+ */
2480
+ /** uin 形判别(peer_id 必须是数字串)。 */
2481
+ const NUMERIC_RE$1 = /^\d+$/;
2482
+ /** 置顶翻转检测(每适配器实例一份,键 = chatType:peerUin——群号与 uin 数值空间可重叠)。 */
2483
+ var PinWatch = class {
2484
+ states = /* @__PURE__ */ new Map();
2485
+ /** 启动基线:置顶会话播种(只记状态,不产生事件)。 */
2486
+ seed(pins) {
2487
+ for (const pin of pins) {
2488
+ if (pin.peerUin === void 0 || pin.peerUin === "") continue;
2489
+ const chatType = pin.scene === "group" ? ChatType.GROUP : ChatType.C2C;
2490
+ this.states.set(`${chatType}:${pin.peerUin}`, 1);
2491
+ }
2492
+ }
2493
+ /**
2494
+ * 观测一个变更条目:topFlag 相对上次观测翻转 → true(应广播);
2495
+ * 首见(基线未建立)或未变 → false。
2496
+ */
2497
+ observe(chatType, peerUin, topFlag) {
2498
+ const key = `${chatType}:${peerUin}`;
2499
+ const prev = this.states.get(key);
2500
+ this.states.set(key, topFlag);
2501
+ return prev !== void 0 && prev !== topFlag;
2502
+ }
2503
+ };
2504
+ /** 场景映射(changedList 条目 chatType → Milky message_scene;影子/其他类型丢弃)。 */
2505
+ function pinScene(chatType) {
2506
+ if (chatType === ChatType.GROUP) return "group";
2507
+ if (chatType === ChatType.C2C) return "friend";
2508
+ return null;
2266
2509
  }
2267
- /** 事件信封公共字段。 */
2268
- function envelope(msg, ctx, eventType, data) {
2510
+ /** 变更条目 → 事件载荷(null = 条目不含置顶字段/场景不支持,跳过不广播)。 */
2511
+ function toPeerPinChangeData(entry) {
2512
+ const scene = pinScene(entry.chatType);
2513
+ if (scene === null || entry.topFlag === void 0) return null;
2514
+ const peerUin = typeof entry.peerUin === "string" && entry.peerUin !== "" ? entry.peerUin : scene === "group" ? entry.peerUid : "";
2515
+ if (peerUin === "" || !NUMERIC_RE$1.test(peerUin)) return null;
2269
2516
  return {
2270
- time: Math.floor(Number(msg.msgTime) / MS_TO_SEC),
2271
- self_id: Number(ctx.selfUin),
2272
- event_type: eventType,
2273
- data
2517
+ data: {
2518
+ message_scene: scene,
2519
+ peer_id: Number(peerUin),
2520
+ is_pinned: entry.topFlag === 1
2521
+ },
2522
+ topFlagTime: typeof entry.topFlagTime === "string" ? entry.topFlagTime : void 0,
2523
+ peerUin
2274
2524
  };
2275
2525
  }
2276
- /** 单个 grayTip → Milky notice 事件(null = 不可翻译)。 */
2277
- function translateGrayTip(msg, g, ctx) {
2278
- if (g.aioOpGrayTipElement != null) return aioOpToEvent(msg, g, ctx);
2279
- if (g.subElementType === GrayTipSubType.GROUP) return groupElementToEvent(msg, g.groupElement, ctx);
2280
- return null;
2281
- }
2282
- /** 群成员变动类映射器表(键 = TipGroupElementType;缺项 = 不可翻译返回 null)。 */
2283
- const GROUP_CHANGE_MAPPERS = {
2284
- [TipGroupElementType.MEMBER_ADD]: toMemberIncrease,
2285
- [TipGroupElementType.QUIT]: toMemberDecrease,
2286
- [TipGroupElementType.SHUT_UP]: toShutUpEvent,
2287
- [TipGroupElementType.GROUP_NAME_MODIFIED]: toNameChange,
2288
- [TipGroupElementType.DISBANDED]: toDisband
2289
- };
2290
- function groupElementToEvent(msg, grp, ctx) {
2291
- if (grp === void 0 || grp.type === void 0) return null;
2292
- const mapper = GROUP_CHANGE_MAPPERS[grp.type];
2293
- if (mapper === void 0) return null;
2294
- return mapper(msg, groupChangeCommon(grp, Number(msg.peerUid)), grp, ctx);
2295
- }
2526
+ // src/milky/inbound/pin.ts
2527
+ /** Milky 置顶域处理器(翻转检测 + 播种基线 + peer_pin_change 广播)。 */
2528
+ var MilkyInboundPin = class {
2529
+ deps;
2530
+ /** peer_pin 翻转检测(批次三;启动期 getPinnedContacts 播种)。 */
2531
+ pinWatch = new PinWatch();
2532
+ constructor(deps) {
2533
+ this.deps = deps;
2534
+ }
2535
+ /** 会话列表变更 → 翻转检测逐条处理(首见/未变/不支持场景静默跳过)。 */
2536
+ handleChanges(lists) {
2537
+ const arr = Array.isArray(lists) ? lists : [lists];
2538
+ for (const list of arr) for (const entry of changedListOf(list)) this.handleEntry(entry);
2539
+ }
2540
+ /** 启动基线:置顶会话播种(2026-11-14 起失败补 debug 日志,不再静默)。 */
2541
+ seed() {
2542
+ this.deps.api.recentContactApi.getPinnedContacts().then((pins) => {
2543
+ this.pinWatch.seed(pins);
2544
+ }).catch((err) => {
2545
+ this.deps.logger?.debug({ err: String(err) }, "milky: 置顶基线播种失败(跳过)");
2546
+ });
2547
+ }
2548
+ /** 单个变更条目:翻译 + 翻转检测 + 广播。 */
2549
+ handleEntry(entry) {
2550
+ const payload = pinPayloadOf(entry);
2551
+ if (payload === null) return;
2552
+ if (!this.pinWatch.observe(payload.chatType, payload.peerUin, payload.topFlag)) return;
2553
+ this.deps.broadcast({
2554
+ time: secondsOf(payload.topFlagTime),
2555
+ self_id: Number(this.deps.api.self.uin),
2556
+ event_type: "peer_pin_change",
2557
+ data: payload.data
2558
+ });
2559
+ }
2560
+ };
2561
+ /** 变更列表 → changedList 条目数组(形状不符 → 空)。 */
2562
+ function changedListOf(list) {
2563
+ if (list === null || typeof list !== "object") return [];
2564
+ const changed = list.changedList;
2565
+ return Array.isArray(changed) ? changed : [];
2566
+ }
2567
+ /** 变更条目 → 翻转检测输入(null = 条目不支持/缺置顶字段)。 */
2568
+ function pinPayloadOf(entry) {
2569
+ if (entry === null || typeof entry !== "object") return null;
2570
+ return pinPayloadFrom(entry);
2571
+ }
2572
+ function pinPayloadFrom(contact) {
2573
+ const topFlag = contact.topFlag;
2574
+ const payload = toPeerPinChangeData(contact);
2575
+ if (topFlag === void 0 || payload === null) return null;
2576
+ return {
2577
+ chatType: contact.chatType,
2578
+ peerUin: payload.peerUin,
2579
+ topFlag,
2580
+ topFlagTime: payload.topFlagTime,
2581
+ data: payload.data
2582
+ };
2583
+ }
2584
+ /** 秒级时间戳归一(空/非法 → 当前时间;topFlagTime/msgTime 均为秒级字符串)。 */
2585
+ function secondsOf(raw) {
2586
+ return numericUin(raw ?? null) ?? Math.floor(Date.now() / 1e3);
2587
+ }
2588
+ // src/milky/inbound/file-notice.ts
2589
+ /**
2590
+ * Milky inbound 轻量通知域:私聊文件双回调(friend_file_upload,按 msgId 去重)
2591
+ * 与 bot_offline(Login 桥,载荷零样本,reason 固定值)。置顶翻转在 pin.ts。
2592
+ */
2593
+ /** Milky 轻量通知域处理器(私聊文件 / bot_offline)。 */
2594
+ var MilkyInboundFileNotice = class {
2595
+ deps;
2596
+ /** friend_file_upload 双回调去重(同载荷,按 msgId)。 */
2597
+ fileKeys = new RecentKeyCache(6e5);
2598
+ constructor(deps) {
2599
+ this.deps = deps;
2600
+ }
2601
+ /** 私聊文件消息 → friend_file_upload(双回调同载荷,按 msgId 去重)。 */
2602
+ fileMessages(msgs) {
2603
+ forEachRawMessage(msgs, (msg) => {
2604
+ const data = toFriendFileUploadData(msg, this.deps.api.self.uin, /* @__PURE__ */ new Map());
2605
+ if (data === null) return;
2606
+ if (data.user_id === 0) this.deps.logger?.debug({
2607
+ msgId: msg.msgId,
2608
+ senderUid: msg.senderUid
2609
+ }, "milky: friend_file_upload senderUin 缺失(user_id=0)");
2610
+ if (!this.fileKeys.claim(`file:${msg.msgId}`)) return;
2611
+ this.deps.broadcast({
2612
+ time: secondsOf(msg.msgTime),
2613
+ self_id: Number(this.deps.api.self.uin),
2614
+ event_type: "friend_file_upload",
2615
+ data
2616
+ });
2617
+ });
2618
+ }
2619
+ /** bot_offline:Login 桥回调(载荷零样本,reason 固定值 + raw 校准日志待野捕)。 */
2620
+ botOffline(reason, args) {
2621
+ this.deps.logger?.debug({
2622
+ reason,
2623
+ raw: sliceRaw(JSON.stringify(args))
2624
+ }, "milky: bot_offline(reason 为固定值,回调载荷待野捕校准)");
2625
+ this.deps.broadcast({
2626
+ time: Math.floor(Date.now() / 1e3),
2627
+ self_id: Number(this.deps.api.self.uin),
2628
+ event_type: "bot_offline",
2629
+ data: { reason }
2630
+ });
2631
+ }
2632
+ };
2633
+ // src/milky/helper/event/notice.ts
2634
+ /** 毫秒 → 秒(Unix 时间戳)。 */
2635
+ const MS_TO_SEC = 1e3;
2636
+ /** 事件信封公共字段。 */
2637
+ function envelope(msg, ctx, eventType, data) {
2638
+ return {
2639
+ time: Math.floor(Number(msg.msgTime) / MS_TO_SEC),
2640
+ self_id: Number(ctx.selfUin),
2641
+ event_type: eventType,
2642
+ data
2643
+ };
2644
+ }
2645
+ /** 单个 grayTip → Milky notice 事件(null = 不可翻译)。 */
2646
+ function translateGrayTip(msg, g, ctx) {
2647
+ if (g.aioOpGrayTipElement != null) return aioOpToEvent(msg, g, ctx);
2648
+ if (g.subElementType === GrayTipSubType.GROUP) return groupElementToEvent(msg, g.groupElement, ctx);
2649
+ return null;
2650
+ }
2651
+ /** 群成员变动类映射器表(键 = TipGroupElementType;缺项 = 不可翻译返回 null)。 */
2652
+ const GROUP_CHANGE_MAPPERS = {
2653
+ [TipGroupElementType.MEMBER_ADD]: toMemberIncrease,
2654
+ [TipGroupElementType.QUIT]: toMemberDecrease,
2655
+ [TipGroupElementType.SHUT_UP]: toShutUpEvent,
2656
+ [TipGroupElementType.GROUP_NAME_MODIFIED]: toNameChange,
2657
+ [TipGroupElementType.DISBANDED]: toDisband
2658
+ };
2659
+ function groupElementToEvent(msg, grp, ctx) {
2660
+ if (grp === void 0 || grp.type === void 0) return null;
2661
+ const mapper = GROUP_CHANGE_MAPPERS[grp.type];
2662
+ if (mapper === void 0) return null;
2663
+ return mapper(msg, groupChangeCommon(grp, Number(msg.peerUid)), grp, ctx);
2664
+ }
2296
2665
  /** 禁言载荷优先(shutUp.member/admin 覆盖顶层 memberUid/adminUid)。 */
2297
2666
  function groupChangeCommon(grp, groupId) {
2298
2667
  return {
@@ -2402,64 +2771,109 @@ function toMilkyNoticeEvent(msg, ctx) {
2402
2771
  }, "milky: 未翻译的 grayTip 子类型(raw 校准数据)");
2403
2772
  return null;
2404
2773
  }
2405
- // src/milky/helper/event/peer-pin.ts
2406
- /**
2407
- * peer_pin_change 翻译(Milky 批次三,RecentContact/onRecentContactListChangedVer2)
2408
- *
2409
- * 回调随消息活动高频快照(含 topFlag 的全量条目 + chatType=7 影子条目),
2410
- * 不能见条目就广播——按「同会话 topFlag 前后值翻转」检测(PinWatch)。
2411
- * 启动期以 getPinnedContacts 播种基线(重启后首个取消置顶也能观测到)。
2412
- *
2413
- * 证据:2026-11-01 set_peer_pin 自触发翻转实验——changedList 条目
2414
- * {chatType, peerUin, topFlag(1/0), topFlagTime(秒级 unix 字符串)},与操作
2415
- * 一一对应(milky.md §0.8.6)。
2416
- */
2417
- /** uin 形判别(peer_id 必须是数字串)。 */
2418
- const NUMERIC_RE$2 = /^\d+$/;
2419
- /** 置顶翻转检测(每适配器实例一份,键 = chatType:peerUin——群号与 uin 数值空间可重叠)。 */
2420
- var PinWatch = class {
2421
- states = /* @__PURE__ */ new Map();
2422
- /** 启动基线:置顶会话播种(只记状态,不产生事件)。 */
2423
- seed(pins) {
2424
- for (const pin of pins) {
2425
- if (pin.peerUin === void 0 || pin.peerUin === "") continue;
2426
- const chatType = pin.scene === "group" ? ChatType.GROUP : ChatType.C2C;
2427
- this.states.set(`${chatType}:${pin.peerUin}`, 1);
2774
+ // src/milky/inbound/message.ts
2775
+ /** Milky 消息域处理器(Msg/onRecvMsg 分流与翻译派发)。 */
2776
+ var MilkyInboundMessage = class {
2777
+ deps;
2778
+ constructor(deps) {
2779
+ this.deps = deps;
2780
+ }
2781
+ /** 单条消息:seq 登记 → grayTip→notice / 群文件上传 / message_receive(自消息不上报)。 */
2782
+ async handle(msg) {
2783
+ this.deps.seqIndex.record(msg);
2784
+ this.recordForward(msg);
2785
+ if (hasGrayTip(msg)) {
2786
+ await this.broadcastNotice(msg);
2787
+ return;
2428
2788
  }
2789
+ const upload = toGroupFileUploadEvent(msg, this.deps.api.self.uin);
2790
+ if (upload !== null) {
2791
+ this.deps.broadcast(upload);
2792
+ return;
2793
+ }
2794
+ if (String(msg.senderUin) === this.deps.api.self.uin) return;
2795
+ this.deps.broadcast(await this.buildMessageReceiveEvent(msg));
2429
2796
  }
2430
- /**
2431
- * 观测一个变更条目:topFlag 相对上次观测翻转 → true(应广播);
2432
- * 首见(基线未建立)或未变 → false。
2433
- */
2434
- observe(chatType, peerUin, topFlag) {
2435
- const key = `${chatType}:${peerUin}`;
2436
- const prev = this.states.get(key);
2437
- this.states.set(key, topFlag);
2438
- return prev !== void 0 && prev !== topFlag;
2797
+ /** grayTip → notice 事件广播(REVOKE 走 message_recall,其余走 notice 翻译)。 */
2798
+ async broadcastNotice(msg) {
2799
+ const uidToUin = await this.deps.enrich.resolveUidToUin(collectGrayTipUids(msg));
2800
+ const event = findRevokeElement(msg) !== void 0 ? toMessageRecallEvent(msg, {
2801
+ selfUin: this.deps.api.self.uin,
2802
+ ...uidToUin !== void 0 ? { uidToUin } : {}
2803
+ }) : toMilkyNoticeEvent(msg, this.noticeCtx(uidToUin));
2804
+ if (event !== null) this.deps.broadcast(event);
2805
+ }
2806
+ /** notice 翻译上下文(uidToUin 缺省空 Map;logger 透传校准日志)。 */
2807
+ noticeCtx(uidToUin) {
2808
+ return {
2809
+ selfUin: this.deps.api.self.uin,
2810
+ ...uidToUin !== void 0 ? { uidToUin } : { uidToUin: /* @__PURE__ */ new Map() },
2811
+ ...this.deps.logger !== void 0 ? { logger: this.deps.logger } : {}
2812
+ };
2813
+ }
2814
+ /** message_receive 组装:at uid→uin + reply 回填 + 群实体回填 + 转发段(全部 fail-soft)。 */
2815
+ async buildMessageReceiveEvent(msg) {
2816
+ const elements = toCanonicalElements(msg);
2817
+ const ctx = { selfUin: this.deps.api.self.uin };
2818
+ await this.deps.enrich.fillMentionUids(elements, ctx);
2819
+ const replyIds = elements.filter((el) => el.type === "reply").map((el) => el.messageId);
2820
+ const meta = this.deps.seqIndex.collectReplyMeta(replyIds);
2821
+ if (meta.size > 0) ctx.replyMeta = meta;
2822
+ await this.deps.enrich.fillGroupEntities(msg, ctx);
2823
+ const forward = this.findForward(msg);
2824
+ if (forward !== void 0) ctx.forwardSegments = [incomingForwardSegment(forward.resId, forward.fileName)];
2825
+ return toMessageReceiveEvent(msg, ctx);
2826
+ }
2827
+ /** 转发 resId → 定位登记(get_forwarded_messages 反查用)。 */
2828
+ recordForward(msg) {
2829
+ const forward = this.findForward(msg);
2830
+ if (forward !== void 0 && forward.resId !== "") this.deps.seqIndex.recordForward(forward.resId, {
2831
+ chatType: msg.chatType,
2832
+ peerUid: msg.peerUid,
2833
+ msgId: msg.msgId
2834
+ });
2835
+ }
2836
+ findForward(msg) {
2837
+ return msg.elements.find((el) => el.multiForwardMsgElement != null)?.multiForwardMsgElement;
2838
+ }
2839
+ };
2840
+ // src/milky/inbound/request.ts
2841
+ /** Milky 请求域处理器(群通知 / 好友申请的 uid 回填与广播)。 */
2842
+ var MilkyInboundRequest = class {
2843
+ deps;
2844
+ constructor(deps) {
2845
+ this.deps = deps;
2846
+ }
2847
+ /** 群通知通道:入群请求 / 成员邀请 / 邀请自身(uid→uin 批量后翻译)。 */
2848
+ async groupNotifies(doubt, notifies) {
2849
+ const ctx = await this.requestCtx(collectNotifyUids(notifies));
2850
+ for (const notify of notifies) {
2851
+ const event = toGroupRequestEvent(notify, doubt, ctx);
2852
+ if (event !== null) this.deps.broadcast(event);
2853
+ }
2854
+ }
2855
+ /** 好友请求通道:Buddy/onBuddyReqChange(防御收窄,未知形状 raw 日志)。 */
2856
+ buddyReqs(arg) {
2857
+ this.broadcastBuddyReqs(arg);
2858
+ }
2859
+ async broadcastBuddyReqs(arg) {
2860
+ const reqs = narrowBuddyReqs(arg);
2861
+ if (reqs === null) {
2862
+ this.deps.logger?.warn({ raw: sliceRaw(JSON.stringify(arg)) }, "milky: onBuddyReqChange 未知参数形状");
2863
+ return;
2864
+ }
2865
+ const ctx = await this.requestCtx(reqs.map((req) => req.friendUid));
2866
+ for (const req of reqs) this.deps.broadcast(toFriendRequestEvent(req, ctx));
2867
+ }
2868
+ /** request 翻译上下文(uid→uin 批量转换;失败退空 Map)。 */
2869
+ async requestCtx(uids) {
2870
+ const uidToUin = await this.deps.enrich.resolveUidToUin(uids);
2871
+ return {
2872
+ selfUin: this.deps.api.self.uin,
2873
+ ...uidToUin !== void 0 ? { uidToUin } : { uidToUin: /* @__PURE__ */ new Map() }
2874
+ };
2439
2875
  }
2440
2876
  };
2441
- /** 场景映射(changedList 条目 chatType → Milky message_scene;影子/其他类型丢弃)。 */
2442
- function pinScene(chatType) {
2443
- if (chatType === ChatType.GROUP) return "group";
2444
- if (chatType === ChatType.C2C) return "friend";
2445
- return null;
2446
- }
2447
- /** 变更条目 → 事件载荷(null = 条目不含置顶字段/场景不支持,跳过不广播)。 */
2448
- function toPeerPinChangeData(entry) {
2449
- const scene = pinScene(entry.chatType);
2450
- if (scene === null || entry.topFlag === void 0) return null;
2451
- const peerUin = typeof entry.peerUin === "string" && entry.peerUin !== "" ? entry.peerUin : scene === "group" ? entry.peerUid : "";
2452
- if (peerUin === "" || !NUMERIC_RE$2.test(peerUin)) return null;
2453
- return {
2454
- data: {
2455
- message_scene: scene,
2456
- peer_id: Number(peerUin),
2457
- is_pinned: entry.topFlag === 1
2458
- },
2459
- topFlagTime: typeof entry.topFlagTime === "string" ? entry.topFlagTime : void 0,
2460
- peerUin
2461
- };
2462
- }
2463
2877
  // src/milky/helper/event/sysmsg.ts
2464
2878
  /**
2465
2879
  * Milky sysmsg 识别表(批次三,2026-11-01;识别机制共享自 core/sysmsg.ts)
@@ -2477,7 +2891,7 @@ function toPeerPinChangeData(entry) {
2477
2891
  * - 528:349/381/382 多端设备同步族:不广播。
2478
2892
  */
2479
2893
  /** 数字串判别(faceId 实证为数字字符串)。 */
2480
- const NUMERIC_RE$1 = /^\d+$/;
2894
+ const NUMERIC_RE = /^\d+$/;
2481
2895
  /** 732:16 → group_message_reaction。 */
2482
2896
  const REACTION_RULE = {
2483
2897
  kind: "group_message_reaction",
@@ -2519,7 +2933,7 @@ function reactionFace(groupId, msgSeq, face) {
2519
2933
  /** faceId 字段(数字字符串 → number;缺失/非数字 → null)。 */
2520
2934
  function reactionFaceId(face) {
2521
2935
  const faceIdText = textOf(face, 1);
2522
- return faceIdText !== null && NUMERIC_RE$1.test(faceIdText) ? Number(faceIdText) : null;
2936
+ return faceIdText !== null && NUMERIC_RE.test(faceIdText) ? Number(faceIdText) : null;
2523
2937
  }
2524
2938
  /** is_add 判定:f5=1 添加 / 2 撤销(f3=1 仅添加时存在,双判据);非法 → null。 */
2525
2939
  function reactionIsAdd(face) {
@@ -2532,127 +2946,68 @@ const KIND_TABLE = /* @__PURE__ */ new Map([["732:16", REACTION_RULE], ["732:1",
2532
2946
  kind: "group_essence_message_change",
2533
2947
  extract: (tree) => {
2534
2948
  const hit = extractEssenceSetSysMsg(tree);
2535
- if (hit === null) return null;
2536
- return {
2537
- group_id: hit.groupCode,
2538
- message_seq: hit.messageSeq,
2539
- is_set: true
2540
- };
2541
- }
2542
- }]]);
2543
- /** 已观测但未命名的键(多端设备同步族等,不广播只走校准日志)。 */
2544
- const OBSERVED_UNNAMED = /* @__PURE__ */ new Set([
2545
- "528:382",
2546
- "528:349",
2547
- "528:381"
2548
- ]);
2549
- /** (msgType, subType) → 识别结果(绑定 Milky 表;table 参数供单测注入)。 */
2550
- function recognizeMilkySysMsg(msgType, subType, table = KIND_TABLE) {
2551
- return recognizeSysMsg(msgType, subType, table, OBSERVED_UNNAMED);
2552
- }
2553
- // src/milky/helper/state/recent-keys.ts
2554
- /**
2555
- * 带过期去重键缓存(Milky 批次三)
2556
- *
2557
- * 两个场景共用:friend_file_upload 双回调(onRecvOfflineFileMsg / onFileMsgCome
2558
- * 同载荷,按 msgId 去重)与 group_essence_message_change 双路径(732:1 快路径
2559
- * vs 列表 diff,按 群:seq:方向 去重)。claim 语义 = 未登记过(或已过期)则登记
2560
- * 并返回 true——调用方据此决定是否广播。
2561
- */
2562
- var RecentKeyCache = class {
2563
- entries = /* @__PURE__ */ new Map();
2564
- ttlMs;
2565
- constructor(ttlMs) {
2566
- this.ttlMs = ttlMs;
2567
- }
2568
- /** 未命中则登记并返回 true(应广播);命中(窗口内重复)返回 false。 */
2569
- claim(key, now = Date.now()) {
2570
- this.prune(now);
2571
- const expiry = this.entries.get(key);
2572
- if (expiry !== void 0 && expiry > now) return false;
2573
- this.entries.set(key, now + this.ttlMs);
2574
- return true;
2575
- }
2576
- /** 惰性清理过期键(每次 claim 顺带执行,量级小无需定时器)。 */
2577
- prune(now) {
2578
- for (const [key, expiry] of this.entries) if (expiry <= now) this.entries.delete(key);
2579
- }
2580
- };
2581
- // src/milky/helper/state/seq-index.ts
2582
- /** 单方向最大条目数(测试用例引用容量语义)。 */
2583
- const MAX_ENTRIES = 4096;
2584
- var MessageSeqIndex = class {
2585
- /** `${chatType}:${peerUid}:${seq}` → msgId。 */
2586
- seqToMsg = /* @__PURE__ */ new Map();
2587
- /** msgId → seq 元信息。 */
2588
- msgToMeta = /* @__PURE__ */ new Map();
2589
- /** 合并转发 resId → 定位信息(P1:get_forwarded_messages)。 */
2590
- forwards = /* @__PURE__ */ new Map();
2591
- /** 接收链路登记(一条消息双向写入;重复 msgId 覆盖)。 */
2592
- record(msg) {
2593
- const seq = Number(msg.msgSeq);
2594
- if (!Number.isFinite(seq) || seq < 0) return;
2595
- this.seqToMsg.set(this.key(msg.chatType, msg.peerUid, seq), msg.msgId);
2596
- this.msgToMeta.set(msg.msgId, {
2597
- seq,
2598
- senderUin: msg.senderUin,
2599
- timeSec: Math.floor(Number(msg.msgTime) / 1e3)
2600
- });
2601
- this.evict();
2602
- }
2603
- /** seq → msgId(反查;未登记返回 undefined)。 */
2604
- resolveMsgId(chatType, peerUid, seq) {
2605
- return this.seqToMsg.get(this.key(chatType, peerUid, seq));
2606
- }
2607
- /**
2608
- * 批量回填 reply 引用元信息(msgId → Milky reply 段 data 所需三元组)。
2609
- * 未命中的 id 不进表(翻译层按 0 兜底)。
2610
- */
2611
- collectReplyMeta(msgIds) {
2612
- const out = /* @__PURE__ */ new Map();
2613
- for (const id of msgIds) {
2614
- const m = this.msgToMeta.get(id);
2615
- if (m !== void 0) out.set(id, {
2616
- messageSeq: m.seq,
2617
- senderId: Number(m.senderUin) || 0,
2618
- time: m.timeSec
2619
- });
2620
- }
2621
- return out;
2622
- }
2623
- /** key 规则(chatType 数值 + peerUid + seq;peerUid 群聊=群号,C2C=uid)。 */
2624
- key(chatType, peerUid, seq) {
2625
- return `${chatType}:${peerUid}:${seq}`;
2626
- }
2627
- /**
2628
- * 登记合并转发(接收链路:消息含 multiForwardMsgElement 时调用)。
2629
- * resId 是 Milky forward_id 的来源;同一 resId 重复覆盖。
2630
- */
2631
- recordForward(resId, entry) {
2632
- if (resId === "") return;
2633
- this.forwards.set(resId, entry);
2634
- while (this.forwards.size > MAX_ENTRIES) {
2635
- const oldest = this.forwards.keys().next().value;
2636
- if (oldest === void 0) break;
2637
- this.forwards.delete(oldest);
2638
- }
2639
- }
2640
- /** resId → 转发定位(get_forwarded_messages;未登记返回 undefined)。 */
2641
- resolveForward(resId) {
2642
- return this.forwards.get(resId);
2949
+ if (hit === null) return null;
2950
+ return {
2951
+ group_id: hit.groupCode,
2952
+ message_seq: hit.messageSeq,
2953
+ is_set: true
2954
+ };
2643
2955
  }
2644
- /** FIFO 淘汰到容量上限内。 */
2645
- evict() {
2646
- while (this.seqToMsg.size > MAX_ENTRIES) {
2647
- const oldest = this.seqToMsg.keys().next().value;
2648
- if (oldest === void 0) break;
2649
- this.seqToMsg.delete(oldest);
2650
- }
2651
- while (this.msgToMeta.size > MAX_ENTRIES) {
2652
- const oldest = this.msgToMeta.keys().next().value;
2653
- if (oldest === void 0) break;
2654
- this.msgToMeta.delete(oldest);
2956
+ }]]);
2957
+ /** 已观测但未命名的键(多端设备同步族等,不广播只走校准日志)。 */
2958
+ const OBSERVED_UNNAMED = /* @__PURE__ */ new Set([
2959
+ "528:382",
2960
+ "528:349",
2961
+ "528:381"
2962
+ ]);
2963
+ /** (msgType, subType) → 识别结果(绑定 Milky 表;table 参数供单测注入)。 */
2964
+ function recognizeMilkySysMsg(msgType, subType, table = KIND_TABLE) {
2965
+ return recognizeSysMsg(msgType, subType, table, OBSERVED_UNNAMED);
2966
+ }
2967
+ // src/milky/inbound/sysmsg.ts
2968
+ /**
2969
+ * Milky inbound sysmsg 域:Msg/onRecvSysMsg 总闸——参数收窄(未知形状 raw warn)
2970
+ * → 单条字节块走 core/shared/sysmsg.ts 的 processSysMsgBlob 通用管线(解码 →
2971
+ * 信封 → 识别 → 分流)。表命中提取 data 体 → 精华快路径 claim 去重 → 信封包装
2972
+ * 广播;未识别 / 提取失败落校准路径,不广播半成品。
2973
+ */
2974
+ /** Milky sysmsg 域处理器(解码识别分流 + 精华快路径去重)。 */
2975
+ var MilkyInboundSysMsg = class {
2976
+ deps;
2977
+ constructor(deps) {
2978
+ this.deps = deps;
2979
+ }
2980
+ /** onRecvSysMsg 总闸:参数收窄(未知形状 raw warn)→ 逐块走通用管线。 */
2981
+ handleRawArg(arg) {
2982
+ const blobs = narrowSysMsgBlobs(arg);
2983
+ if (blobs === null) {
2984
+ this.deps.logger?.warn({ raw: sliceRaw(JSON.stringify(arg)) }, "milky: onRecvSysMsg 未知参数形状");
2985
+ return;
2655
2986
  }
2987
+ for (const blob of blobs) processSysMsgBlob(blob, {
2988
+ scope: "milky",
2989
+ logger: this.deps.logger,
2990
+ decodeFailLevel: "debug",
2991
+ recognize: (msgType, subType) => recognizeMilkySysMsg(msgType, subType),
2992
+ onNotice: (tree, env, rec) => this.handleHit(tree, env, rec)
2993
+ });
2994
+ }
2995
+ /** 表命中分流:提取 data 体 → 精华快路径 claim → 信封包装广播;失败落校准。 */
2996
+ async handleHit(tree, env, rec) {
2997
+ if (rec.kind !== "notice") return false;
2998
+ const data = rec.rule.extract(tree, env, () => 0, {
2999
+ selfUin: Number(this.deps.api.self.uin),
3000
+ time: env.time ?? Math.floor(Date.now() / 1e3)
3001
+ });
3002
+ if (data === null) return false;
3003
+ if (!this.deps.essence.claimFastPath(rec.rule.kind, data)) return true;
3004
+ this.deps.broadcast({
3005
+ time: env.time ?? Math.floor(Date.now() / 1e3),
3006
+ self_id: Number(this.deps.api.self.uin),
3007
+ event_type: rec.rule.kind,
3008
+ data
3009
+ });
3010
+ return true;
2656
3011
  }
2657
3012
  };
2658
3013
  // src/milky/transport.ts
@@ -2825,27 +3180,14 @@ function pathnameOf(url) {
2825
3180
  // src/milky/adapter.ts
2826
3181
  var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
2827
3182
  protocol = "milky";
2828
- msgChannel;
2829
- groupChannel;
2830
- buddyChannel;
2831
- recentContactChannel;
2832
- loginChannel;
2833
- /** peer_pin 翻转检测(批次三;启动期 getPinnedContacts 播种)。 */
2834
- pinWatch = new PinWatch();
2835
- /** friend_file_upload 双回调去重(同载荷,按 msgId)。 */
2836
- fileKeys = new RecentKeyCache(6e5);
2837
- /** essence 双路径去重(732:1 快路径 vs 列表 diff,键 群:seq:方向)。 */
2838
- essenceKeys = new RecentKeyCache(3e5);
2839
- /** 精华列表缓存(群号 → seq → 条目{操作者/发送者})。 */
2840
- essenceCaches = /* @__PURE__ */ new Map();
2841
- /** 精华列表拉取串行链(并发回写乱序会把新列表覆盖成旧列表)。 */
2842
- essenceChain = Promise.resolve();
2843
3183
  calibLogger;
2844
3184
  api;
3185
+ /** seq 双向登记索引(发送回查 / reply 回填 / 转发定位共享)。 */
2845
3186
  seqIndex = new MessageSeqIndex();
2846
3187
  /** 动作注册表(公共只读:装配方/测试枚举)。 */
2847
3188
  registry;
2848
- unsubscribes = [];
3189
+ /** 收链路事件管道(订阅 / 过滤 / 去重 / 翻译派发,2026-11-14 拆出)。 */
3190
+ pipeline;
2849
3191
  stopTransports = null;
2850
3192
  constructor(opts) {
2851
3193
  super({
@@ -2857,13 +3199,38 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
2857
3199
  onReload: (config) => this.reloadTransports(config)
2858
3200
  }
2859
3201
  });
2860
- this.msgChannel = opts.msgChannel;
2861
- this.groupChannel = opts.groupChannel;
2862
- this.buddyChannel = opts.buddyChannel;
2863
- this.recentContactChannel = opts.recentContactChannel;
2864
- this.loginChannel = opts.loginChannel;
2865
3202
  this.calibLogger = opts.logger;
2866
3203
  this.api = new MilkyApi(opts, this.seqIndex);
3204
+ const base = {
3205
+ api: this.api,
3206
+ seqIndex: this.seqIndex,
3207
+ broadcast: (event) => this.broadcastEvent(event),
3208
+ logger: opts.logger
3209
+ };
3210
+ const enrich = new MilkyEnrichment({ api: this.api });
3211
+ const essence = new MilkyInboundEssence(base);
3212
+ this.pipeline = new MilkyEventPipeline({
3213
+ msgChannel: opts.msgChannel,
3214
+ ...opts.groupChannel !== void 0 ? { groupChannel: opts.groupChannel } : {},
3215
+ ...opts.buddyChannel !== void 0 ? { buddyChannel: opts.buddyChannel } : {},
3216
+ ...opts.recentContactChannel !== void 0 ? { recentContactChannel: opts.recentContactChannel } : {},
3217
+ ...opts.loginChannel !== void 0 ? { loginChannel: opts.loginChannel } : {},
3218
+ essence,
3219
+ message: new MilkyInboundMessage({
3220
+ ...base,
3221
+ enrich
3222
+ }),
3223
+ sysMsg: new MilkyInboundSysMsg({
3224
+ ...base,
3225
+ essence
3226
+ }),
3227
+ request: new MilkyInboundRequest({
3228
+ ...base,
3229
+ enrich
3230
+ }),
3231
+ fileNotice: new MilkyInboundFileNotice(base),
3232
+ pin: new MilkyInboundPin(base)
3233
+ });
2867
3234
  this.registry = createMilkyActionRegistry({ api: this.api });
2868
3235
  }
2869
3236
  /** 启动传输 + 订阅(enabled=false 空转:不订阅不起传输)。 */
@@ -2883,7 +3250,7 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
2883
3250
  this.stopTransports = set.close;
2884
3251
  await Promise.all(set.adapters.map((a) => a.open()));
2885
3252
  }
2886
- this.subscribe();
3253
+ this.pipeline.subscribe();
2887
3254
  this.calibLogger?.info({
2888
3255
  host: config.host,
2889
3256
  port: config.port,
@@ -2897,434 +3264,13 @@ var NapukettoMilkyAdapter = class extends BaseProtocolAdapter {
2897
3264
  }
2898
3265
  /** 停止:退订 + 关传输。 */
2899
3266
  async stopAll() {
2900
- this.unsubscribeAll();
3267
+ this.pipeline.unsubscribeAll();
2901
3268
  if (this.stopTransports !== null) {
2902
3269
  await this.stopTransports();
2903
3270
  this.stopTransports = null;
2904
3271
  }
2905
3272
  }
2906
- /** 订阅 kernel 事件(消息 + 群通知 + 好友请求,幂等)。 */
2907
- subscribe() {
2908
- if (this.unsubscribes.length > 0) return;
2909
- this.unsubscribes.push(subscribeRawMessages(this.msgChannel, (msg) => {
2910
- this.handleIncoming(msg);
2911
- }));
2912
- this.unsubscribes.push(this.msgChannel.on("Msg/onRecvSysMsg", (arg) => {
2913
- this.handleSysMsg(arg);
2914
- }));
2915
- this.unsubscribes.push(this.msgChannel.on("Msg/onRecvOfflineFileMsg", (msgs) => {
2916
- this.handleFileMessages(msgs);
2917
- }), this.msgChannel.on("Msg/onFileMsgCome", (msgs) => {
2918
- this.handleFileMessages(msgs);
2919
- }));
2920
- this.subscribeGroupAndBuddy();
2921
- this.subscribeBatch3();
2922
- }
2923
- /** 群通知 + 好友请求通道(P1 事件源;通道缺省不订阅)。 */
2924
- subscribeGroupAndBuddy() {
2925
- if (this.groupChannel !== void 0) {
2926
- const groupChannel = this.groupChannel;
2927
- this.unsubscribes.push(groupChannel.on("Group/onGroupNotifiesUpdated", (doubt, notifies) => {
2928
- this.handleGroupNotifies(doubt, notifies);
2929
- }));
2930
- }
2931
- if (this.buddyChannel !== void 0) {
2932
- const buddyChannel = this.buddyChannel;
2933
- this.unsubscribes.push(buddyChannel.on("Buddy/onBuddyReqChange", (arg) => {
2934
- this.handleBuddyReqs(arg);
2935
- }));
2936
- }
2937
- }
2938
- /** 批次三通道:精华列表变更 / 置顶翻转(含播种基线)/ bot_offline。 */
2939
- subscribeBatch3() {
2940
- if (this.groupChannel !== void 0) {
2941
- const groupChannel = this.groupChannel;
2942
- this.unsubscribes.push(groupChannel.on("Group/onGroupEssenceListChange", (arg) => {
2943
- this.handleEssenceChange(arg);
2944
- }));
2945
- }
2946
- if (this.recentContactChannel !== void 0) {
2947
- const recentContactChannel = this.recentContactChannel;
2948
- this.unsubscribes.push(recentContactChannel.on("RecentContact/onRecentContactListChangedVer2", (lists) => {
2949
- this.handlePinChanges(lists);
2950
- }));
2951
- this.seedPinWatch();
2952
- }
2953
- if (this.loginChannel !== void 0) {
2954
- const loginChannel = this.loginChannel;
2955
- this.unsubscribes.push(loginChannel.on("Login/onLoginDisConnected", (...args) => {
2956
- this.broadcastBotOffline("disconnected", args);
2957
- }), loginChannel.on("Login/onLogoutSucceed", (...args) => {
2958
- this.broadcastBotOffline("logout", args);
2959
- }));
2960
- }
2961
- }
2962
- /** 退订(幂等)。 */
2963
- unsubscribeAll() {
2964
- for (const off of this.unsubscribes) off();
2965
- this.unsubscribes = [];
2966
- }
2967
- /** 单条消息:seq 登记 → grayTip→notice / 群文件上传 / message_receive(自消息不上报)。 */
2968
- async handleIncoming(msg) {
2969
- this.seqIndex.record(msg);
2970
- this.recordForward(msg);
2971
- if (hasGrayTip(msg)) {
2972
- await this.broadcastNotice(msg);
2973
- return;
2974
- }
2975
- const upload = toGroupFileUploadEvent(msg, this.api.self.uin);
2976
- if (upload !== null) {
2977
- this.broadcastEvent(upload);
2978
- return;
2979
- }
2980
- if (String(msg.senderUin) === this.api.self.uin) return;
2981
- this.broadcastEvent(await this.buildMessageReceiveEvent(msg));
2982
- }
2983
- /** grayTip → notice 事件广播(REVOKE 走 message_recall,其余走 notice 翻译)。 */
2984
- async broadcastNotice(msg) {
2985
- const uidToUin = await this.resolveUidToUin(collectGrayTipUids(msg));
2986
- const event = findRevokeElement(msg) !== void 0 ? toMessageRecallEvent(msg, {
2987
- selfUin: this.api.self.uin,
2988
- ...uidToUin !== void 0 ? { uidToUin } : {}
2989
- }) : toMilkyNoticeEvent(msg, this.noticeCtx(uidToUin));
2990
- if (event !== null) this.broadcastEvent(event);
2991
- }
2992
- /** notice 翻译上下文(uidToUin 缺省空 Map;logger 透传校准日志)。 */
2993
- noticeCtx(uidToUin) {
2994
- return {
2995
- selfUin: this.api.self.uin,
2996
- ...uidToUin !== void 0 ? { uidToUin } : { uidToUin: /* @__PURE__ */ new Map() },
2997
- ...this.calibLogger !== void 0 ? { logger: this.calibLogger } : {}
2998
- };
2999
- }
3000
- /** 群通知通道:入群请求 / 成员邀请 / 邀请自身(uid→uin 批量后翻译)。 */
3001
- async handleGroupNotifies(doubt, notifies) {
3002
- const ctx = await this.requestCtx(collectNotifyUids(notifies));
3003
- for (const notify of notifies) {
3004
- const event = toGroupRequestEvent(notify, doubt, ctx);
3005
- if (event !== null) this.broadcastEvent(event);
3006
- }
3007
- }
3008
- /** 好友请求通道:Buddy/onBuddyReqChange(防御收窄,未知形状 raw 日志)。 */
3009
- handleBuddyReqs(arg) {
3010
- const reqs = narrowBuddyReqs(arg);
3011
- if (reqs === null) {
3012
- this.calibLogger?.warn({ raw: truncate(JSON.stringify(arg)) }, "milky: onBuddyReqChange 未知参数形状");
3013
- return;
3014
- }
3015
- (async () => {
3016
- const ctx = await this.requestCtx(reqs.map((req) => req.friendUid));
3017
- for (const req of reqs) this.broadcastEvent(toFriendRequestEvent(req, ctx));
3018
- })();
3019
- }
3020
- /** request 翻译上下文(uid→uin 批量转换)。 */
3021
- async requestCtx(uids) {
3022
- const uidToUin = await this.resolveUidToUin(uids);
3023
- return {
3024
- selfUin: this.api.self.uin,
3025
- ...uidToUin !== void 0 ? { uidToUin } : { uidToUin: /* @__PURE__ */ new Map() }
3026
- };
3027
- }
3028
- /** message_receive 组装:at uid→uin + reply 回填 + 群实体回填 + 转发段(全部 fail-soft)。 */
3029
- async buildMessageReceiveEvent(msg) {
3030
- const elements = toCanonicalElements(msg);
3031
- const ctx = { selfUin: this.api.self.uin };
3032
- await this.fillMentionUids(elements, ctx);
3033
- this.fillReplyMeta(elements, ctx);
3034
- await this.fillGroupEntities(msg, ctx);
3035
- const forward = msg.elements.find((el) => el.multiForwardMsgElement != null)?.multiForwardMsgElement;
3036
- if (forward !== void 0) ctx.forwardSegments = [incomingForwardSegment(forward.resId, forward.fileName)];
3037
- return toMessageReceiveEvent(msg, ctx);
3038
- }
3039
- /** at uid → uin 批量转换(mention.user_id 用;失败 mention 段跳过)。 */
3040
- async fillMentionUids(elements, ctx) {
3041
- const atUids = elements.filter((el) => el.type === "at" && el.target !== "all").map((el) => el.target);
3042
- if (atUids.length === 0) return;
3043
- try {
3044
- ctx.uidToUin = await this.api.uidToUin(atUids);
3045
- } catch {}
3046
- }
3047
- /** reply 引用元信息回填(seqIndex 命中即用;未命中不强查)。 */
3048
- fillReplyMeta(elements, ctx) {
3049
- const replyIds = elements.filter((el) => el.type === "reply").map((el) => el.messageId);
3050
- const meta = this.seqIndex.collectReplyMeta(replyIds);
3051
- if (meta.size > 0) ctx.replyMeta = meta;
3052
- }
3053
- /** 群场景实体回填(GroupCache 缓存优先,失败最小实体兜底)。 */
3054
- async fillGroupEntities(msg, ctx) {
3055
- if (msg.chatType !== ChatType.GROUP || this.api.groupCache === void 0) return;
3056
- 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)]);
3057
- ctx.groupEntity = toGroupEntity(detail, msg.peerUid);
3058
- ctx.groupMemberEntity = toGroupMemberEntity(member, msg.peerUid, msg.senderUin);
3059
- }
3060
- /** 转发 resId → 定位登记(get_forwarded_messages 反查用)。 */
3061
- recordForward(msg) {
3062
- const forward = msg.elements.find((el) => el.multiForwardMsgElement != null)?.multiForwardMsgElement;
3063
- if (forward !== void 0 && forward.resId !== "") this.seqIndex.recordForward(forward.resId, {
3064
- chatType: msg.chatType,
3065
- peerUid: msg.peerUid,
3066
- msgId: msg.msgId
3067
- });
3068
- }
3069
- /**
3070
- * sysmsg 总闸:解码 → 识别 → 表命中才广播(732:16 表情回应 / 732:1 精华
3071
- * 设置);未识别 debug 校准日志。规则提取失败不广播半成品事件。
3072
- */
3073
- handleSysMsg(arg) {
3074
- const blobs = narrowSysMsgBlobs(arg);
3075
- if (blobs === null) {
3076
- this.calibLogger?.warn({ raw: truncate(JSON.stringify(arg)) }, "milky: onRecvSysMsg 未知参数形状");
3077
- return;
3078
- }
3079
- for (const blob of blobs) this.handleSysMsgBlob(blob);
3080
- }
3081
- /** 单条字节块:解码 → 识别 → 提取;任一步失败走校准日志返回 null。 */
3082
- handleSysMsgBlob(blob) {
3083
- const hit = this.sysMsgHit(blob);
3084
- if (hit === null) return;
3085
- if (!this.claimEssenceFastPath(hit)) return;
3086
- this.broadcastEvent({
3087
- time: hit.env.time ?? Math.floor(Date.now() / 1e3),
3088
- self_id: Number(this.api.self.uin),
3089
- event_type: hit.rule.kind,
3090
- data: hit.data
3091
- });
3092
- }
3093
- /** 解码 + 识别 + 提取(每步失败各自打 debug 校准日志)。 */
3094
- sysMsgHit(blob) {
3095
- const tree = decodeProtoTree(blob);
3096
- if (tree === null) {
3097
- this.calibLogger?.debug({ raw: toHex(blob).slice(0, 1024) }, "milky: onRecvSysMsg protobuf 解码失败");
3098
- return null;
3099
- }
3100
- const env = extractSysMsgEnvelope(tree);
3101
- const rule = this.sysMsgRule(env, tree, blob);
3102
- if (rule === null) return null;
3103
- return {
3104
- env,
3105
- rule: rule.rule,
3106
- data: rule.data
3107
- };
3108
- }
3109
- /** 识别 + 规则提取(未识别/提取失败 → 校准日志 + null)。 */
3110
- sysMsgRule(env, tree, blob) {
3111
- const rec = recognizeMilkySysMsg(env.msgType, env.subType);
3112
- if (rec.kind !== "notice") {
3113
- this.calibLogger?.debug({
3114
- verdict: rec.kind,
3115
- msgType: env.msgType,
3116
- subType: env.subType,
3117
- strings: env.strings,
3118
- raw: toHex(blob).slice(0, 1024)
3119
- }, "milky: onRecvSysMsg 校准数据(未识别,不广播)");
3120
- return null;
3121
- }
3122
- const ctx = {
3123
- selfUin: Number(this.api.self.uin),
3124
- time: env.time ?? Math.floor(Date.now() / 1e3)
3125
- };
3126
- const data = rec.rule.extract(tree, env, () => 0, ctx);
3127
- if (data === null) {
3128
- this.calibLogger?.debug({
3129
- kind: rec.rule.kind,
3130
- msgType: env.msgType,
3131
- subType: env.subType
3132
- }, "milky: sysmsg 规则提取失败(不广播)");
3133
- return null;
3134
- }
3135
- return {
3136
- rule: rec.rule,
3137
- data
3138
- };
3139
- }
3140
- /** 精华快路径去重守卫:非精华事件恒 true;精华事件 claim 失败(已由列表 diff 抢发)→ false。 */
3141
- claimEssenceFastPath(hit) {
3142
- if (hit.rule.kind !== "group_essence_message_change") return true;
3143
- const essence = hit.data;
3144
- return this.essenceKeys.claim(`${essence.group_id}:${essence.message_seq}:1`);
3145
- }
3146
- /** 私聊文件消息 → friend_file_upload(双回调同载荷,按 msgId 去重)。 */
3147
- handleFileMessages(msgs) {
3148
- forEachRawMessage(msgs, (msg) => {
3149
- const data = toFriendFileUploadData(msg, this.api.self.uin, /* @__PURE__ */ new Map());
3150
- if (data === null) return;
3151
- if (data.user_id === 0) this.calibLogger?.debug({
3152
- msgId: msg.msgId,
3153
- senderUid: msg.senderUid
3154
- }, "milky: friend_file_upload senderUin 缺失(user_id=0)");
3155
- if (!this.fileKeys.claim(`file:${msg.msgId}`)) return;
3156
- this.broadcastEvent({
3157
- time: secondsOf(msg.msgTime),
3158
- self_id: Number(this.api.self.uin),
3159
- event_type: "friend_file_upload",
3160
- data
3161
- });
3162
- });
3163
- }
3164
- /** 精华列表变更:拉全量列表 diff(remove 路径 + operator 回填;串行防乱序)。 */
3165
- handleEssenceChange(arg) {
3166
- const groupCode = narrowEssenceGroupArg(arg);
3167
- if (groupCode === null) {
3168
- this.calibLogger?.warn({ raw: truncate(JSON.stringify(arg)) }, "milky: onGroupEssenceListChange 未知参数形状");
3169
- return;
3170
- }
3171
- this.essenceChain = this.essenceChain.then(() => this.syncEssenceList(groupCode), () => void 0);
3172
- }
3173
- /** 单群精华列表同步:拉取 → diff → 广播 → 更新缓存(基线未建立只建基线)。 */
3174
- async syncEssenceList(groupCode) {
3175
- let items;
3176
- try {
3177
- items = await this.api.webApi.getEssenceMsgList(groupCode);
3178
- } catch (e) {
3179
- this.calibLogger?.warn({
3180
- group: groupCode,
3181
- err: String(e)
3182
- }, "milky: 精华列表拉取失败(diff 跳过)");
3183
- return;
3184
- }
3185
- const prev = this.essenceCaches.get(groupCode);
3186
- const { cache, added, removed } = diffEssenceList(prev, items);
3187
- this.essenceCaches.set(groupCode, cache);
3188
- if (prev === void 0) return;
3189
- const selfId = Number(this.api.self.uin);
3190
- const now = Math.floor(Date.now() / 1e3);
3191
- this.broadcastEssenceAdded(groupCode, added, now, selfId);
3192
- this.broadcastEssenceRemoved(groupCode, removed, now, selfId);
3193
- }
3194
- /** diff 新增项广播(is_set=true;operator = add_digest_uin;快路径已发则跳过)。 */
3195
- broadcastEssenceAdded(groupCode, added, now, selfId) {
3196
- for (const item of added) {
3197
- if (!this.essenceKeys.claim(`${groupCode}:${item.messageSeq}:1`)) continue;
3198
- const data = essenceAddedData(groupCode, item);
3199
- this.broadcastEvent({
3200
- time: now,
3201
- self_id: selfId,
3202
- event_type: "group_essence_message_change",
3203
- data
3204
- });
3205
- }
3206
- }
3207
- /** diff 移除项广播(is_set=false;取消无 sysmsg,operator 不可得省略)。 */
3208
- broadcastEssenceRemoved(groupCode, removed, now, selfId) {
3209
- for (const seq of removed) {
3210
- if (!this.essenceKeys.claim(`${groupCode}:${seq}:0`)) continue;
3211
- this.broadcastEvent({
3212
- time: now,
3213
- self_id: selfId,
3214
- event_type: "group_essence_message_change",
3215
- data: {
3216
- group_id: Number(groupCode),
3217
- message_seq: seq,
3218
- is_set: false
3219
- }
3220
- });
3221
- }
3222
- }
3223
- /** 会话列表变更 → peer_pin_change(topFlag 翻转检测,条目自带 chatType 判场景)。 */
3224
- handlePinChanges(lists) {
3225
- const arr = Array.isArray(lists) ? lists : [lists];
3226
- for (const list of arr) this.handlePinChangeList(list);
3227
- }
3228
- /** 单个变更列表:changedList 逐条目翻转检测 + 广播。 */
3229
- handlePinChangeList(list) {
3230
- for (const entry of changedListOf(list)) this.handlePinEntry(entry);
3231
- }
3232
- /** 单个变更条目:翻译 + 翻转检测 + 广播(首见/未变/不支持场景静默跳过)。 */
3233
- handlePinEntry(entry) {
3234
- const payload = pinPayloadOf(entry);
3235
- if (payload === null) return;
3236
- if (!this.pinWatch.observe(payload.chatType, payload.peerUin, payload.topFlag)) return;
3237
- this.broadcastEvent({
3238
- time: secondsOf(payload.topFlagTime),
3239
- self_id: Number(this.api.self.uin),
3240
- event_type: "peer_pin_change",
3241
- data: payload.data
3242
- });
3243
- }
3244
- /** 启动基线:置顶会话播种(重启后首个取消置顶也能观测到翻转;失败静默)。 */
3245
- seedPinWatch() {
3246
- this.api.recentContactApi.getPinnedContacts().then((pins) => {
3247
- this.pinWatch.seed(pins);
3248
- }).catch(() => void 0);
3249
- }
3250
- /** bot_offline:Login 桥回调(载荷零样本,reason 固定值 + raw 校准日志待野捕)。 */
3251
- broadcastBotOffline(reason, args) {
3252
- this.calibLogger?.debug({
3253
- reason,
3254
- raw: truncate(JSON.stringify(args))
3255
- }, "milky: bot_offline(reason 为固定值,回调载荷待野捕校准)");
3256
- this.broadcastEvent({
3257
- time: Math.floor(Date.now() / 1e3),
3258
- self_id: Number(this.api.self.uin),
3259
- event_type: "bot_offline",
3260
- data: { reason }
3261
- });
3262
- }
3263
- /** uid 批量 → uin(空集/失败返回 undefined 语义:调用方用空 Map)。 */
3264
- resolveUidToUin(uids) {
3265
- const unique = [...new Set(uids.filter((uid) => uid !== ""))];
3266
- if (unique.length === 0) return Promise.resolve(void 0);
3267
- return this.api.uidToUin(unique).catch(() => void 0);
3268
- }
3269
3273
  };
3270
- /** 是否含 grayTip 元素(与 OB11 收链路同判据)。 */
3271
- function hasGrayTip(msg) {
3272
- return msg.elements.some((el) => el.grayTipElement != null);
3273
- }
3274
- /** 撤回 grayTip 元素(非撤回消息返回 undefined)。 */
3275
- function findRevokeElement(msg) {
3276
- return msg.elements.find((el) => el.grayTipElement?.revokeElement != null)?.grayTipElement?.revokeElement;
3277
- }
3278
- /** 字符串截断(raw 日志防刷屏)。 */
3279
- function truncate(raw) {
3280
- return raw === void 0 ? "" : raw.slice(0, 2e3);
3281
- }
3282
- /** 数字串判别(uin / 秒级时间戳)。 */
3283
- const NUMERIC_RE = /^\d+$/;
3284
- /** diff 新增项 → 事件载荷(operator = add_digest_uin,非数字串省略)。 */
3285
- function essenceAddedData(groupCode, item) {
3286
- const base = {
3287
- group_id: Number(groupCode),
3288
- message_seq: item.messageSeq
3289
- };
3290
- if (item.operatorUin !== null && NUMERIC_RE.test(item.operatorUin)) return {
3291
- ...base,
3292
- operator_id: Number(item.operatorUin),
3293
- is_set: true
3294
- };
3295
- return {
3296
- ...base,
3297
- is_set: true
3298
- };
3299
- }
3300
- /** 变更列表 → changedList 条目数组(形状不符 → 空)。 */
3301
- function changedListOf(list) {
3302
- if (list === null || typeof list !== "object") return [];
3303
- const changed = list.changedList;
3304
- return Array.isArray(changed) ? changed : [];
3305
- }
3306
- /** 变更条目 → 翻转检测输入(null = 条目不支持/缺置顶字段)。 */
3307
- function pinPayloadOf(entry) {
3308
- if (entry === null || typeof entry !== "object") return null;
3309
- return pinPayloadFrom(entry);
3310
- }
3311
- function pinPayloadFrom(contact) {
3312
- const topFlag = contact.topFlag;
3313
- const payload = toPeerPinChangeData(contact);
3314
- if (topFlag === void 0 || payload === null) return null;
3315
- return {
3316
- chatType: contact.chatType,
3317
- peerUin: payload.peerUin,
3318
- topFlag,
3319
- topFlagTime: payload.topFlagTime,
3320
- data: payload.data
3321
- };
3322
- }
3323
- /** 秒级时间戳归一(空/非法 → 当前时间;topFlagTime/msgTime 均为秒级字符串)。 */
3324
- function secondsOf(raw) {
3325
- if (raw !== void 0 && NUMERIC_RE.test(raw)) return Number(raw);
3326
- return Math.floor(Date.now() / 1e3);
3327
- }
3328
3274
  // src/milky/config.ts
3329
3275
  /**
3330
3276
  * Milky 协议配置(zod schema,归属本包,ADR-012)