wezard 2.8.8 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.claude-plugin/plugin.json +0 -6
  2. package/CLAUDE.md +3 -2
  3. package/README.md +5 -5
  4. package/config.example.jsonc +4 -0
  5. package/dist/cli/codex-hook.js +20 -4
  6. package/dist/cli/codex-hook.js.map +1 -1
  7. package/dist/cli/init.js +10 -8
  8. package/dist/cli/init.js.map +1 -1
  9. package/dist/cli/sync.js +32 -112
  10. package/dist/cli/sync.js.map +1 -1
  11. package/dist/daemon/approval.js +53 -14
  12. package/dist/daemon/approval.js.map +1 -1
  13. package/dist/daemon/channel-context.js +62 -0
  14. package/dist/daemon/channel-context.js.map +1 -0
  15. package/dist/daemon/channel-store.js +96 -0
  16. package/dist/daemon/channel-store.js.map +1 -0
  17. package/dist/daemon/channel.js +693 -0
  18. package/dist/daemon/channel.js.map +1 -0
  19. package/dist/daemon/config-api.js +10 -2
  20. package/dist/daemon/config-api.js.map +1 -1
  21. package/dist/daemon/danger.js +24 -205
  22. package/dist/daemon/danger.js.map +1 -1
  23. package/dist/daemon/handoff.js +243 -28
  24. package/dist/daemon/handoff.js.map +1 -1
  25. package/dist/daemon/idle-nudge.js +29 -8
  26. package/dist/daemon/idle-nudge.js.map +1 -1
  27. package/dist/daemon/inbound.js +6 -1
  28. package/dist/daemon/inbound.js.map +1 -1
  29. package/dist/daemon/index.js +135 -15
  30. package/dist/daemon/index.js.map +1 -1
  31. package/dist/daemon/message-events.js +82 -10
  32. package/dist/daemon/message-events.js.map +1 -1
  33. package/dist/daemon/mirror-bridge.js +203 -18
  34. package/dist/daemon/mirror-bridge.js.map +1 -1
  35. package/dist/daemon/pending.js +7 -5
  36. package/dist/daemon/pending.js.map +1 -1
  37. package/dist/daemon/picker-policy.js +27 -12
  38. package/dist/daemon/picker-policy.js.map +1 -1
  39. package/dist/daemon/spawn-tmux.js +124 -20
  40. package/dist/daemon/spawn-tmux.js.map +1 -1
  41. package/dist/daemon/wezard-session.js +1 -0
  42. package/dist/daemon/wezard-session.js.map +1 -1
  43. package/dist/daemon/wizard.js +1 -1
  44. package/dist/daemon/wizard.js.map +1 -1
  45. package/dist/mcp/tools.js +18 -1
  46. package/dist/mcp/tools.js.map +1 -1
  47. package/dist/shared/allow-rules.js +32 -2
  48. package/dist/shared/allow-rules.js.map +1 -1
  49. package/dist/shared/cli-backends.js +14 -0
  50. package/dist/shared/cli-backends.js.map +1 -1
  51. package/dist/shared/config.js +74 -14
  52. package/dist/shared/config.js.map +1 -1
  53. package/dist/shared/detail-render.js +6 -0
  54. package/dist/shared/detail-render.js.map +1 -1
  55. package/dist/shared/detail-store.js.map +1 -1
  56. package/dist/shared/json-map-store.js +23 -6
  57. package/dist/shared/json-map-store.js.map +1 -1
  58. package/dist/shared/repl-script.js +114 -26
  59. package/dist/shared/repl-script.js.map +1 -1
  60. package/dist/shared/session-hooks.js +46 -0
  61. package/dist/shared/session-hooks.js.map +1 -0
  62. package/dist/shared/session-mcp.js +59 -0
  63. package/dist/shared/session-mcp.js.map +1 -0
  64. package/dist/shared/session-skills.js +55 -0
  65. package/dist/shared/session-skills.js.map +1 -0
  66. package/dist/shared/tool-hints.js +61 -11
  67. package/dist/shared/tool-hints.js.map +1 -1
  68. package/hooks/pre-tool-use.sh +18 -0
  69. package/package.json +1 -2
  70. package/hooks/hooks.json +0 -16
@@ -0,0 +1,693 @@
1
+ // 频道(topic)桥: SDK 1.0.7 的 dispatch 表里没有 aibot_topic_event_callback,
2
+ // 这一层在 SDK 丢掉帧之前接住它,把「频道里 @ 了机器人」翻译成一条普通的文本消息
3
+ // 交给 inbound / mirror;出站再把 topic_id 的 markdown 换成频道的 send_post /
4
+ // send_reply。群聊 / 单聊的路径完全不变。
5
+ //
6
+ // 频道里没有被 @ 的新帖子 / 新回复也会进来(topic_event / topic_reply_event)。
7
+ // 这些不直接答,先交给每个 bot 的「判官」:判官是一个只读最近几条消息的轻量 wizard,
8
+ // 只回 JSON {respond, reason};respond 才把原帖交给主 wizard。
9
+ import { spawn } from "node:child_process";
10
+ import { join } from "node:path";
11
+ import { generateReqId } from "@wecom/aibot-node-sdk";
12
+ import { pickTier } from "../shared/model-tiers.js";
13
+ import { resolveCliBackend } from "../shared/cli-backends.js";
14
+ import { augmentedPath } from "../shared/exec-path.js";
15
+ import { baseOfKey, keyOf } from "../shared/session-label.js";
16
+ import { sleep } from "../shared/std.js";
17
+ import { wizardStore } from "./wizard.js";
18
+ import { expandHome } from "../shared/paths.js";
19
+ import { ChannelStore } from "./channel-store.js";
20
+ import { formatChannelContext, pickQuery, wantsHistory, withoutMsg } from "./channel-context.js";
21
+ const TOPIC_EVENT = "aibot_topic_event_callback";
22
+ const CMD_POST = "aibot_topic_send_post";
23
+ const CMD_REPLY = "aibot_topic_send_reply";
24
+ const CMD_GET_POSTS = "aibot_topic_get_post_list";
25
+ const CMD_GET_REPLIES = "aibot_topic_get_reply_list";
26
+ const CMD_SEARCH = "aibot_topic_search";
27
+ const CMD_SEARCH_RESULT = "get_search_result";
28
+ /** 已知 topic_id。sendMessage 用它区分「频道」和普通群 chatid。 */
29
+ const topics = new Set();
30
+ /** 入站事件 msgid → 它所属的帖子;replyStream 用 streamId 找回来。 */
31
+ const byStream = new Map();
32
+ /** topic 上最近一条帖子,主动消息尽量挂成它的评论。 */
33
+ const lastPost = new Map();
34
+ /** 频道里最近一个说话的人;审批卡改投他的私聊,频道不支持按钮卡片。 */
35
+ const lastAsker = new Map();
36
+ /** 事件可能重投;msgid 去重表有界。 */
37
+ const seen = new Set();
38
+ /** 已经交给主 wizard 的 post / reply;判官与直接 @ 可能同时到,谁先到谁答。 */
39
+ const dispatched = new Set();
40
+ /** post_id → 是否收到过 topic_at_bot。只有被 @ 过的帖子才能用 send_reply 评论;
41
+ * 未被 @ 的新帖只能 send_post 主动发(官方“回复被@的内容” vs “主动发内容”)。 */
42
+ const replyOk = new Map();
43
+ /** 判官串行:同一 topic 一次只跑一个判断,一次 -p 进程更不该并发抢占。 */
44
+ const judgeQueues = new Map();
45
+ const MENTION_RE = /\$\{inline_mention(?::[^}]*)?\}/g;
46
+ const FILE_RE = /\$\{inline_file(?::[^}]*)?\}/g;
47
+ const cleanContent = (s) => String(s ?? "").replace(MENTION_RE, "").replace(FILE_RE, "").trim();
48
+ const clip = (s, n = 300) => (s.length > n ? s.slice(0, n) + "…" : s);
49
+ const replyBody = (frame) => frame?.body ?? frame;
50
+ const call = async (client, cmd, body) => {
51
+ // reply() 只是「带 cmd 的 WS 请求」;req_id 自造,服务端回执按它匹配。
52
+ const frame = await client.reply({ headers: { req_id: generateReqId("topic") } }, body, cmd);
53
+ return replyBody(frame);
54
+ };
55
+ const fetchPost = async (client, topicId, postId, log) => {
56
+ const body = await call(client, CMD_GET_POSTS, { topic_id: topicId, type: 0, post_id_list: [postId] });
57
+ if (body?.errcode)
58
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId, postId }, "channel get_post failed");
59
+ const list = body?.post_list ?? body?.posts ?? [];
60
+ return list[0] ?? body?.post ?? null;
61
+ };
62
+ const fetchReply = async (client, topicId, postId, replyId, log) => {
63
+ const body = await call(client, CMD_GET_REPLIES, { topic_id: topicId, post_id: postId, type: 0, reply_id_list: [replyId] });
64
+ if (body?.errcode)
65
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId, postId, replyId }, "channel get_reply failed");
66
+ const list = body?.reply_list ?? body?.replies ?? [];
67
+ return list[0] ?? null;
68
+ };
69
+ const fetchRecent = async (client, topicId, limit, log) => {
70
+ const body = await call(client, CMD_GET_POSTS, { topic_id: topicId, type: 1, sort_type: 1, limit });
71
+ if (body?.errcode)
72
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId }, "channel get_recent failed");
73
+ const list = body?.post_list ?? [];
74
+ return Array.isArray(list) ? list.slice().reverse() : [];
75
+ };
76
+ /** 本地缓存 (每个 topic 一个 jsonl), 懒初始化: 配置里的 stateDir / 保留策略变了就换一份。 */
77
+ let store;
78
+ let storeKey = "";
79
+ /** 已经回填过的 topic —— 进程重启后重新算一次 (断线空窗期的事件本地没有)。 */
80
+ const backfilled = new Set();
81
+ const ensureStore = (cfg) => {
82
+ const h = cfg.wrc.channel.history;
83
+ if (!h.enabled)
84
+ return undefined;
85
+ const key = `${cfg.daemon.stateDir}|${h.keepDays}|${h.maxMessages}`;
86
+ if (!store || storeKey !== key) {
87
+ store = new ChannelStore({
88
+ dir: join(expandHome(cfg.daemon.stateDir), "channels"),
89
+ keepDays: h.keepDays,
90
+ maxMessages: h.maxMessages,
91
+ });
92
+ storeKey = key;
93
+ backfilled.clear();
94
+ }
95
+ return store;
96
+ };
97
+ /** 频道回包的时间戳单位不统一 (秒 / 毫秒都见过)。 */
98
+ const atOf = (t) => {
99
+ const n = Number(t ?? 0);
100
+ if (!Number.isFinite(n) || n <= 0)
101
+ return Date.now();
102
+ return n > 1e12 ? n : n * 1000;
103
+ };
104
+ const authorOf = (creator) => {
105
+ const c = creator ?? {};
106
+ return Number(c.type) === 1 ? `bot:${String(c.aibotid ?? "?").slice(0, 10)}` : String(c.userid ?? "user");
107
+ };
108
+ const postMsg = (p) => {
109
+ const id = String(p?.post_id ?? "");
110
+ const text = cleanContent(p?.content);
111
+ if (!id || !text)
112
+ return undefined;
113
+ return { id, kind: "post", postId: id, at: atOf(p?.create_time), author: authorOf(p?.creator), text };
114
+ };
115
+ const replyMsg = (r, postId) => {
116
+ const id = String(r?.reply_id ?? "");
117
+ const text = cleanContent(r?.content);
118
+ if (!id || !text)
119
+ return undefined;
120
+ return { id, kind: "reply", postId: String(r?.post_id ?? postId), at: atOf(r?.create_time), author: authorOf(r?.creator), text };
121
+ };
122
+ /** 记一条进本地缓存: 判官上下文 / 主 wizard 上下文 / read_channel 共用这一份。 */
123
+ const record = async (cfg, topicId, msg) => {
124
+ if (!msg)
125
+ return;
126
+ await ensureStore(cfg)?.append(topicId, msg);
127
+ };
128
+ /** 第一次见到的 topic 从官方补最近 N 条 —— reload / 断线空窗期的消息本地没有。 */
129
+ const backfill = async (client, cfg, log, topicId) => {
130
+ const h = cfg.wrc.channel.history;
131
+ const s = ensureStore(cfg);
132
+ if (!s || !h.backfillOnBoot || backfilled.has(topicId))
133
+ return;
134
+ backfilled.add(topicId);
135
+ if ((await s.count(topicId)) >= h.mainPosts)
136
+ return;
137
+ const posts = await fetchRecent(client, topicId, h.mainPosts, log);
138
+ for (const m of posts.map(postMsg).filter((x) => !!x))
139
+ await s.append(topicId, m);
140
+ log.info({ topicId, n: posts.length }, "channel history backfilled");
141
+ };
142
+ /** 判官 / 上下文要看的最近帖子: 本地够用就不打接口。 */
143
+ const recentPosts = async (client, cfg, log, topicId, limit) => {
144
+ const local = (await ensureStore(cfg)?.recentPosts(topicId, limit)) ?? [];
145
+ if (local.length >= Math.min(limit, 3))
146
+ return local;
147
+ const posts = await fetchRecent(client, topicId, limit, log);
148
+ return posts.map(postMsg).filter((m) => !!m);
149
+ };
150
+ /** 官方搜索: 两步 (search 出 jobid → get_search_result 取摘要), 摘要只是 ID, 正文按 post 再取一次。 */
151
+ const searchRemote = async (d, topicId, query, limit) => {
152
+ const body = await call(d.client, CMD_SEARCH, { keyword_list: [query], topic_id_list: [topicId], limit });
153
+ if (body?.errcode) {
154
+ d.log.debug({ errcode: body.errcode, errmsg: body.errmsg, topicId }, "channel search rejected");
155
+ return [];
156
+ }
157
+ const jobid = String(body?.jobid ?? "");
158
+ if (!jobid)
159
+ return [];
160
+ const ids = [];
161
+ for (let i = 0; i < 5 && ids.length < limit; i += 1) {
162
+ const r = await call(d.client, CMD_SEARCH_RESULT, { jobid, topic_id: topicId, limit });
163
+ if (r?.errcode)
164
+ break;
165
+ for (const x of r?.result_list ?? []) {
166
+ const id = String(x?.post_id ?? "");
167
+ if (id && !ids.includes(id))
168
+ ids.push(id);
169
+ }
170
+ if (!r?.has_more)
171
+ break;
172
+ await sleep(300);
173
+ }
174
+ if (!ids.length)
175
+ return [];
176
+ const b = await call(d.client, CMD_GET_POSTS, { topic_id: topicId, type: 0, post_id_list: ids.slice(0, Math.max(1, limit)) });
177
+ const posts = b?.post_list ?? [];
178
+ return posts.map(postMsg).filter((m) => !!m);
179
+ };
180
+ /** 先本地 grep (便宜、立刻), 不够再走官方搜索 (语义索引只在服务端)。 */
181
+ const searchChannel = async (d, topicId, query, limit) => {
182
+ if (!limit || !query)
183
+ return [];
184
+ const local = (await ensureStore(d.cfg)?.search(topicId, query, limit)) ?? [];
185
+ if (local.length >= limit)
186
+ return local;
187
+ const seen = new Set(local.map((m) => m.id));
188
+ const remote = (await searchRemote(d, topicId, query, limit)).filter((m) => !seen.has(m.id));
189
+ return [...local, ...remote].slice(0, limit);
190
+ };
191
+ /** 主 wizard 的上下文: 当前线程 + 最近 + (这句话有指代时才) 搜索命中。
192
+ * 入站帧的身份 (topic / post / msgid) 永远写在首行 —— 即使 history 关掉、没有历史可带,
193
+ * 主 agent 也必须能指回原始消息。 */
194
+ const contextFor = async (d, topicId, postId, triggerId, text, extra = {}) => {
195
+ const h = d.cfg.wrc.channel.history;
196
+ // 触发这条上下文的回复 id 与线程根不同 (评论) 时一并带上: 目标 agent 要能指回
197
+ // 那一句评论, 而不只是它所属的帖子。
198
+ const replyId = triggerId && triggerId !== postId ? triggerId : "";
199
+ const id = { topicId, postId, ...(replyId ? { replyId } : {}), ...(extra.msgid ? { msgid: extra.msgid } : {}) };
200
+ const s = ensureStore(d.cfg);
201
+ if (!s)
202
+ return formatChannelContext({ ...id, budget: h.contextChars });
203
+ const thread = withoutMsg(await s.thread(topicId, postId, h.mainReplies), triggerId);
204
+ const recent = withoutMsg(await s.recentPosts(topicId, h.mainPosts), triggerId);
205
+ const query = h.searchLimit > 0 && wantsHistory(text) ? pickQuery(text) : "";
206
+ const hits = query ? (await searchChannel(d, topicId, query, h.searchLimit)).filter((m) => m.id !== triggerId) : [];
207
+ return formatChannelContext({
208
+ ...id,
209
+ thread,
210
+ recent,
211
+ hits,
212
+ ...(query ? { query } : {}),
213
+ ...(extra.reason ? { reason: extra.reason } : {}),
214
+ ...(extra.intent ? { intent: extra.intent } : {}),
215
+ budget: h.contextChars,
216
+ });
217
+ };
218
+ const stamp = (ms) => {
219
+ const d = new Date(ms);
220
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
221
+ };
222
+ const renderLines = (list) => list.map((m) => `[${stamp(m.at)}] ${m.author}: ${clip(m.text, 400)}`).join("\n");
223
+ /** read_channel 的守护进程侧: 本地缓存优先, 搜不到 / 没缓存才问官方。 */
224
+ export const readChannel = async (d, req) => {
225
+ const topicId = req.topic.replace(/^chat:/, "").trim();
226
+ if (!topicId)
227
+ return { ok: false, text: "给一个频道: `chat:<topic_id>` 或裸 topic_id" };
228
+ const limit = Math.min(Math.max(Number(req.limit ?? 20) || 20, 1), 100);
229
+ const query = (req.query ?? "").trim();
230
+ if (query) {
231
+ const hits = await searchChannel(d, topicId, query, limit);
232
+ return { ok: true, text: hits.length ? `频道 ${topicId} · 搜「${query}」· ${hits.length} 条\n${renderLines(hits)}` : `频道 ${topicId} 没搜到「${query}」` };
233
+ }
234
+ const local = (await ensureStore(d.cfg)?.slice(topicId, { ...(req.since !== undefined ? { since: req.since } : {}), ...(req.until !== undefined ? { until: req.until } : {}), limit })) ?? [];
235
+ const list = local.length
236
+ ? local
237
+ : (await fetchRecent(d.client, topicId, Math.min(limit, 20), d.log)).map(postMsg).filter((m) => !!m);
238
+ return { ok: true, text: list.length ? `频道 ${topicId} · ${list.length} 条\n${renderLines(list)}` : `频道 ${topicId} 没有读到消息 (没见过这个频道, 或还没缓存)` };
239
+ };
240
+ const emptyFrame = () => ({ headers: { req_id: "" } });
241
+ const serial = (key, job) => {
242
+ const prev = judgeQueues.get(key) ?? Promise.resolve();
243
+ const next = prev.then(job, job);
244
+ judgeQueues.set(key, next.catch(() => undefined).finally(() => {
245
+ if (judgeQueues.get(key) === next)
246
+ judgeQueues.delete(key);
247
+ }));
248
+ return next;
249
+ };
250
+ /** 逐个 `{` 数括号取 JSON 对象 (跳过字符串里的括号),比非贪婪正则可容下 rewrite 里的代码块。 */
251
+ const jsonObjects = (text) => {
252
+ const out = [];
253
+ for (let i = 0; i < text.length; i += 1) {
254
+ if (text[i] !== "{")
255
+ continue;
256
+ let depth = 0;
257
+ let inStr = false;
258
+ let esc = false;
259
+ for (let j = i; j < text.length; j += 1) {
260
+ const c = text[j];
261
+ if (inStr) {
262
+ if (esc)
263
+ esc = false;
264
+ else if (c === "\\")
265
+ esc = true;
266
+ else if (c === '"')
267
+ inStr = false;
268
+ }
269
+ else if (c === '"')
270
+ inStr = true;
271
+ else if (c === "{")
272
+ depth += 1;
273
+ else if (c === "}") {
274
+ depth -= 1;
275
+ if (depth === 0) {
276
+ out.push(text.slice(i, j + 1));
277
+ i = j;
278
+ break;
279
+ }
280
+ }
281
+ }
282
+ }
283
+ return out;
284
+ };
285
+ const asText = (v) => (typeof v === "string" ? v.trim() : "");
286
+ /** 字段容错: 只认字符串 (对象 / 数组当没写),并按第一个非空别名取值 —— 模型多吐、少吐都不炸。 */
287
+ const asField = (o, keys) => keys.map((k) => asText(o[k])).find(Boolean) ?? "";
288
+ /** respond 也容忍模型写成字符串 "true" / "false"。 */
289
+ const asReply = (v) => typeof v === "boolean" ? v : v === "true" ? true : v === "false" ? false : undefined;
290
+ export const parseVerdict = (text) => {
291
+ for (const b of jsonObjects(text).reverse()) {
292
+ try {
293
+ const o = JSON.parse(b);
294
+ const respond = asReply(o.respond);
295
+ if (respond === undefined)
296
+ continue;
297
+ const intent = asField(o, ["intent", "意图"]);
298
+ const rewrite = asField(o, ["rewrite", "rewritten", "instruction", "改写"]);
299
+ return {
300
+ respond,
301
+ reason: asField(o, ["reason", "理由"]),
302
+ ...(respond && intent ? { intent } : {}),
303
+ ...(respond && rewrite ? { rewrite } : {}),
304
+ };
305
+ }
306
+ catch { /* 不是这一块 */ }
307
+ }
308
+ const plain = text.trim();
309
+ if (/^yes\b/i.test(plain))
310
+ return { respond: true, reason: plain.slice(0, 120) };
311
+ if (/^no\b/i.test(plain))
312
+ return { respond: false, reason: plain.slice(0, 120) };
313
+ return undefined;
314
+ };
315
+ /** 判官放行后交给主 agent 的正文: 改写优先, 原文永远可回溯。
316
+ * 改写缺失 / 为空 / 与原文相同 → 原样用原帖, 改写这一层坏了也不丢消息。 */
317
+ const bodyFor = (text, verdict) => {
318
+ const rewrite = verdict.respond ? (verdict.rewrite ?? "").trim() : "";
319
+ if (!rewrite || rewrite === text.trim())
320
+ return text;
321
+ return `${rewrite}\n——\n原帖:${text}`;
322
+ };
323
+ /** 判官是一次性判定, 不是一个住下来的会话: 一个 `-p` 进程进, stdout 出一行 JSON。
324
+ * 不落会话 (--no-session-persistence)、不给工具 (--tools "")、不带 --settings /
325
+ * --session-id —— 判官不该在 projects/ 里留痕被当成可镜像的会话, 也不该出审批卡。 */
326
+ export const runJudgeOnce = (deps, prompt) => {
327
+ const { cfg, log } = deps;
328
+ const backend = resolveCliBackend(cfg.wrc);
329
+ if (!backend.oneShotArgs) {
330
+ log.warn({ backend: backend.name }, "channel judge: backend has no one-shot mode");
331
+ return Promise.resolve(undefined);
332
+ }
333
+ const pick = pickTier(cfg, cfg.wrc.channel.judge.tier, {});
334
+ const args = backend.oneShotArgs(prompt, {
335
+ ...(pick.ok && pick.model ? { model: pick.model } : {}),
336
+ ...(pick.ok && pick.effort ? { effort: pick.effort } : {}),
337
+ });
338
+ const timeoutMs = cfg.wrc.channel.judge.timeoutMs;
339
+ return new Promise((resolve) => {
340
+ const started = Date.now();
341
+ const proc = spawn(backend.bin, args, {
342
+ cwd: expandHome(cfg.wrc.cwd),
343
+ env: { ...process.env, PATH: augmentedPath(process.env.PATH) },
344
+ stdio: ["ignore", "pipe", "pipe"],
345
+ });
346
+ let out = "";
347
+ let errTail = "";
348
+ let settled = false;
349
+ const finish = (text, why) => {
350
+ if (settled)
351
+ return;
352
+ settled = true;
353
+ clearTimeout(timer);
354
+ const ms = Date.now() - started;
355
+ if (text)
356
+ log.info({ ms, tier: pick.ok ? pick.tier : undefined, model: pick.ok ? pick.model : undefined }, "channel judge ran");
357
+ else
358
+ log.warn({ ms, why, bin: backend.bin, stderrTail: errTail.slice(-200) }, "channel judge: no verdict");
359
+ resolve(text);
360
+ };
361
+ const timer = setTimeout(() => {
362
+ proc.kill("SIGKILL");
363
+ finish(undefined, `timeout ${timeoutMs}ms`);
364
+ }, timeoutMs);
365
+ proc.stdout?.on("data", (c) => { out = (out + c.toString("utf8")).slice(-8000); });
366
+ proc.stderr?.on("data", (c) => { errTail = (errTail + c.toString("utf8")).slice(-800); });
367
+ proc.on("error", (e) => finish(undefined, `spawn ${e.message}`));
368
+ proc.on("close", (code) => {
369
+ if (code !== 0)
370
+ return finish(undefined, `exit ${code}`);
371
+ finish(out.trim() || undefined, "empty output");
372
+ });
373
+ });
374
+ };
375
+ const askJudge = async (deps, prompt) => {
376
+ const text = await runJudgeOnce(deps, prompt);
377
+ if (!text)
378
+ return undefined;
379
+ const verdict = parseVerdict(text);
380
+ if (!verdict)
381
+ deps.log.warn({ chars: text.length, head: text.slice(0, 200) }, "channel judge: unparsable output");
382
+ return verdict;
383
+ };
384
+ const botName = (cfg) => cfg.wrc.botNames.find(Boolean) ?? "wezard";
385
+ /** 每条历史都带 id + 时刻: 判官只做判定不改身份, 但它引用的那一句必须能被
386
+ * 目标 agent 直接指回去, 所以 id 不能被压缩成 "第 N 条"。 */
387
+ const judgeLine = (m, mark = " ") => `${mark}${m.kind === "reply" ? "reply" : "post"}=${m.id} [${stamp(m.at)}] ${m.author}: ${clip(m.text, 300)}`;
388
+ export const buildJudgePrompt = (cfg, i) => {
389
+ const base = `chat:${i.topicId}`;
390
+ const me = botName(cfg);
391
+ const job = wizardStore()?.get(base)?.description ?? "这个频道的助手";
392
+ const others = (wizardStore()?.all() ?? [])
393
+ .filter((w) => baseOfKey(w.target) === base && w.target !== base && w.target !== keyOf(base, "judge"))
394
+ .map((w) => `${w.name || w.target}${w.description ? `(${w.description})` : ""}`)
395
+ .slice(0, 12);
396
+ const isReply = i.triggerId && i.triggerId !== i.postId;
397
+ return [
398
+ `你是 ${me} 的频道判官。判断最新一条消息是否应该由 ${me} 回应;该回应时,把它整理成一条给主 agent 的指令。`,
399
+ `定位:topic=${i.topicId} · thread post=${i.postId}${isReply ? ` · 本次消息 reply=${i.triggerId}` : ""} · msgid=${i.msgid}`,
400
+ `你的职责:${job}`,
401
+ others.length ? `频道里其他机器人:${others.join("、")}` : "",
402
+ i.thread.length ? "这条消息所在的线程(父帖 + 评论,都带 id):" : "",
403
+ ...i.thread.map((m) => judgeLine(m, " ")),
404
+ i.recent.length ? "最近的频道消息(旧→新):" : "",
405
+ ...i.recent.map((m, k) => judgeLine(m, `[${k + 1}] `)),
406
+ `最新消息(${i.latestAuthor}):${clip(i.latest, 600)}`,
407
+ "",
408
+ "规则:",
409
+ "- 最新消息 @ 了别的机器人、明显属于别人的职责、或只是闲聊 → respond=false",
410
+ "- 最新消息在向本频道求助、需要你回答 → respond=true",
411
+ "- 拿不准也 respond=false;不要重复别人已经回答的内容",
412
+ "- respond=false 时不要写 intent / rewrite,留空字符串",
413
+ "",
414
+ "respond=true 时还要给出两步(只整理,不回答):",
415
+ "1. intent:一句话说清这条消息想要什么(问什么 / 要你做什么 / 报了什么故障)。",
416
+ "2. rewrite:把这条消息改写成一条主 agent 能直接执行的自洽指令 ——",
417
+ " 补全省略的主语和指代对象(必要时代上线程里被回复的那一句),把零散的一句压成一条完整指令;",
418
+ " 原文里的路径、命令、报错、数字、ID、链接一律原样保留,不添加原文没有的事实,不替用户补需求,不写答复内容;",
419
+ " 用与原文相同的语言,只写改写后的正文,不要加「改写:」之类的前缀。",
420
+ "",
421
+ "这是一次性请求:不要调用工具,不要回答用户,不要解释。只输出下面这一行 JSON(不要代码围栏):",
422
+ '{"respond":true|false,"reason":"一句话判断依据","intent":"一句话意图(respond=false 时留空)","rewrite":"改写后给主 agent 的指令正文(respond=false 时留空)"}',
423
+ ].filter(Boolean).join("\n");
424
+ };
425
+ // 出站传输补丁必须早于 installResponseTracker 安装:tracker 会把当时的
426
+ // client.sendMessage / replyStream 抓成 orig*,晚装就绕过了频道分支。
427
+ export const installChannelTransport = (client, log) => {
428
+ log.info("channel transport installed");
429
+ const sendPost = (topicId, content) => call(client, CMD_POST, { topic_id: topicId, content })
430
+ .then((body) => {
431
+ if (body?.errcode)
432
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId }, "channel post rejected");
433
+ else
434
+ log.info({ topicId, len: content.length }, "channel post sent");
435
+ const id = String(body?.post_id ?? "");
436
+ if (id)
437
+ lastPost.set(topicId, id);
438
+ return body;
439
+ })
440
+ .catch((e) => { log.warn({ err: e.message, topicId }, "channel post failed"); return undefined; });
441
+ const sendReply = (ctx, content) => call(client, CMD_REPLY, { topic_id: ctx.topicId, post_id: ctx.postId, content })
442
+ .then((body) => {
443
+ if (body?.errcode)
444
+ log.warn({ errcode: body.errcode, errmsg: body.errmsg, topicId: ctx.topicId }, "channel reply rejected");
445
+ else
446
+ log.info({ topicId: ctx.topicId, postId: ctx.postId, len: content.length }, "channel reply sent");
447
+ return body;
448
+ })
449
+ .catch((e) => { log.warn({ err: e.message, topicId: ctx.topicId }, "channel reply failed"); return undefined; });
450
+ // ── 出站:topic 不走群 chatid,改成频道帖子 / 评论 ──
451
+ const origSend = client.sendMessage.bind(client);
452
+ client.sendMessage = (chatid, body) => {
453
+ // mirror 有时把 “chat:<topic>” 原样递进来;topic 集合里存的是裸 topic_id。
454
+ const bare = String(chatid).replace(/^(user|chat|group):/, "");
455
+ const topicId = topics.has(chatid) ? chatid : topics.has(bare) ? bare : "";
456
+ if (!topicId)
457
+ return origSend(chatid, body);
458
+ // 频道没有模板卡片按钮;审批卡改投问话人的私聊,点完结论仍回到频道。
459
+ if (body?.msgtype === "template_card") {
460
+ const asker = lastAsker.get(topicId);
461
+ if (asker) {
462
+ log.info({ topicId, asker }, "channel: card routed to asker DM");
463
+ return origSend(asker, body);
464
+ }
465
+ log.warn({ topicId }, "channel: template_card dropped (no asker)");
466
+ return Promise.resolve(emptyFrame());
467
+ }
468
+ const content = body?.msgtype === "markdown" ? String(body.markdown?.content ?? "") : "";
469
+ if (!content) {
470
+ log.warn({ topicId, msgtype: body?.msgtype }, "channel: unsupported outbound");
471
+ return Promise.resolve(emptyFrame());
472
+ }
473
+ const postId = lastPost.get(topicId);
474
+ // 只有被 @ 过的帖子才能评论;未被 @ 的新帖只能主动发一条新帖。
475
+ return postId && replyOk.get(postId) === true
476
+ ? sendReply({ topicId, postId, asker: lastAsker.get(topicId) ?? "" }, content)
477
+ : sendPost(topicId, content);
478
+ };
479
+ // replyStream 的气泡只对群聊有意义;频道里把最终帧落成一条评论,中间帧丢掉。
480
+ const origStream = client.replyStream.bind(client);
481
+ client.replyStream = (frame, streamId, content, finish = false, ...rest) => {
482
+ // 事件流里的 streamId 可能是 route eventId,而 fake frame 的 req_id 才是频道 msgid —— 两边都认。
483
+ const ctx = byStream.get(streamId) ?? byStream.get(String(frame?.headers?.req_id ?? ""));
484
+ if (!ctx)
485
+ return origStream(frame, streamId, content, finish, ...rest);
486
+ if (!finish)
487
+ return Promise.resolve(emptyFrame());
488
+ return replyOk.get(ctx.postId) === true ? sendReply(ctx, content) : sendPost(ctx.topicId, content);
489
+ };
490
+ };
491
+ export const installChannelEvents = (client, cfg, log) => {
492
+ const wsm = client.wsManager;
493
+ if (!wsm || typeof wsm.handleFrame !== "function") {
494
+ log.warn("channel: wsManager.handleFrame unavailable; topic events will be ignored");
495
+ return;
496
+ }
497
+ const dispatch = (topicId, postId, msgid, fromUser, text, at, allowReply) => {
498
+ if (dispatched.has(postId))
499
+ return;
500
+ dispatched.add(postId);
501
+ if (dispatched.size > 3000)
502
+ dispatched.delete(dispatched.values().next().value);
503
+ replyOk.set(postId, allowReply);
504
+ if (replyOk.size > 3000)
505
+ replyOk.delete(replyOk.keys().next().value);
506
+ lastPost.set(topicId, postId);
507
+ byStream.set(msgid, { topicId, postId, asker: fromUser });
508
+ if (byStream.size > 3000)
509
+ byStream.delete(byStream.keys().next().value);
510
+ const fake = {
511
+ headers: { req_id: msgid },
512
+ body: {
513
+ msgid,
514
+ chattype: "group",
515
+ chatid: topicId,
516
+ from: { userid: fromUser },
517
+ create_time: at,
518
+ msgtype: "text",
519
+ text: { content: text },
520
+ },
521
+ };
522
+ log.info({ topicId, postId, msgid, len: text.length }, "channel rx");
523
+ client.emit("message.text", fake);
524
+ };
525
+ const mentions = (post) => {
526
+ const list = post?.inline_mention_list ?? post?.mention_list ?? [];
527
+ if (!Array.isArray(list))
528
+ return [];
529
+ return list.map((x) => {
530
+ const m = x?.member ?? x ?? {};
531
+ return { type: Number(m.type ?? 0), bot: typeof m.aibotid === "string" ? m.aibotid : undefined };
532
+ });
533
+ };
534
+ const judgeAndMaybe = async (topicId, postId, msgid, fromUser, text, at, selfBot, triggerId) => {
535
+ if (!cfg.wrc.channel.judge.enabled) {
536
+ log.info({ topicId, postId }, "channel judge disabled");
537
+ return;
538
+ }
539
+ if (dispatched.has(postId)) {
540
+ log.info({ topicId, postId }, "channel judge skipped: already dispatched");
541
+ return;
542
+ }
543
+ const post = await fetchPost(client, topicId, postId, log);
544
+ const ms = mentions(post);
545
+ // 不能因为“提到自己”就跳过:回复/引用机器人时 inline_mention 也可能带上自己,
546
+ // 但这时不一定有 topic_at_bot。交给判官,dispatched 会保证不会双答。
547
+ if (ms.some((m) => m.type === 1 && m.bot === selfBot)) {
548
+ log.info({ topicId, postId }, "channel judge: self-mention, wait for topic_at_bot");
549
+ // 先等一拍:真有 topic_at_bot 就让直接 @ 路径答(评论);没有才走判官。
550
+ await sleep(1200);
551
+ if (dispatched.has(postId)) {
552
+ log.info({ topicId, postId }, "channel judge skipped: self-mention handled by topic_at_bot");
553
+ return;
554
+ }
555
+ }
556
+ if (ms.some((m) => m.type === 1 && m.bot && m.bot !== selfBot)) {
557
+ log.info({ topicId, postId }, "channel judge skipped: addressed to another bot");
558
+ return;
559
+ }
560
+ const recent = await recentPosts(client, cfg, log, topicId, cfg.wrc.channel.judge.maxPosts);
561
+ const thread = withoutMsg((await ensureStore(cfg)?.thread(topicId, postId, 4)) ?? [], triggerId);
562
+ const prompt = buildJudgePrompt(cfg, {
563
+ topicId, postId, triggerId, msgid,
564
+ recent: withoutMsg(recent, triggerId),
565
+ thread,
566
+ latest: text,
567
+ latestAuthor: fromUser,
568
+ });
569
+ // 一次 -p 进程也串行:同一 topic 两条消息同时到不该各起一个, 判词会互相盖。
570
+ const verdict = await serial(`judge:${topicId}`, () => askJudge({ cfg, log }, prompt));
571
+ if (!verdict?.respond) {
572
+ // 超时 / 进程失败 / 输出解析不了都落在这里: 判官是个减噪层, 它的结论是「不回应」。
573
+ // 回落 = 不投递 (频道里不会有人收到这条), 但要留得下可查的一行 —— 不静默丢。
574
+ log.warn({ topicId, postId, msgid, triggerId, reason: verdict?.reason ?? "timeout/unparsable" }, "channel judge: no dispatch (verdict absent or respond=false)");
575
+ return;
576
+ }
577
+ log.info({ topicId, postId, reason: verdict.reason, intent: verdict.intent, rewritten: !!verdict.rewrite }, "channel judge: yes");
578
+ // 判官说 YES 才拼展开版上下文: 线程 + 最近 + (这句话有指代时) 搜索命中。
579
+ // 入站帧的 msgid 随首行一起下去 —— 判官只加意图 / 改写,不替换身份。
580
+ const ctx = await contextFor({ client, cfg, log }, topicId, postId, triggerId, text, {
581
+ reason: verdict.reason,
582
+ msgid,
583
+ ...(verdict.intent ? { intent: verdict.intent } : {}),
584
+ });
585
+ dispatch(topicId, postId, msgid, fromUser, `${ctx}\n——\n${bodyFor(text, verdict)}`, at, false);
586
+ };
587
+ const onTopic = async (frame) => {
588
+ const body = frame?.body ?? {};
589
+ const ev = body.event ?? {};
590
+ const topicId = String(body.topic_id ?? "");
591
+ const from = body.from ?? {};
592
+ const asker = String(from.userid ?? "");
593
+ const selfBot = String(body.aibotid ?? "");
594
+ const at = Number(body.create_time ?? 0) * 1000 || Date.now();
595
+ if (!topicId)
596
+ return;
597
+ topics.add(topicId);
598
+ if (asker)
599
+ lastAsker.set(topicId, asker);
600
+ // 第一次见到的频道从官方补最近 N 条 (reload / 断线空窗期的事件本地没有)。
601
+ void backfill(client, cfg, log, topicId).catch((e) => log.warn({ err: e.message, topicId }, "channel backfill failed"));
602
+ 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");
603
+ if (ev.eventtype === "topic_at_bot") {
604
+ const postId = String(ev.topic_at_bot?.post_id ?? "");
605
+ const replyId = String(ev.topic_at_bot?.reply_id ?? "");
606
+ const msgid = String(body.msgid ?? postId);
607
+ if (!postId || !msgid)
608
+ return;
609
+ if (seen.has(msgid))
610
+ return;
611
+ seen.add(msgid);
612
+ if (seen.size > 3000)
613
+ seen.delete(seen.values().next().value);
614
+ if (dispatched.has(postId))
615
+ return;
616
+ const post = await fetchPost(client, topicId, postId, log);
617
+ const reply = replyId ? await fetchReply(client, topicId, postId, replyId, log) : null;
618
+ if (!post)
619
+ log.warn({ topicId, postId }, "channel: post content not found");
620
+ await record(cfg, topicId, postMsg(post));
621
+ if (reply)
622
+ await record(cfg, topicId, replyMsg(reply, postId));
623
+ const text = cleanContent(reply?.content ?? post?.content) || "(在频道里 @ 了你,没有正文)";
624
+ const ctx = await contextFor({ client, cfg, log }, topicId, postId, replyId || postId, text, { msgid });
625
+ dispatch(topicId, postId, msgid, asker, `${ctx}\n——\n${text}`, at, true);
626
+ return;
627
+ }
628
+ if (ev.eventtype === "topic_event" && Number(ev.topic_event?.type ?? 0) === 1) {
629
+ const postId = String(ev.topic_event?.post_id ?? "");
630
+ const msgid = String(body.msgid ?? postId);
631
+ if (!postId || !msgid)
632
+ return;
633
+ if (seen.has(msgid) || dispatched.has(postId)) {
634
+ log.info({ topicId, postId, msgid }, "channel topic_event skipped: seen/dispatched");
635
+ return;
636
+ }
637
+ if (!asker) {
638
+ log.info({ topicId, postId, msgid }, "channel topic_event skipped: bot-authored");
639
+ return;
640
+ }
641
+ seen.add(msgid);
642
+ if (seen.size > 3000)
643
+ seen.delete(seen.values().next().value);
644
+ const post = await fetchPost(client, topicId, postId, log);
645
+ await record(cfg, topicId, postMsg(post));
646
+ const text = cleanContent(post?.content);
647
+ if (!text)
648
+ return;
649
+ void judgeAndMaybe(topicId, postId, msgid, asker, text, at, selfBot, postId)
650
+ .catch((e) => log.warn({ err: e.message, topicId, postId }, "channel judge failed"));
651
+ return;
652
+ }
653
+ if (ev.eventtype === "topic_reply_event" && Number(ev.topic_reply_event?.type ?? 0) === 1) {
654
+ const postId = String(ev.topic_reply_event?.post_id ?? "");
655
+ const replyId = String(ev.topic_reply_event?.reply_id ?? "");
656
+ const msgid = String(body.msgid ?? replyId);
657
+ if (!postId || !replyId || !msgid)
658
+ return;
659
+ if (seen.has(replyId) || dispatched.has(replyId) || !asker) {
660
+ log.info({ topicId, postId, replyId, msgid, asker }, "channel topic_reply_event skipped");
661
+ return;
662
+ }
663
+ seen.add(replyId);
664
+ if (seen.size > 3000)
665
+ seen.delete(seen.values().next().value);
666
+ const reply = await fetchReply(client, topicId, postId, replyId, log);
667
+ await record(cfg, topicId, replyMsg(reply, postId));
668
+ const text = cleanContent(reply?.content);
669
+ if (!text)
670
+ return;
671
+ void judgeAndMaybe(topicId, postId, msgid, asker, text, at, selfBot, replyId)
672
+ .catch((e) => log.warn({ err: e.message, topicId, postId }, "channel judge failed"));
673
+ return;
674
+ }
675
+ log.debug({ type: ev.eventtype, topicId }, "channel event ignored");
676
+ };
677
+ // 先接住原始帧,再交给 SDK 原来的 handleFrame(普通群 / 单聊不受影响)。
678
+ // 注意不能包 onMessage: WSManager.handleFrame 的未知帧分支根本不会调它。
679
+ const prev = wsm.handleFrame.bind(wsm);
680
+ wsm.handleFrame = (frame) => {
681
+ if (frame?.cmd === TOPIC_EVENT) {
682
+ void onTopic(frame).catch((e) => log.warn({ err: e.message }, "channel event failed"));
683
+ return;
684
+ }
685
+ prev(frame);
686
+ };
687
+ };
688
+ // 兼容入口:新代码应分别早装 transport、晚装 events。
689
+ export const installChannelBridge = (client, cfg, log) => {
690
+ installChannelTransport(client, log);
691
+ installChannelEvents(client, cfg, log);
692
+ };
693
+ //# sourceMappingURL=channel.js.map