wezard 3.0.1 → 3.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/CLAUDE.md +14 -11
  2. package/README.md +2 -2
  3. package/cli/wezard.sh +56 -20
  4. package/config.example.jsonc +3 -0
  5. package/dist/cli/audit.js +11 -13
  6. package/dist/cli/audit.js.map +1 -1
  7. package/dist/cli/codex-hook.js +20 -17
  8. package/dist/cli/codex-hook.js.map +1 -1
  9. package/dist/cli/ext.js +271 -0
  10. package/dist/cli/ext.js.map +1 -0
  11. package/dist/cli/init.js +9 -13
  12. package/dist/cli/init.js.map +1 -1
  13. package/dist/cli/sync.js +3 -2
  14. package/dist/cli/sync.js.map +1 -1
  15. package/dist/cli/wx.js +7 -6
  16. package/dist/cli/wx.js.map +1 -1
  17. package/dist/daemon/aibot-media.js +28 -20
  18. package/dist/daemon/aibot-media.js.map +1 -1
  19. package/dist/daemon/approval.js +60 -37
  20. package/dist/daemon/approval.js.map +1 -1
  21. package/dist/daemon/channel-onboarding.js +61 -0
  22. package/dist/daemon/channel-onboarding.js.map +1 -0
  23. package/dist/daemon/channel-posts.js +56 -16
  24. package/dist/daemon/channel-posts.js.map +1 -1
  25. package/dist/daemon/channel-rebind.js +100 -0
  26. package/dist/daemon/channel-rebind.js.map +1 -0
  27. package/dist/daemon/channel-store.js.map +1 -1
  28. package/dist/daemon/channel.js +218 -466
  29. package/dist/daemon/channel.js.map +1 -1
  30. package/dist/daemon/chat-name.js +6 -2
  31. package/dist/daemon/chat-name.js.map +1 -1
  32. package/dist/daemon/claim.js +1 -45
  33. package/dist/daemon/claim.js.map +1 -1
  34. package/dist/daemon/classes.js +11 -13
  35. package/dist/daemon/classes.js.map +1 -1
  36. package/dist/daemon/config-api.js +5 -29
  37. package/dist/daemon/config-api.js.map +1 -1
  38. package/dist/daemon/control-socket.js +93 -0
  39. package/dist/daemon/control-socket.js.map +1 -0
  40. package/dist/daemon/danger-scrub.js +315 -0
  41. package/dist/daemon/danger-scrub.js.map +1 -0
  42. package/dist/daemon/danger.js +146 -16
  43. package/dist/daemon/danger.js.map +1 -1
  44. package/dist/daemon/detail.js +37 -15
  45. package/dist/daemon/detail.js.map +1 -1
  46. package/dist/daemon/exec-surface.js +108 -0
  47. package/dist/daemon/exec-surface.js.map +1 -0
  48. package/dist/daemon/external.js +595 -0
  49. package/dist/daemon/external.js.map +1 -0
  50. package/dist/daemon/http.js +97 -16
  51. package/dist/daemon/http.js.map +1 -1
  52. package/dist/daemon/inbound.js +91 -80
  53. package/dist/daemon/inbound.js.map +1 -1
  54. package/dist/daemon/index.js +1268 -171
  55. package/dist/daemon/index.js.map +1 -1
  56. package/dist/daemon/last-response.js +8 -17
  57. package/dist/daemon/last-response.js.map +1 -1
  58. package/dist/daemon/legacy-panes.js +67 -0
  59. package/dist/daemon/legacy-panes.js.map +1 -0
  60. package/dist/daemon/mcp-http.js.map +1 -1
  61. package/dist/daemon/me-room.js +137 -0
  62. package/dist/daemon/me-room.js.map +1 -0
  63. package/dist/daemon/media.js +14 -0
  64. package/dist/daemon/media.js.map +1 -1
  65. package/dist/daemon/message-format.js +5 -0
  66. package/dist/daemon/message-format.js.map +1 -1
  67. package/dist/daemon/mirror-bridge.js +77 -26
  68. package/dist/daemon/mirror-bridge.js.map +1 -1
  69. package/dist/daemon/notices.js +4 -5
  70. package/dist/daemon/notices.js.map +1 -1
  71. package/dist/daemon/onboarding.js +120 -45
  72. package/dist/daemon/onboarding.js.map +1 -1
  73. package/dist/daemon/peers.js +2 -2
  74. package/dist/daemon/peers.js.map +1 -1
  75. package/dist/daemon/plan-http.js +2 -3
  76. package/dist/daemon/plan-http.js.map +1 -1
  77. package/dist/daemon/reach.js +1 -5
  78. package/dist/daemon/reach.js.map +1 -1
  79. package/dist/daemon/room-bind.js +297 -0
  80. package/dist/daemon/room-bind.js.map +1 -0
  81. package/dist/daemon/room-facts.js +1 -1
  82. package/dist/daemon/room-facts.js.map +1 -1
  83. package/dist/daemon/room-hub.js +158 -19
  84. package/dist/daemon/room-hub.js.map +1 -1
  85. package/dist/daemon/room-overdue.js +90 -28
  86. package/dist/daemon/room-overdue.js.map +1 -1
  87. package/dist/daemon/room-watchdog.js +44 -22
  88. package/dist/daemon/room-watchdog.js.map +1 -1
  89. package/dist/daemon/rooms.js +101 -4
  90. package/dist/daemon/rooms.js.map +1 -1
  91. package/dist/daemon/session-scan.js +1 -1
  92. package/dist/daemon/session-scan.js.map +1 -1
  93. package/dist/daemon/short-id-log.js +43 -0
  94. package/dist/daemon/short-id-log.js.map +1 -0
  95. package/dist/daemon/spawn-tmux.js +12 -9
  96. package/dist/daemon/spawn-tmux.js.map +1 -1
  97. package/dist/daemon/steward-guard.js +1 -1
  98. package/dist/daemon/steward-guard.js.map +1 -1
  99. package/dist/daemon/steward-model.js +17 -3
  100. package/dist/daemon/steward-model.js.map +1 -1
  101. package/dist/daemon/steward-repair.js +171 -0
  102. package/dist/daemon/steward-repair.js.map +1 -0
  103. package/dist/daemon/steward.js +48 -9
  104. package/dist/daemon/steward.js.map +1 -1
  105. package/dist/daemon/tool-face.js +31 -0
  106. package/dist/daemon/tool-face.js.map +1 -0
  107. package/dist/daemon/turn-opening.js +8 -3
  108. package/dist/daemon/turn-opening.js.map +1 -1
  109. package/dist/daemon/wake-tail.js +2 -2
  110. package/dist/daemon/wake-tail.js.map +1 -1
  111. package/dist/daemon/wizard-memory.js +4 -10
  112. package/dist/daemon/wizard-memory.js.map +1 -1
  113. package/dist/daemon/wizard.js +153 -73
  114. package/dist/daemon/wizard.js.map +1 -1
  115. package/dist/daemon/ws.js +1 -1
  116. package/dist/daemon/ws.js.map +1 -1
  117. package/dist/mcp/output.js +27 -5
  118. package/dist/mcp/output.js.map +1 -1
  119. package/dist/mcp/relay.js +152 -0
  120. package/dist/mcp/relay.js.map +1 -0
  121. package/dist/mcp/tools.js +87 -39
  122. package/dist/mcp/tools.js.map +1 -1
  123. package/dist/shared/chat-http.js +65 -48
  124. package/dist/shared/chat-http.js.map +1 -1
  125. package/dist/shared/cli-local-status.js +28 -0
  126. package/dist/shared/cli-local-status.js.map +1 -0
  127. package/dist/shared/cli-socket.js +14 -0
  128. package/dist/shared/cli-socket.js.map +1 -0
  129. package/dist/shared/codex-hooks.js +5 -2
  130. package/dist/shared/codex-hooks.js.map +1 -1
  131. package/dist/shared/config.js +45 -45
  132. package/dist/shared/config.js.map +1 -1
  133. package/dist/shared/daemon-addr.js +23 -0
  134. package/dist/shared/daemon-addr.js.map +1 -0
  135. package/dist/shared/daemon-client.js +41 -0
  136. package/dist/shared/daemon-client.js.map +1 -0
  137. package/dist/shared/daemon-token.js +2 -2
  138. package/dist/shared/daemon-token.js.map +1 -1
  139. package/dist/shared/external.js +402 -0
  140. package/dist/shared/external.js.map +1 -0
  141. package/dist/shared/inject-view.js +48 -10
  142. package/dist/shared/inject-view.js.map +1 -1
  143. package/dist/shared/instance-id.js +21 -0
  144. package/dist/shared/instance-id.js.map +1 -0
  145. package/dist/shared/message-footer.js +8 -1
  146. package/dist/shared/message-footer.js.map +1 -1
  147. package/dist/shared/model-tiers.js +39 -1
  148. package/dist/shared/model-tiers.js.map +1 -1
  149. package/dist/shared/ports.js +56 -0
  150. package/dist/shared/ports.js.map +1 -0
  151. package/dist/shared/pricing.js +0 -5
  152. package/dist/shared/pricing.js.map +1 -1
  153. package/dist/shared/role-render.js +8 -7
  154. package/dist/shared/role-render.js.map +1 -1
  155. package/dist/shared/role-view.js +5 -2
  156. package/dist/shared/role-view.js.map +1 -1
  157. package/dist/shared/room-overdue.js +84 -12
  158. package/dist/shared/room-overdue.js.map +1 -1
  159. package/dist/shared/room-view.js +18 -4
  160. package/dist/shared/room-view.js.map +1 -1
  161. package/dist/shared/room.js +245 -28
  162. package/dist/shared/room.js.map +1 -1
  163. package/dist/shared/session-label.js +29 -51
  164. package/dist/shared/session-label.js.map +1 -1
  165. package/dist/shared/session-mcp.js +35 -57
  166. package/dist/shared/session-mcp.js.map +1 -1
  167. package/dist/shared/smarts.js +15 -30
  168. package/dist/shared/smarts.js.map +1 -1
  169. package/dist/shared/world.js +1 -1
  170. package/dist/shared/world.js.map +1 -1
  171. package/dist/svr/facts-store.js.map +1 -1
  172. package/dist/svr/index.js +57 -15
  173. package/dist/svr/index.js.map +1 -1
  174. package/hooks/pre-tool-use.sh +14 -10
  175. package/hooks/stop.sh +5 -3
  176. package/launchd/com.wezard.svr.plist.template +2 -0
  177. package/package.json +3 -1
  178. package/scripts/install.sh +12 -0
  179. package/systemd/wezard-svr.service.template +2 -0
  180. package/web/chat.js +81 -40
  181. package/dist/daemon/bot-mux.js +0 -161
  182. package/dist/daemon/bot-mux.js.map +0 -1
@@ -1,27 +1,21 @@
1
1
  // 频道(topic)桥: SDK 1.0.7 的 dispatch 表里没有 aibot_topic_event_callback,
2
- // 这一层在 SDK 丢掉帧之前接住它,把「频道里 @ 了机器人」翻译成一条普通的文本消息
3
- // 交给 inbound / mirror;出站再把 topic_id 的 markdown 换成频道的 send_post /
4
- // send_reply。群聊 / 单聊的路径完全不变。
2
+ // 这一层在 SDK 丢掉帧之前接住它。
5
3
  //
6
- // 频道里没有被 @ 的新帖子 / 新回复也会进来(topic_event / topic_reply_event)。
7
- // 这些不直接答,先交给每个 bot 的「判官」:判官是一个只读最近几条消息的轻量 wizard,
8
- // 只回 JSON {respond, reason};respond 才把原帖交给主 wizard。
9
- // P7-S3: strict 频道 (chatPolicy/首见判定) 里判官多一职 —— 无人点名的人话是否开义务、
10
- // 落给谁 (respond 即开义务, rewrite 句首点名即落人); 出站终句不再包装成评论 (sendPost)。
11
- import { spawn } from "node:child_process";
4
+ // 2026-11-23 起频道 / 帖子都是 room (docs/room/channel-monitor.md):
5
+ // - 频道 room id = chat:<topic_id>; 帖子 room id = chat:<opk…> (原生帧的 chatid)。
6
+ // - 没被 @ 的新帖 / 还没配上 opk 的评论 → 频道 room 的一行人话 (带 post);
7
+ // 配上 opk 之后的评论 → 帖子 room 的一行人话。
8
+ // - @ 机器人的原生帧照旧由 inbound 送进帖子会话 (也就是帖子 room 的那条人话);
9
+ // 同一句的 topic_at_bot 事件只用来学配对 (post_id ↔ opk ↔ topic_id) 与兜底。
10
+ // - 判官 (一次性 JSON 判定) 已删: 每个 room 一个常驻 monitor 成员, 由它决定激活谁
11
+ // (shared/room.ts 的 activate 行); 这里只负责把话落进对的 room。
12
12
  import { join } from "node:path";
13
13
  import { generateReqId } from "@wecom/aibot-node-sdk";
14
- import { pickTier } from "../shared/model-tiers.js";
15
- import { resolveCliBackend } from "../shared/cli-backends.js";
16
- import { augmentedPath } from "../shared/exec-path.js";
17
- import { baseOfKey, keyOf, sameBot } from "../shared/session-label.js";
18
14
  import { sleep } from "../shared/std.js";
19
- import { identityOf, wizardStore } from "./wizard.js";
20
- import { stewardIdentityOf } from "./steward.js";
21
- import { learnChannelPost } from "./channel-posts.js";
15
+ import { learnChannelPost, postBaseOf } from "./channel-posts.js";
22
16
  import { expandHome } from "../shared/paths.js";
17
+ import { inboxName, saveToInbox, sniffExt } from "./media.js";
23
18
  import { ChannelStore } from "./channel-store.js";
24
- import { formatChannelContext, pickQuery, wantsHistory, withoutMsg } from "./channel-context.js";
25
19
  const TOPIC_EVENT = "aibot_topic_event_callback";
26
20
  const CMD_POST = "aibot_topic_send_post";
27
21
  const CMD_REPLY = "aibot_topic_send_reply";
@@ -33,27 +27,14 @@ const CMD_SEARCH_RESULT = "get_search_result";
33
27
  const topics = new Set();
34
28
  /** 把 topic_id 登记为已知频道 (onTopic 里自动做; 导出给测试 / 显式注册面用)。 */
35
29
  export const registerTopic = (topicId) => { topics.add(topicId); };
36
- /** 入站事件 msgid → 它所属的帖子;replyStream 用 streamId 找回来。 */
37
- const byStream = new Map();
38
- /** topic 上最近一条帖子,主动消息尽量挂成它的评论。 */
39
- const lastPost = new Map();
40
30
  /** 频道里最近一个说话的人;审批卡改投他的私聊,频道不支持按钮卡片。 */
41
31
  const lastAsker = new Map();
42
32
  /** 事件可能重投;msgid 去重表有界。 */
43
33
  const seen = new Set();
44
- /** 已经交给主 wizard 的 post / reply;判官与直接 @ 可能同时到,谁先到谁答。 */
45
- const dispatched = new Set();
46
- /** post_id → 是否收到过 topic_at_bot。只有被 @ 过的帖子才能用 send_reply 评论;
47
- * 未被 @ 的新帖只能 send_post 主动发(官方“回复被@的内容” vs “主动发内容”)。 */
48
- const replyOk = new Map();
49
- /** 判官串行:同一 topic 一次只跑一个判断,一次 -p 进程更不该并发抢占。 */
50
- const judgeQueues = new Map();
51
34
  /** 企微原生入站已带上的频道 @ (aibot_msg_callback, compat_info.source=channel): asker → 到达记录。
52
- * 企微现在把频道里 @ 机器人的话**两路**同时推: 原生帧 (chatid = 该帖子自己的 opk… 群 id) 与
53
- * topic_at_bot 事件 (topic_id = 频道)。两路都投 = 同一句话由两个 wizard 各答一遍 —— 2026-11-17
54
- * test1 频道实录: 帖子会话绑了管家, chat:<topic_id> 的默认会话也在答, 还经 lastPost 答进了别的帖子。
55
- * 原生帧由 inbound 记一笔, topic_at_bot 等一拍认领 (一帧只抵一个事件); 等不到 (企微没推原生帧)
56
- * 才由桥自己投 —— 兜底不丢话。 */
35
+ * 企微把频道里 @ 机器人的话**两路**同时推: 原生帧 (chatid = 该帖子自己的 opk… 群 id) 与
36
+ * topic_at_bot 事件 (topic_id = 频道)。原生帧由 inbound 记一笔, topic_at_bot 等一拍认领
37
+ * (一帧只抵一个事件); 等不到 (企微没推原生帧) 才由桥自己落一行, 兜底不丢话。 */
57
38
  const nativeFrames = new Map();
58
39
  const NATIVE_WAIT_MS = 3000;
59
40
  /** 原生帧可能比事件先到: 认领窗口往前放这么多。 */
@@ -87,6 +68,87 @@ const MENTION_RE = /\$\{inline_mention(?::[^}]*)?\}/g;
87
68
  const FILE_RE = /\$\{inline_file(?::[^}]*)?\}/g;
88
69
  const cleanContent = (s) => String(s ?? "").replace(MENTION_RE, "").replace(FILE_RE, "").trim();
89
70
  const clip = (s, n = 300) => (s.length > n ? s.slice(0, n) + "…" : s);
71
+ const NO_MEDIA = { images: [], files: [] };
72
+ /** ChannelHuman 的媒体字段: 没有就不写 (账本行不为空字段多一截)。 */
73
+ const mediaOf = (m) => ({
74
+ ...(m.images.length ? { images: m.images } : {}), ...(m.files.length ? { files: m.files } : {}),
75
+ });
76
+ /** 回包里有几份媒体 (纯读字段, 不下载) —— 日志与「空正文但有图」的判定用。 */
77
+ export const mediaCountOf = (item) => {
78
+ const it = item;
79
+ return {
80
+ images: Array.isArray(it?.image_list) ? it.image_list.length : 0,
81
+ files: Array.isArray(it?.inline_file_list) ? it.inline_file_list.length : 0,
82
+ };
83
+ };
84
+ const cookieOf = (x) => x.cookie_name && x.cookie_value ? { cookieName: String(x.cookie_name), cookieValue: String(x.cookie_value) } : {};
85
+ const mediaRefsOf = (item) => {
86
+ const it = item;
87
+ const images = (Array.isArray(it?.image_list) ? it.image_list : [])
88
+ .filter((m) => m?.download_url)
89
+ .map((m) => ({ url: String(m.download_url), ...cookieOf(m) }));
90
+ const files = (Array.isArray(it?.inline_file_list) ? it.inline_file_list : [])
91
+ .filter((f) => f?.download_url)
92
+ .map((f) => ({ url: String(f.download_url), ...cookieOf(f), name: String(f.file_name || "file") }));
93
+ return { images, files };
94
+ };
95
+ /** 拉一份频道媒体: 普通 HTTPS GET + cookie (频道素材没有 aeskey, 不是长连接加密媒体,
96
+ * 不能走 client.downloadFile)。失败只 warn —— 一条拉不到不该把整句话吞掉。 */
97
+ const fetchMedia = async (ref, log, msgid) => {
98
+ try {
99
+ const res = await fetch(ref.url, {
100
+ headers: ref.cookieName && ref.cookieValue ? { cookie: ref.cookieName + "=" + ref.cookieValue } : {},
101
+ signal: AbortSignal.timeout(20_000),
102
+ });
103
+ if (!res.ok) {
104
+ log.warn({ msgid, status: res.status }, "channel media: http not ok");
105
+ return undefined;
106
+ }
107
+ return Buffer.from(await res.arrayBuffer());
108
+ }
109
+ catch (e) {
110
+ log.warn({ msgid, err: e.message }, "channel media: download failed");
111
+ return undefined;
112
+ }
113
+ };
114
+ const downloadMedia = async (cfg, log, item, msgid) => {
115
+ const refs = mediaRefsOf(item);
116
+ const n = mediaCountOf(item);
117
+ if (!refs.images.length && !refs.files.length) {
118
+ // debug 口径: 回包到底带没带媒体 (字段长度), 用来在真机上确认企微真的把图放在 image_list 里。
119
+ if (n.images || n.files)
120
+ log.warn({ msgid, ...n }, "channel media: refs unreadable (no download_url)");
121
+ return NO_MEDIA;
122
+ }
123
+ const dir = expandHome(cfg.wrc.mirror.inboxDir);
124
+ const images = [];
125
+ const files = [];
126
+ let i = 0;
127
+ for (const ref of refs.images) {
128
+ const buf = await fetchMedia(ref, log, msgid);
129
+ if (!buf)
130
+ continue;
131
+ const saved = saveToInbox(dir, inboxName(msgid, i++, "image" + sniffExt(buf)), buf);
132
+ if ("reason" in saved) {
133
+ log.warn({ msgid, reason: saved.reason }, "channel media: not saved");
134
+ continue;
135
+ }
136
+ images.push(saved.path);
137
+ }
138
+ for (const ref of refs.files) {
139
+ const buf = await fetchMedia(ref, log, msgid);
140
+ if (!buf)
141
+ continue;
142
+ const saved = saveToInbox(dir, inboxName(msgid, i++, ref.name), buf);
143
+ if ("reason" in saved) {
144
+ log.warn({ msgid, reason: saved.reason }, "channel media: not saved");
145
+ continue;
146
+ }
147
+ files.push({ path: saved.path, name: ref.name });
148
+ }
149
+ log.info({ msgid, ...n, savedImages: images.length, savedFiles: files.length }, "channel media saved");
150
+ return { images, files };
151
+ };
90
152
  const replyBody = (frame) => frame?.body ?? frame;
91
153
  const call = async (client, cmd, body) => {
92
154
  // reply() 只是「带 cmd 的 WS 请求」;req_id 自造,服务端回执按它匹配。
@@ -123,7 +185,7 @@ const ensureStore = (cfg) => {
123
185
  const h = cfg.wrc.channel.history;
124
186
  if (!h.enabled)
125
187
  return undefined;
126
- const key = `${cfg.daemon.stateDir}|${h.keepDays}|${h.maxMessages}`;
188
+ const key = cfg.daemon.stateDir + "|" + h.keepDays + "|" + h.maxMessages;
127
189
  if (!store || storeKey !== key) {
128
190
  store = new ChannelStore({
129
191
  dir: join(expandHome(cfg.daemon.stateDir), "channels"),
@@ -144,26 +206,27 @@ const atOf = (t) => {
144
206
  };
145
207
  const authorOf = (creator) => {
146
208
  const c = creator ?? {};
147
- return Number(c.type) === 1 ? `bot:${String(c.aibotid ?? "?").slice(0, 10)}` : String(c.userid ?? "user");
209
+ return Number(c.type) === 1 ? "bot:" + String(c.aibotid ?? "?").slice(0, 10) : String(c.userid ?? "user");
148
210
  };
149
- const postMsg = (p) => {
211
+ const postMsg = (p, media = NO_MEDIA) => {
150
212
  const id = String(p?.post_id ?? "");
151
213
  const text = cleanContent(p?.content);
152
- if (!id || !text)
214
+ if (!id || (!text && !media.images.length && !media.files.length))
153
215
  return undefined;
154
- return { id, kind: "post", postId: id, at: atOf(p?.create_time), author: authorOf(p?.creator), text };
216
+ return { id, kind: "post", postId: id, at: atOf(p?.create_time), author: authorOf(p?.creator), text,
217
+ ...(media.images.length ? { images: media.images } : {}), ...(media.files.length ? { files: media.files } : {}) };
155
218
  };
156
- const replyMsg = (r, postId) => {
219
+ const replyMsg = (r, postId, media = NO_MEDIA) => {
157
220
  const id = String(r?.reply_id ?? "");
158
221
  const text = cleanContent(r?.content);
159
- if (!id || !text)
222
+ if (!id || (!text && !media.images.length && !media.files.length))
160
223
  return undefined;
161
- return { id, kind: "reply", postId: String(r?.post_id ?? postId), at: atOf(r?.create_time), author: authorOf(r?.creator), text };
224
+ return { id, kind: "reply", postId: String(r?.post_id ?? postId), at: atOf(r?.create_time), author: authorOf(r?.creator), text,
225
+ ...(media.images.length ? { images: media.images } : {}), ...(media.files.length ? { files: media.files } : {}) };
162
226
  };
163
- /** 最近消息里活跃的其他机器人 (§6 邻居感知): bot:<id> → 条数, 自己 (selfBot) 已剔除。
164
- * 判官 prompt 的 others 段与主 wizard 的注入上下文共用这一份聚合。 */
227
+ /** 最近消息里活跃的其他机器人 (§6 邻居感知): bot:<id> → 条数, 自己 (selfBot) 已剔除。 */
165
228
  export const botAuthors = (msgs, selfBot = "") => {
166
- const self = selfBot ? `bot:${selfBot.slice(0, 10)}` : "";
229
+ const self = selfBot ? "bot:" + selfBot.slice(0, 10) : "";
167
230
  const n = new Map();
168
231
  for (const m of msgs) {
169
232
  const a = m?.author ?? "";
@@ -176,7 +239,7 @@ export const botAuthors = (msgs, selfBot = "") => {
176
239
  .slice(0, 8)
177
240
  .map(([id, count]) => ({ id, n: count }));
178
241
  };
179
- /** 记一条进本地缓存: 判官上下文 / 主 wizard 上下文 / read_channel 共用这一份。 */
242
+ /** 记一条进本地缓存: read_channel / 回填共用这一份。 */
180
243
  const record = async (cfg, topicId, msg) => {
181
244
  if (!msg)
182
245
  return;
@@ -192,18 +255,10 @@ const backfill = async (client, cfg, log, topicId) => {
192
255
  if ((await s.count(topicId)) >= h.mainPosts)
193
256
  return;
194
257
  const posts = await fetchRecent(client, topicId, h.mainPosts, log);
195
- for (const m of posts.map(postMsg).filter((x) => !!x))
258
+ for (const m of posts.map((p) => postMsg(p)).filter((x) => !!x))
196
259
  await s.append(topicId, m);
197
260
  log.info({ topicId, n: posts.length }, "channel history backfilled");
198
261
  };
199
- /** 判官 / 上下文要看的最近帖子: 本地够用就不打接口。 */
200
- const recentPosts = async (client, cfg, log, topicId, limit) => {
201
- const local = (await ensureStore(cfg)?.recentPosts(topicId, limit)) ?? [];
202
- if (local.length >= Math.min(limit, 3))
203
- return local;
204
- const posts = await fetchRecent(client, topicId, limit, log);
205
- return posts.map(postMsg).filter((m) => !!m);
206
- };
207
262
  /** 官方搜索: 两步 (search 出 jobid → get_search_result 取摘要), 摘要只是 ID, 正文按 post 再取一次。 */
208
263
  const searchRemote = async (d, topicId, query, limit) => {
209
264
  const body = await call(d.client, CMD_SEARCH, { keyword_list: [query], topic_id_list: [topicId], limit });
@@ -232,7 +287,7 @@ const searchRemote = async (d, topicId, query, limit) => {
232
287
  return [];
233
288
  const b = await call(d.client, CMD_GET_POSTS, { topic_id: topicId, type: 0, post_id_list: ids.slice(0, Math.max(1, limit)) });
234
289
  const posts = b?.post_list ?? [];
235
- return posts.map(postMsg).filter((m) => !!m);
290
+ return posts.map((p) => postMsg(p)).filter((m) => !!m);
236
291
  };
237
292
  /** 先本地 grep (便宜、立刻), 不够再走官方搜索 (语义索引只在服务端)。 */
238
293
  const searchChannel = async (d, topicId, query, limit) => {
@@ -245,308 +300,96 @@ const searchChannel = async (d, topicId, query, limit) => {
245
300
  const remote = (await searchRemote(d, topicId, query, limit)).filter((m) => !seen.has(m.id));
246
301
  return [...local, ...remote].slice(0, limit);
247
302
  };
248
- /** 主 wizard 的上下文: 当前线程 + 最近 + (这句话有指代时才) 搜索命中。
249
- * 入站帧的身份 (topic / post / msgid) 永远写在首行 —— 即使 history 关掉、没有历史可带,
250
- * 主 agent 也必须能指回原始消息。 */
251
- const contextFor = async (d, topicId, postId, triggerId, text, extra = {}) => {
252
- const h = d.cfg.wrc.channel.history;
253
- // 触发这条上下文的回复 id 与线程根不同 (评论) 时一并带上: 目标 agent 要能指回
254
- // 那一句评论, 而不只是它所属的帖子。
255
- const replyId = triggerId && triggerId !== postId ? triggerId : "";
256
- const id = { topicId, postId, ...(replyId ? { replyId } : {}), ...(extra.msgid ? { msgid: extra.msgid } : {}) };
257
- const s = ensureStore(d.cfg);
258
- if (!s)
259
- return formatChannelContext({ ...id, budget: h.contextChars });
260
- const thread = withoutMsg(await s.thread(topicId, postId, h.mainReplies), triggerId);
261
- const recent = withoutMsg(await s.recentPosts(topicId, h.mainPosts), triggerId);
262
- const query = h.searchLimit > 0 && wantsHistory(text) ? pickQuery(text) : "";
263
- const hits = query ? (await searchChannel(d, topicId, query, h.searchLimit)).filter((m) => m.id !== triggerId) : [];
264
- // 邻居感知: 从同一批历史里聚合其他机器人 (自己剔除), 让主 wizard 知道谁也在场。
265
- const bots = botAuthors([...thread, ...recent, ...hits], extra.selfBot ?? "");
266
- return formatChannelContext({
267
- ...id,
268
- thread,
269
- recent,
270
- hits,
271
- ...(bots.length ? { bots } : {}),
272
- ...(query ? { query } : {}),
273
- ...(extra.reason ? { reason: extra.reason } : {}),
274
- ...(extra.intent ? { intent: extra.intent } : {}),
275
- budget: h.contextChars,
276
- });
277
- };
278
303
  const stamp = (ms) => {
279
304
  const d = new Date(ms);
280
- return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
305
+ const hh = String(d.getHours()).padStart(2, "0");
306
+ const mm = String(d.getMinutes()).padStart(2, "0");
307
+ return hh + ":" + mm;
281
308
  };
282
- const renderLines = (list) => list.map((m) => `[${stamp(m.at)}] ${m.author}: ${clip(m.text, 400)}`).join("\n");
309
+ /** read_channel 的一行: 正文 + 媒体 (图片 / 文件给本地路径, agent 直接 Read)。 */
310
+ const mediaTag = (m) => [...(m.images ?? []).map((p) => "[图: " + p + "]"), ...(m.files ?? []).map((f) => "[文件: " + f.name + " " + f.path + "]")].join(" ");
311
+ const renderLines = (list) => list.map((m) => {
312
+ const tag = mediaTag(m);
313
+ return "[" + stamp(m.at) + "] " + m.author + ": " + clip(m.text, 400) + (tag ? " " + tag : "");
314
+ }).join("\n");
283
315
  /** read_channel 的守护进程侧: 本地缓存优先, 搜不到 / 没缓存才问官方。 */
284
316
  export const readChannel = async (d, req) => {
285
317
  const topicId = req.topic.replace(/^chat:/, "").trim();
286
318
  if (!topicId)
287
- return { ok: false, text: "给一个频道: `chat:<topic_id>` 或裸 topic_id" };
319
+ return { ok: false, text: "给一个频道: chat:<topic_id> 或裸 topic_id" };
288
320
  const limit = Math.min(Math.max(Number(req.limit ?? 20) || 20, 1), 100);
289
321
  const query = (req.query ?? "").trim();
290
322
  if (query) {
291
323
  const hits = await searchChannel(d, topicId, query, limit);
292
- return { ok: true, text: hits.length ? `频道 ${topicId} · 搜「${query}」· ${hits.length} 条\n${renderLines(hits)}` : `频道 ${topicId} 没搜到「${query}」` };
324
+ return { ok: true, text: hits.length ? "频道 " + topicId + " · 搜「" + query + "」· " + hits.length + " 条\n" + renderLines(hits) : "频道 " + topicId + " 没搜到「" + query + "」" };
293
325
  }
294
326
  const local = (await ensureStore(d.cfg)?.slice(topicId, { ...(req.since !== undefined ? { since: req.since } : {}), ...(req.until !== undefined ? { until: req.until } : {}), limit })) ?? [];
295
327
  const list = local.length
296
328
  ? local
297
- : (await fetchRecent(d.client, topicId, Math.min(limit, 20), d.log)).map(postMsg).filter((m) => !!m);
298
- return { ok: true, text: list.length ? `频道 ${topicId} · ${list.length} 条\n${renderLines(list)}` : `频道 ${topicId} 没有读到消息 (没见过这个频道, 或还没缓存)` };
299
- };
300
- const emptyFrame = () => ({ headers: { req_id: "" } });
301
- const serial = (key, job) => {
302
- const prev = judgeQueues.get(key) ?? Promise.resolve();
303
- const next = prev.then(job, job);
304
- judgeQueues.set(key, next.catch(() => undefined).finally(() => {
305
- if (judgeQueues.get(key) === next)
306
- judgeQueues.delete(key);
307
- }));
308
- return next;
309
- };
310
- /** 逐个 `{` 数括号取 JSON 对象 (跳过字符串里的括号),比非贪婪正则可容下 rewrite 里的代码块。 */
311
- const jsonObjects = (text) => {
312
- const out = [];
313
- for (let i = 0; i < text.length; i += 1) {
314
- if (text[i] !== "{")
315
- continue;
316
- let depth = 0;
317
- let inStr = false;
318
- let esc = false;
319
- for (let j = i; j < text.length; j += 1) {
320
- const c = text[j];
321
- if (inStr) {
322
- if (esc)
323
- esc = false;
324
- else if (c === "\\")
325
- esc = true;
326
- else if (c === '"')
327
- inStr = false;
328
- }
329
- else if (c === '"')
330
- inStr = true;
331
- else if (c === "{")
332
- depth += 1;
333
- else if (c === "}") {
334
- depth -= 1;
335
- if (depth === 0) {
336
- out.push(text.slice(i, j + 1));
337
- i = j;
338
- break;
339
- }
340
- }
341
- }
342
- }
343
- return out;
344
- };
345
- const asText = (v) => (typeof v === "string" ? v.trim() : "");
346
- /** 字段容错: 只认字符串 (对象 / 数组当没写),并按第一个非空别名取值 —— 模型多吐、少吐都不炸。 */
347
- const asField = (o, keys) => keys.map((k) => asText(o[k])).find(Boolean) ?? "";
348
- /** respond 也容忍模型写成字符串 "true" / "false"。 */
349
- const asReply = (v) => typeof v === "boolean" ? v : v === "true" ? true : v === "false" ? false : undefined;
350
- export const parseVerdict = (text) => {
351
- for (const b of jsonObjects(text).reverse()) {
352
- try {
353
- const o = JSON.parse(b);
354
- const respond = asReply(o.respond);
355
- if (respond === undefined)
356
- continue;
357
- const intent = asField(o, ["intent", "意图"]);
358
- const rewrite = asField(o, ["rewrite", "rewritten", "instruction", "改写"]);
359
- return {
360
- respond,
361
- reason: asField(o, ["reason", "理由"]),
362
- ...(respond && intent ? { intent } : {}),
363
- ...(respond && rewrite ? { rewrite } : {}),
364
- };
365
- }
366
- catch { /* 不是这一块 */ }
367
- }
368
- const plain = text.trim();
369
- if (/^yes\b/i.test(plain))
370
- return { respond: true, reason: plain.slice(0, 120) };
371
- if (/^no\b/i.test(plain))
372
- return { respond: false, reason: plain.slice(0, 120) };
373
- return undefined;
374
- };
375
- /** 判官放行后交给主 agent 的正文: 改写优先, 原文永远可回溯。
376
- * 改写缺失 / 为空 / 与原文相同 → 原样用原帖, 改写这一层坏了也不丢消息。 */
377
- const bodyFor = (text, verdict) => {
378
- const rewrite = verdict.respond ? (verdict.rewrite ?? "").trim() : "";
379
- if (!rewrite || rewrite === text.trim())
380
- return text;
381
- return `${rewrite}\n——\n原帖:${text}`;
382
- };
383
- /** 判官是一次性判定, 不是一个住下来的会话: 一个 `-p` 进程进, stdout 出一行 JSON。
384
- * 不落会话 (--no-session-persistence)、不给工具 (--tools "")、不带 --settings /
385
- * --session-id —— 判官不该在 projects/ 里留痕被当成可镜像的会话, 也不该出审批卡。 */
386
- export const runJudgeOnce = (deps, prompt) => {
387
- const { cfg, log } = deps;
388
- const backend = resolveCliBackend(cfg.wrc);
389
- if (!backend.oneShotArgs) {
390
- log.warn({ backend: backend.name }, "channel judge: backend has no one-shot mode");
391
- return Promise.resolve(undefined);
392
- }
393
- const pick = pickTier(cfg, cfg.wrc.channel.judge.tier, {});
394
- const args = backend.oneShotArgs(prompt, {
395
- ...(pick.ok && pick.model ? { model: pick.model } : {}),
396
- ...(pick.ok && pick.effort ? { effort: pick.effort } : {}),
397
- });
398
- const timeoutMs = cfg.wrc.channel.judge.timeoutMs;
399
- return new Promise((resolve) => {
400
- const started = Date.now();
401
- const proc = spawn(backend.bin, args, {
402
- cwd: expandHome(cfg.wrc.cwd),
403
- env: { ...process.env, PATH: augmentedPath(process.env.PATH) },
404
- stdio: ["ignore", "pipe", "pipe"],
405
- });
406
- let out = "";
407
- let errTail = "";
408
- let settled = false;
409
- const finish = (text, why) => {
410
- if (settled)
411
- return;
412
- settled = true;
413
- clearTimeout(timer);
414
- const ms = Date.now() - started;
415
- if (text)
416
- log.info({ ms, tier: pick.ok ? pick.tier : undefined, model: pick.ok ? pick.model : undefined }, "channel judge ran");
417
- else
418
- log.warn({ ms, why, bin: backend.bin, stderrTail: errTail.slice(-200) }, "channel judge: no verdict");
419
- resolve(text);
420
- };
421
- const timer = setTimeout(() => {
422
- proc.kill("SIGKILL");
423
- finish(undefined, `timeout ${timeoutMs}ms`);
424
- }, timeoutMs);
425
- proc.stdout?.on("data", (c) => { out = (out + c.toString("utf8")).slice(-8000); });
426
- proc.stderr?.on("data", (c) => { errTail = (errTail + c.toString("utf8")).slice(-800); });
427
- proc.on("error", (e) => finish(undefined, `spawn ${e.message}`));
428
- proc.on("close", (code) => {
429
- if (code !== 0)
430
- return finish(undefined, `exit ${code}`);
431
- finish(out.trim() || undefined, "empty output");
432
- });
433
- });
434
- };
435
- const askJudge = async (deps, prompt) => {
436
- const text = await runJudgeOnce(deps, prompt);
437
- if (!text)
438
- return undefined;
439
- const verdict = parseVerdict(text);
440
- if (!verdict)
441
- deps.log.warn({ chars: text.length, head: text.slice(0, 200) }, "channel judge: unparsable output");
442
- return verdict;
443
- };
444
- const botName = (cfg) => cfg.wrc.botNames.find(Boolean) ?? "wezard";
445
- /** 每条历史都带 id + 时刻: 判官只做判定不改身份, 但它引用的那一句必须能被
446
- * 目标 agent 直接指回去, 所以 id 不能被压缩成 "第 N 条"。 */
447
- const judgeLine = (m, mark = " ") => `${mark}${m.kind === "reply" ? "reply" : "post"}=${m.id} [${stamp(m.at)}] ${m.author}: ${clip(m.text, 300)}`;
448
- export const buildJudgePrompt = (cfg, i) => {
449
- const base = `chat:${i.topicId}`;
450
- const me = botName(cfg);
451
- // 职责取频道管家身份的描述 (绑定 > 频道默认会话; §6 频道也是「组团里的一个群」),
452
- // 没绑也没会话的新频道回落全局管家, 再没有就退通用文案。
453
- const store = wizardStore();
454
- const stewardId = stewardIdentityOf(cfg, store, base);
455
- const stewardRecs = stewardId ? (store?.all() ?? []).filter((w) => identityOf(w) === stewardId) : [];
456
- // 新频道 (无绑定无默认会话): 接待它的是全局管家 (§6), 职责行回落到它的描述。
457
- const globalRec = stewardId ? undefined : (store?.all() ?? [])
458
- .filter((w) => w.kind === "global-steward" && sameBot(base, w.target))
459
- .sort((a, b) => Number(a.target !== identityOf(a)) - Number(b.target !== identityOf(b)) || a.bornAt - b.bornAt)[0];
460
- const job = stewardRecs.find((w) => w.target === stewardId)?.description
461
- ?? stewardRecs[0]?.description
462
- ?? store?.get(base)?.description
463
- ?? globalRec?.description
464
- ?? "这个频道的助手";
465
- const others = (store?.all() ?? [])
466
- .filter((w) => baseOfKey(w.target) === base && w.target !== base && w.target !== keyOf(base, "judge"))
467
- .map((w) => `${w.name || w.target}${w.description ? `(${w.description})` : ""}`)
468
- .slice(0, 12);
469
- const isReply = i.triggerId && i.triggerId !== i.postId;
470
- return [
471
- `你是 ${me} 的频道判官。判断最新一条消息是否应该由 ${me} 回应;该回应时,把它整理成一条给主 agent 的指令。`,
472
- `定位:topic=${i.topicId} · thread post=${i.postId}${isReply ? ` · 本次消息 reply=${i.triggerId}` : ""} · msgid=${i.msgid}`,
473
- `你的职责:${job}`,
474
- others.length ? `频道里其他机器人:${others.join("、")}` : "",
475
- i.bots?.length ? `频道里最近活跃的其他机器人:${i.bots.map((b) => `${b.id}(${b.n} 条)`).join("、")} —— 跨 bot 身份只认 bot:<id>,它们帖子里的 🧙‍♂️ name: 是自称名` : "",
476
- i.thread.length ? "这条消息所在的线程(父帖 + 评论,都带 id):" : "",
477
- ...i.thread.map((m) => judgeLine(m, " ")),
478
- i.recent.length ? "最近的频道消息(旧→新):" : "",
479
- ...i.recent.map((m, k) => judgeLine(m, `[${k + 1}] `)),
480
- `最新消息(${i.latestAuthor}):${clip(i.latest, 600)}`,
481
- "",
482
- ...(i.strict ? [
483
- "本频道是严格模式 (strict): 无人点名的每条人话默认开一条义务 —— respond 就等于「开义务」, respond=false 则这条不开 (闲聊 / 别人的事)。",
484
- ...(i.members?.length ? ["频道成员 (义务只能落给成员): " + i.members.join("、") + "。"] : []),
485
- "落给谁: 最新消息明显是找某个成员的, 就在 rewrite 的**句首**写它的点名 (.名字 空格开头, 名字用上面名单里的); 归属拿不准或找的是频道整体 → 不点名, 交给主 agent (默认接待)。",
486
- ""
487
- ] : []),
488
- "规则:",
489
- "- 最新消息 @ 了别的机器人、明显属于别人的职责、或只是闲聊 → respond=false",
490
- "- 最新消息在向本频道求助、需要你回答 → respond=true",
491
- "- 拿不准也 respond=false;不要重复别人已经回答的内容",
492
- "- respond=false 时不要写 intent / rewrite,留空字符串",
493
- "",
494
- "respond=true 时还要给出两步(只整理,不回答):",
495
- "1. intent:一句话说清这条消息想要什么(问什么 / 要你做什么 / 报了什么故障)。",
496
- "2. rewrite:把这条消息改写成一条主 agent 能直接执行的自洽指令 ——",
497
- " 补全省略的主语和指代对象(必要时代上线程里被回复的那一句),把零散的一句压成一条完整指令;",
498
- " 原文里的路径、命令、报错、数字、ID、链接一律原样保留,不添加原文没有的事实,不替用户补需求,不写答复内容;",
499
- " 用与原文相同的语言,只写改写后的正文,不要加「改写:」之类的前缀。",
500
- "",
501
- "这是一次性请求:不要调用工具,不要回答用户,不要解释。只输出下面这一行 JSON(不要代码围栏):",
502
- '{"respond":true|false,"reason":"一句话判断依据","intent":"一句话意图(respond=false 时留空)","rewrite":"改写后给主 agent 的指令正文(respond=false 时留空)"}',
503
- ].filter(Boolean).join("\n");
329
+ : (await fetchRecent(d.client, topicId, Math.min(limit, 20), d.log)).map((p) => postMsg(p)).filter((m) => !!m);
330
+ return { ok: true, text: list.length ? "频道 " + topicId + " · " + list.length + " 条\n" + renderLines(list) : "频道 " + topicId + " 没有读到消息 (没见过这个频道, 或还没缓存)" };
504
331
  };
505
332
  // 出站传输补丁必须早于 installResponseTracker 安装:tracker 会把当时的
506
333
  // client.sendMessage / replyStream 抓成 orig*,晚装就绕过了频道分支。
507
334
  /** base principal 是否是一个已登记的频道 (chat:<topic_id>)。 */
508
335
  export const isTopicChat = (base) => base.startsWith("chat:") && topics.has(base.slice("chat:".length));
509
- /** 工具面 (P7-S3: chat_say / chat_reply 的频道分支): 按 replyOk 选评论/新帖。
510
- * msgid (频道消息信封上的 msg) 能定位到具体帖子时用它, 否则用该频道最近一条帖子;
511
- * 帖子没被 @ 过 (replyOk=false) 只能主动发新帖 (官方语义)。 */
512
- export const sendTopicContent = async (client, log, topicId, content, msgid) => {
513
- const ctx = msgid ? byStream.get(msgid) : undefined;
514
- const postId = ctx?.postId ?? lastPost.get(topicId);
515
- const asReply = !!postId && replyOk.get(postId) === true;
516
- const body = await call(client, asReply ? CMD_REPLY : CMD_POST, asReply ? { topic_id: topicId, post_id: postId, content } : { topic_id: topicId, content });
336
+ /** 频道 room 的出站: 一律发新帖 (send_post)。 */
337
+ /** 频道 room 的出站选择 (§2.3): 交代 / 回话挂在那条评论行上 (原话行带 post) → 评论回那个帖子;
338
+ * 其余 (chat_say 主动说 / re 的不是评论) → 发新帖。选择编码在动作里, 不给工具加参数。
339
+ * postOf = 按消息 id 查那条原话行的频道 post_id (频道 room 的人话行带, 帖子 room 的行不带)。 */
340
+ export const channelOutboundOf = (row, postOf) => {
341
+ if (row.kind === "reply")
342
+ for (const id of row.re ?? []) {
343
+ const post = postOf(id);
344
+ if (post)
345
+ return { action: "reply", post };
346
+ }
347
+ return { action: "post" };
348
+ };
349
+ const topicBody = (content, media) => {
350
+ const files = media?.files ?? [];
351
+ const inline = files.map((f, i) => ({ placeholder: "p" + (i + 1), media_id: f.mediaId }));
352
+ const withInline = files.length
353
+ ? content + "\n" + files.map((_, i) => "${inline_file:p" + (i + 1) + "}").join(" ")
354
+ : content;
355
+ const images = (media?.imageIds ?? []).map((id) => ({ media_id: id }));
356
+ return { content: withInline, ...(images.length ? { image_list: images } : {}), ...(inline.length ? { inline_file_list: inline } : {}) };
357
+ };
358
+ export const sendTopicPost = async (client, log, topicId, content, media) => {
359
+ const body = await call(client, CMD_POST, { topic_id: topicId, ...topicBody(content, media) });
517
360
  if (body?.errcode)
518
- log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId, postId }, "channel tool send rejected");
361
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId }, "channel tool post rejected");
519
362
  else
520
- log.info({ topicId, via: asReply ? "reply" : "post", len: content.length }, "channel tool sent");
521
- return asReply ? "reply" : "post";
363
+ log.info({ topicId, via: "post", len: content.length }, "channel tool sent");
364
+ return "post";
365
+ };
366
+ /** 帖子 room 的出站: 一律评论到根帖 (send_reply)。企微拒 (errcode) 时回 "rejected" —— 调用方决定回退。 */
367
+ export const sendTopicReply = async (client, log, topicId, postId, content, media) => {
368
+ const body = await call(client, CMD_REPLY, { topic_id: topicId, post_id: postId, ...topicBody(content, media) });
369
+ if (body?.errcode) {
370
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId, postId }, "channel tool reply rejected");
371
+ return "rejected";
372
+ }
373
+ log.info({ topicId, postId, via: "reply", len: content.length }, "channel tool sent");
374
+ return "reply";
375
+ };
376
+ /** 评论回帖, 被企微拒时回退发新帖 (2026-11-23 人报纠正: 没 @ 过机器人的帖子实测也能评论, 早先
377
+ * 「只能评论 @ 过它的帖子」的说法不成立; 回退仅作真被拒的兜底, 不按 @ 与否预判。原先只 warn → 交代
378
+ * 静默丢失)。fallback 是新帖正文 (通常带引用标注); 没给就用原正文。 */
379
+ export const sendTopicReplyOrPost = async (client, log, topicId, postId, content, fallback, media) => {
380
+ const r = await sendTopicReply(client, log, topicId, postId, content, media);
381
+ if (r === "reply")
382
+ return "reply";
383
+ log.warn({ topicId, postId }, "channel reply rejected → fallback to post");
384
+ await sendTopicPost(client, log, topicId, fallback ?? content, media);
385
+ return "post";
522
386
  };
523
- export const installChannelTransport = (client, log, cfg) => {
387
+ export const installChannelTransport = (client, log) => {
524
388
  log.info("channel transport installed");
525
- const sendPost = (topicId, content) => call(client, CMD_POST, { topic_id: topicId, content })
526
- .then((body) => {
527
- if (body?.errcode)
528
- log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId }, "channel post rejected");
529
- else
530
- log.info({ topicId, len: content.length }, "channel post sent");
531
- const id = String(body?.post_id ?? "");
532
- if (id)
533
- lastPost.set(topicId, id);
534
- return body;
535
- })
536
- .catch((e) => { log.warn({ err: e.message, topicId }, "channel post failed"); return undefined; });
537
- const sendReply = (ctx, content) => call(client, CMD_REPLY, { topic_id: ctx.topicId, post_id: ctx.postId, content })
538
- .then((body) => {
539
- if (body?.errcode)
540
- log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId: ctx.topicId }, "channel reply rejected");
541
- else
542
- log.info({ topicId: ctx.topicId, postId: ctx.postId, len: content.length }, "channel reply sent");
543
- return body;
544
- })
545
- .catch((e) => { log.warn({ err: e.message, topicId: ctx.topicId }, "channel reply failed"); return undefined; });
546
- // ── 出站:topic 不走群 chatid,改成频道帖子 / 评论 ──
389
+ // ── 出站:topic 不走群 chatid,改成频道新帖 ──
547
390
  const origSend = client.sendMessage.bind(client);
548
391
  client.sendMessage = (chatid, body) => {
549
- // mirror 有时把 “chat:<topic>” 原样递进来;topic 集合里存的是裸 topic_id。
392
+ // mirror 有时把 "chat:<topic>" 原样递进来;topic 集合里存的是裸 topic_id。
550
393
  const bare = String(chatid).replace(/^(user|chat|group):/, "");
551
394
  const topicId = topics.has(chatid) ? chatid : topics.has(bare) ? bare : "";
552
395
  if (!topicId)
@@ -559,31 +402,15 @@ export const installChannelTransport = (client, log, cfg) => {
559
402
  return origSend(asker, body);
560
403
  }
561
404
  log.warn({ topicId }, "channel: template_card dropped (no asker)");
562
- return Promise.resolve(emptyFrame());
405
+ return Promise.resolve({ headers: { req_id: "" } });
563
406
  }
564
407
  const content = body?.msgtype === "markdown" ? String(body.markdown?.content ?? "") : "";
565
408
  if (!content) {
566
409
  log.warn({ topicId, msgtype: body?.msgtype }, "channel: unsupported outbound");
567
- return Promise.resolve(emptyFrame());
410
+ return Promise.resolve({ headers: { req_id: "" } });
568
411
  }
569
- // room 口径 (fix-task §8.2): strict 频道分支已删, 自动出站统一走 replyOk 选择
570
- // (被 @ 过的帖子评论, 否则新帖; 评论的主动权留给工具面)。
571
- const postId = lastPost.get(topicId);
572
- // 只有被 @ 过的帖子才能评论;未被 @ 的新帖只能主动发一条新帖。
573
- return postId && replyOk.get(postId) === true
574
- ? sendReply({ topicId, postId, asker: lastAsker.get(topicId) ?? "" }, content)
575
- : sendPost(topicId, content);
576
- };
577
- // replyStream 的气泡只对群聊有意义;频道里把最终帧落成一条评论,中间帧丢掉。
578
- const origStream = client.replyStream.bind(client);
579
- client.replyStream = (frame, streamId, content, finish = false, ...rest) => {
580
- // 事件流里的 streamId 可能是 route eventId,而 fake frame 的 req_id 才是频道 msgid —— 两边都认。
581
- const ctx = byStream.get(streamId) ?? byStream.get(String(frame?.headers?.req_id ?? ""));
582
- if (!ctx)
583
- return origStream(frame, streamId, content, finish, ...rest);
584
- if (!finish)
585
- return Promise.resolve(emptyFrame());
586
- return replyOk.get(ctx.postId) === true ? sendReply(ctx, content) : sendPost(ctx.topicId, content);
412
+ // 频道 room 只发新帖; 帖子 room 不走这里 (chat:<opk…> 不在 topics, 由 index 的 roomMirror 走 send_reply)。
413
+ return sendTopicPost(client, log, topicId, content).then(() => ({ headers: { req_id: "" } }));
587
414
  };
588
415
  };
589
416
  export const installChannelEvents = (client, cfg, log, facts) => {
@@ -592,97 +419,14 @@ export const installChannelEvents = (client, cfg, log, facts) => {
592
419
  log.warn("channel: wsManager.handleFrame unavailable; topic events will be ignored");
593
420
  return;
594
421
  }
595
- const dispatch = (topicId, postId, msgid, fromUser, text, at, allowReply) => {
596
- if (dispatched.has(postId))
422
+ /** 落一行人话; 没有 ingest (旧接线 / 测试桩) 就只记日志 —— 静默丢话是不允许的。 */
423
+ const ingest = (e) => {
424
+ if (!facts?.ingest) {
425
+ log.warn({ room: e.room, post: e.post, msgid: e.msgid }, "channel: no room ingest wired, message not delivered");
597
426
  return;
598
- dispatched.add(postId);
599
- if (dispatched.size > 3000)
600
- dispatched.delete(dispatched.values().next().value);
601
- replyOk.set(postId, allowReply);
602
- if (replyOk.size > 3000)
603
- replyOk.delete(replyOk.keys().next().value);
604
- lastPost.set(topicId, postId);
605
- byStream.set(msgid, { topicId, postId, asker: fromUser });
606
- if (byStream.size > 3000)
607
- byStream.delete(byStream.keys().next().value);
608
- const fake = {
609
- headers: { req_id: msgid },
610
- body: {
611
- msgid,
612
- chattype: "group",
613
- chatid: topicId,
614
- from: { userid: fromUser },
615
- create_time: at,
616
- msgtype: "text",
617
- text: { content: text },
618
- },
619
- };
620
- log.info({ topicId, postId, msgid, len: text.length }, "channel rx");
621
- client.emit("message.text", fake);
622
- };
623
- const mentions = (post) => {
624
- const list = post?.inline_mention_list ?? post?.mention_list ?? [];
625
- if (!Array.isArray(list))
626
- return [];
627
- return list.map((x) => {
628
- const m = x?.member ?? x ?? {};
629
- return { type: Number(m.type ?? 0), bot: typeof m.aibotid === "string" ? m.aibotid : undefined };
630
- });
631
- };
632
- const judgeAndMaybe = async (topicId, postId, msgid, fromUser, text, at, selfBot, triggerId) => {
633
- if (!cfg.wrc.channel.judge.enabled) {
634
- log.info({ topicId, postId }, "channel judge disabled");
635
- return;
636
- }
637
- if (dispatched.has(postId)) {
638
- log.info({ topicId, postId }, "channel judge skipped: already dispatched");
639
- return;
640
- }
641
- const post = await fetchPost(client, topicId, postId, log);
642
- const ms = mentions(post);
643
- // 不能因为“提到自己”就跳过:回复/引用机器人时 inline_mention 也可能带上自己,
644
- // 但这时不一定有 topic_at_bot。交给判官,dispatched 会保证不会双答。
645
- if (ms.some((m) => m.type === 1 && m.bot === selfBot)) {
646
- log.info({ topicId, postId }, "channel judge: self-mention, wait for topic_at_bot");
647
- // 先等一拍:真有 topic_at_bot 就让直接 @ 路径答(评论);没有才走判官。
648
- await sleep(1200);
649
- if (dispatched.has(postId)) {
650
- log.info({ topicId, postId }, "channel judge skipped: self-mention handled by topic_at_bot");
651
- return;
652
- }
653
427
  }
654
- if (ms.some((m) => m.type === 1 && m.bot && m.bot !== selfBot)) {
655
- log.info({ topicId, postId }, "channel judge skipped: addressed to another bot");
656
- return;
657
- }
658
- const recent = await recentPosts(client, cfg, log, topicId, cfg.wrc.channel.judge.maxPosts);
659
- const thread = withoutMsg((await ensureStore(cfg)?.thread(topicId, postId, 4)) ?? [], triggerId);
660
- const prompt = buildJudgePrompt(cfg, {
661
- topicId, postId, triggerId, msgid,
662
- recent: withoutMsg(recent, triggerId),
663
- thread,
664
- latest: text,
665
- latestAuthor: fromUser,
666
- bots: botAuthors([...recent, ...thread], selfBot),
667
- });
668
- // 一次 -p 进程也串行:同一 topic 两条消息同时到不该各起一个, 判词会互相盖。
669
- const verdict = await serial(`judge:${topicId}`, () => askJudge({ cfg, log }, prompt));
670
- if (!verdict?.respond) {
671
- // 超时 / 进程失败 / 输出解析不了都落在这里: 判官是个减噪层, 它的结论是「不回应」。
672
- // 回落 = 不投递 (频道里不会有人收到这条), 但要留得下可查的一行 —— 不静默丢。
673
- log.warn({ topicId, postId, msgid, triggerId, reason: verdict?.reason ?? "timeout/unparsable" }, "channel judge: no dispatch (verdict absent or respond=false)");
674
- return;
675
- }
676
- log.info({ topicId, postId, reason: verdict.reason, intent: verdict.intent, rewritten: !!verdict.rewrite }, "channel judge: yes");
677
- // 判官说 YES 才拼展开版上下文: 线程 + 最近 + (这句话有指代时) 搜索命中。
678
- // 入站帧的 msgid 随首行一起下去 —— 判官只加意图 / 改写,不替换身份。
679
- const ctx = await contextFor({ client, cfg, log }, topicId, postId, triggerId, text, {
680
- reason: verdict.reason,
681
- msgid,
682
- selfBot,
683
- ...(verdict.intent ? { intent: verdict.intent } : {}),
684
- });
685
- dispatch(topicId, postId, msgid, fromUser, `${ctx}\n——\n${bodyFor(text, verdict)}`, at, false);
428
+ log.info({ room: e.room, post: e.post, msgid: e.msgid, len: e.text.length, mention: e.mention }, "channel rx");
429
+ facts.ingest(e);
686
430
  };
687
431
  const onTopic = async (frame) => {
688
432
  const body = frame?.body ?? {};
@@ -690,7 +434,6 @@ export const installChannelEvents = (client, cfg, log, facts) => {
690
434
  const topicId = String(body.topic_id ?? "");
691
435
  const from = body.from ?? {};
692
436
  const asker = String(from.userid ?? "");
693
- const selfBot = String(body.aibotid ?? "");
694
437
  const at = Number(body.create_time ?? 0) * 1000 || Date.now();
695
438
  const recvAt = Date.now();
696
439
  if (!topicId)
@@ -698,9 +441,11 @@ export const installChannelEvents = (client, cfg, log, facts) => {
698
441
  registerTopic(topicId);
699
442
  if (asker)
700
443
  lastAsker.set(topicId, asker);
444
+ facts?.channelSeen?.(topicId);
701
445
  // 第一次见到的频道从官方补最近 N 条 (reload / 断线空窗期的事件本地没有)。
702
446
  void backfill(client, cfg, log, topicId).catch((e) => log.warn({ err: e.message, topicId }, "channel backfill failed"));
703
447
  log.info({ topicId, type: ev.eventtype, postId: ev.topic_event?.post_id ?? ev.topic_reply_event?.post_id ?? ev.topic_at_bot?.post_id, asker }, "channel event");
448
+ const channelRoom = "chat:" + topicId;
704
449
  if (ev.eventtype === "topic_at_bot") {
705
450
  const postId = String(ev.topic_at_bot?.post_id ?? "");
706
451
  const replyId = String(ev.topic_at_bot?.reply_id ?? "");
@@ -714,31 +459,34 @@ export const installChannelEvents = (client, cfg, log, facts) => {
714
459
  seen.delete(seen.values().next().value);
715
460
  const native = await awaitNative(asker, recvAt - NATIVE_SKEW_MS, facts?.nativeWaitMs ?? NATIVE_WAIT_MS);
716
461
  if (native) {
717
- // 原生帧已把这句话投给帖子会话; 桥只记账: 标 dispatched (判官别再接), 帖子照存本地缓存。
718
- // 配上的这一对就是「帖子 → 频道」的唯一判据 (原生帧里没有频道标识), 落盘给管家绑定按频道判。
719
- if (learnChannelPost(cfg, native, topicId))
462
+ // 原生帧已把这句话投给帖子会话 (= 帖子 room 的那条人话); 桥只记账。
463
+ // 配上的这一对就是「帖子 → 频道」的唯一判据 (原生帧里没有频道标识)。
464
+ if (learnChannelPost(cfg, native, topicId, postId)) {
720
465
  log.info({ topicId, post: native }, "channel post learned");
721
- dispatched.add(postId);
722
- if (dispatched.size > 3000)
723
- dispatched.delete(dispatched.values().next().value);
466
+ facts?.postTouched?.(topicId, native);
467
+ }
724
468
  log.info({ topicId, postId, msgid, nativeChat: native }, "channel at_bot: carried by native frame, bridge skip");
725
469
  await record(cfg, topicId, postMsg(await fetchPost(client, topicId, postId, log)));
726
470
  if (replyId)
727
471
  await record(cfg, topicId, replyMsg(await fetchReply(client, topicId, postId, replyId, log), postId));
728
472
  return;
729
473
  }
730
- if (dispatched.has(postId))
731
- return;
732
474
  const post = await fetchPost(client, topicId, postId, log);
733
475
  const reply = replyId ? await fetchReply(client, topicId, postId, replyId, log) : null;
734
476
  if (!post)
735
477
  log.warn({ topicId, postId }, "channel: post content not found");
736
- await record(cfg, topicId, postMsg(post));
478
+ const hit = reply ?? post;
479
+ const media = await downloadMedia(cfg, log, hit, msgid);
480
+ await record(cfg, topicId, postMsg(post, reply ? NO_MEDIA : media));
737
481
  if (reply)
738
- await record(cfg, topicId, replyMsg(reply, postId));
739
- const text = cleanContent(reply?.content ?? post?.content) || "(在频道里 @ 了你,没有正文)";
740
- const ctx = await contextFor({ client, cfg, log }, topicId, postId, replyId || postId, text, { msgid, selfBot });
741
- dispatch(topicId, postId, msgid, asker, `${ctx}\n——\n${text}`, at, true);
482
+ await record(cfg, topicId, replyMsg(reply, postId, media));
483
+ const text = cleanContent(hit?.content) || "(在频道里 @ 了你,没有正文)";
484
+ // 兜底: 帖子已配对 → 帖子 room (它就是那个帖子); 没配对 → 频道 room。这一路是 topic_at_bot
485
+ // (人 @ 了机器人), 落到哪个 room 都一样记 mention:"bot" —— 直达 host, 不交给 room 的 monitor。
486
+ const paired = postBaseOf(cfg, topicId, postId);
487
+ ingest(paired
488
+ ? { room: paired, author: asker, text, at, msgid, mention: "bot", ...mediaOf(media) }
489
+ : { room: channelRoom, post: postId, author: asker, text, at, msgid, mention: "bot", ...mediaOf(media) });
742
490
  return;
743
491
  }
744
492
  if (ev.eventtype === "topic_event" && Number(ev.topic_event?.type ?? 0) === 1) {
@@ -746,8 +494,8 @@ export const installChannelEvents = (client, cfg, log, facts) => {
746
494
  const msgid = String(body.msgid ?? postId);
747
495
  if (!postId || !msgid)
748
496
  return;
749
- if (seen.has(msgid) || dispatched.has(postId)) {
750
- log.info({ topicId, postId, msgid }, "channel topic_event skipped: seen/dispatched");
497
+ if (seen.has(msgid)) {
498
+ log.info({ topicId, postId, msgid }, "channel topic_event skipped: seen");
751
499
  return;
752
500
  }
753
501
  if (!asker) {
@@ -758,12 +506,13 @@ export const installChannelEvents = (client, cfg, log, facts) => {
758
506
  if (seen.size > 3000)
759
507
  seen.delete(seen.values().next().value);
760
508
  const post = await fetchPost(client, topicId, postId, log);
761
- await record(cfg, topicId, postMsg(post));
509
+ const media = await downloadMedia(cfg, log, post, msgid);
510
+ await record(cfg, topicId, postMsg(post, media));
762
511
  const text = cleanContent(post?.content);
763
- if (!text)
512
+ if (!text && !media.images.length && !media.files.length)
764
513
  return;
765
- void judgeAndMaybe(topicId, postId, msgid, asker, text, at, selfBot, postId)
766
- .catch((e) => log.warn({ err: e.message, topicId, postId }, "channel judge failed"));
514
+ // 没被 @ 的新帖: 频道 room 的一行人话 (带 post); 不 @ 机器人就不过 host, 由 monitor 判激活。
515
+ ingest({ room: channelRoom, post: postId, author: asker, text, at, msgid, ...mediaOf(media) });
767
516
  return;
768
517
  }
769
518
  if (ev.eventtype === "topic_reply_event" && Number(ev.topic_reply_event?.type ?? 0) === 1) {
@@ -772,7 +521,7 @@ export const installChannelEvents = (client, cfg, log, facts) => {
772
521
  const msgid = String(body.msgid ?? replyId);
773
522
  if (!postId || !replyId || !msgid)
774
523
  return;
775
- if (seen.has(replyId) || dispatched.has(replyId) || !asker) {
524
+ if (seen.has(replyId) || !asker) {
776
525
  log.info({ topicId, postId, replyId, msgid, asker }, "channel topic_reply_event skipped");
777
526
  return;
778
527
  }
@@ -780,12 +529,16 @@ export const installChannelEvents = (client, cfg, log, facts) => {
780
529
  if (seen.size > 3000)
781
530
  seen.delete(seen.values().next().value);
782
531
  const reply = await fetchReply(client, topicId, postId, replyId, log);
783
- await record(cfg, topicId, replyMsg(reply, postId));
532
+ const media = await downloadMedia(cfg, log, reply, msgid);
533
+ await record(cfg, topicId, replyMsg(reply, postId, media));
784
534
  const text = cleanContent(reply?.content);
785
- if (!text)
535
+ if (!text && !media.images.length && !media.files.length)
786
536
  return;
787
- void judgeAndMaybe(topicId, postId, msgid, asker, text, at, selfBot, replyId)
788
- .catch((e) => log.warn({ err: e.message, topicId, postId }, "channel judge failed"));
537
+ // 评论: 帖子已配对 → 帖子 room; 还没配对 → 频道 room (带 post)。
538
+ const paired = postBaseOf(cfg, topicId, postId);
539
+ ingest(paired
540
+ ? { room: paired, author: asker, text, at, msgid, ...mediaOf(media) }
541
+ : { room: channelRoom, post: postId, author: asker, text, at, msgid, ...mediaOf(media) });
789
542
  return;
790
543
  }
791
544
  log.debug({ type: ev.eventtype, topicId }, "channel event ignored");
@@ -801,5 +554,4 @@ export const installChannelEvents = (client, cfg, log, facts) => {
801
554
  prev(frame);
802
555
  };
803
556
  };
804
- // 兼容入口:新代码应分别早装 transport、晚装 events。
805
557
  //# sourceMappingURL=channel.js.map