wechat-clawbot 1.0.0 → 1.0.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.
package/lib/bridge.js CHANGED
@@ -7,7 +7,7 @@
7
7
  * collected from the durable `session/event` feed and sent back to the WeChat
8
8
  * user who triggered the turn.
9
9
  */
10
- import { readFileSync, unlinkSync } from "node:fs";
10
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
11
11
  import { basename } from "node:path";
12
12
  import { installModelSelection, } from "@deepseek-ai/dsh-agent";
13
13
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -19,11 +19,25 @@ import { registerCodexPeerTools } from "./codex-peer.js";
19
19
  import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
20
20
  import { markSessionCreated, wasSessionCreated } from "./state.js";
21
21
  import { TypingIndicator } from "./typing.js";
22
+ import { HOLD_MESSAGE, INCOMING_WAIT_MS, MAX_HOLDS, MAX_RESTARTS, TOGETHER_HINT, mayRestartTurn, shouldHoldReply } from "./coalesce.js";
23
+ import { Backlog, FILE_ATTEMPTS, digestChunks, dueStamp, fileLabel, isSendWindowClosed, occurrenceAt } from "./backlog.js";
22
24
  /**
23
25
  * Tool calls that are the bot talking to the user, not working: they must not
24
26
  * bring 「正在输入」 back after a reply (see TypingIndicator.noteWorking).
25
27
  */
26
28
  const REPLY_TOOLS = new Set(["send_wechat_text", "send_wechat_file", "ask_user_question"]);
29
+ /** A user message as the WeChat bridge appends it. */
30
+ function wechatUserMessage(parts) {
31
+ return createUserMessage({
32
+ content: parts,
33
+ // v4 sessions refuse the retired `{ kind: "plugin", plugin }` wrapper
34
+ // outright ("format v4 message requires a producer-owned source kind"),
35
+ // so every inbound WeChat message would fail to append. This is the exact
36
+ // kind the v3→v4 converter gives this plugin's history
37
+ // (`plugin:${name}` for a third-party producer), so old and new agree.
38
+ source: { kind: "plugin:wechat-clawbot" },
39
+ });
40
+ }
27
41
  import { IdleCompactor, IDLE_COMPACT_RATIO, hostCompactionThreshold } from "./idle-compact.js";
28
42
  import { registerSendFileTool } from "./tool.js";
29
43
  import { randomUUID } from "node:crypto";
@@ -41,6 +55,33 @@ export class WechatBridge {
41
55
  selectionInstalled = new WeakSet();
42
56
  /** Queued turns waiting for the serialized worker (oldest first). */
43
57
  queue = [];
58
+ /** Whether the running turn has answered yet (sent, asked, or started a file). */
59
+ answeredThisTurn = false;
60
+ /** Replies held this turn because the recipient wrote more (capped, see coalesce.ts). */
61
+ holdsThisTurn = 0;
62
+ /** Texts the current queued turn answers (batch, merges, steered ones), for auto-memory. */
63
+ chainTexts = [];
64
+ /** Tool calls in the current turn; 0 means the bot is still on its first thought. */
65
+ toolCallsThisTurn = 0;
66
+ /** Restarts made while answering the current queued message (capped). */
67
+ restarts = 0;
68
+ /**
69
+ * The message the worker's running turn answers. A newer one merges into it
70
+ * while the host has not picked it up (a restart settling, maintenance
71
+ * holding the agent); once written into the history (`recordedAt`, the host
72
+ * turn and step that did it), a restart may cancel that step without losing
73
+ * it. A restart's own message is `restarted` and carries TOGETHER_HINT.
74
+ */
75
+ turnMessage;
76
+ /** The host turn and step running now, from turn/start and step/start. */
77
+ hostTurn = 0;
78
+ hostStep = 0;
79
+ /** Messages each sender has put into the agent's inbox, by id; unread while still there. */
80
+ inboxIds = new Map();
81
+ /** What those messages were, to answer them if a turn ends with them still waiting. */
82
+ inboxTasks = new Map();
83
+ /** Messages per sender that reached clawbot but not the bridge yet (an image downloading). */
84
+ incoming = new Map();
44
85
  /** Whether the WeChat tools are registered on the current agent scope. */
45
86
  toolsRegistered = false;
46
87
  /** The sender whose turn is currently being driven (approvals go to them). */
@@ -64,12 +105,23 @@ export class WechatBridge {
64
105
  idleCompact;
65
106
  /** Tokens the last model request on this session carried, as reported by the provider. */
66
107
  lastRequestTokens;
108
+ /** Messages WeChat would not take yet; sent after the user's next message is answered. */
109
+ backlog;
110
+ /** When each sender's latest message reached the bot: that reopens WeChat's window. */
111
+ lastInbound = new Map();
112
+ /** Recipients whose backlog is being delivered right now (one delivery at a time). */
113
+ delivering = new Set();
114
+ /** Senders whose message was steered into a turn the worker does not drive (a reminder). */
115
+ steeredIntoOtherTurn = new Set();
116
+ /** When the running reminder turn was due: what a refused reminder is stamped with. */
117
+ reminderDueAt;
67
118
  constructor(ctx, config, sendText, deps) {
68
119
  this.ctx = ctx;
69
120
  this.config = config;
70
121
  this.sendText = sendText;
71
122
  this.deps = deps;
72
123
  this.sessionId = SessionId(config.sessionId);
124
+ this.backlog = deps.backlog ?? new Backlog();
73
125
  this.typing = new TypingIndicator({
74
126
  getAccount: () => deps.getAccount(),
75
127
  getContextToken: (sender) => deps.getContextToken(sender),
@@ -167,17 +219,217 @@ export class WechatBridge {
167
219
  return false;
168
220
  }
169
221
  this.turnMessageCount += 1;
222
+ this.answeredThisTurn = true;
223
+ const due = this.reminderDueAt ?? new Date().toISOString();
170
224
  this.sendChain = this.sendChain.then(async () => {
171
225
  try {
172
226
  await this.sendText(sender, text);
173
227
  this.typing.noteDelivered(sender);
174
228
  }
175
229
  catch (err) {
176
- logger.error(`sendTextTo: failed to ${sender}: ${String(err)}`);
230
+ // `transient` lines (a question the bot waits on, an upload notice)
231
+ // mean nothing later; everything else waits for the user's next message.
232
+ if (!opts?.transient && isSendWindowClosed(err))
233
+ this.keep(sender, { kind: "text", at: due, text });
234
+ else
235
+ logger.error(`sendTextTo: failed to ${sender}: ${String(err)}`);
177
236
  }
178
237
  });
179
238
  return true;
180
239
  }
240
+ /** send_wechat_file hit WeChat's closed window: keep the file for later. */
241
+ keepFile(to, file) {
242
+ this.keep(to, { kind: "file", at: this.reminderDueAt ?? new Date().toISOString(), ...file });
243
+ }
244
+ /** Keep what WeChat would not take now (see backlog.ts). */
245
+ keep(to, item) {
246
+ try {
247
+ this.backlog.add(to, item);
248
+ logger.info(`backlog: WeChat will not let the bot write first now; kept a ${item.kind} for ${to} until they write again`);
249
+ }
250
+ catch (err) {
251
+ logger.error(`backlog: could not keep a ${item.kind} for ${to}: ${String(err)}`);
252
+ }
253
+ }
254
+ /**
255
+ * Send what WeChat would not take earlier, once `to` has written again and
256
+ * the bot has answered: one digest in time order (on the outbound chain, so
257
+ * it lands after the reply), then any files. One delivery at a time.
258
+ */
259
+ deliverBacklog(to) {
260
+ if (this.disposed || this.delivering.has(to))
261
+ return;
262
+ let items;
263
+ try {
264
+ items = this.backlog.peek(to);
265
+ }
266
+ catch (err) {
267
+ logger.warn(`backlog: unreadable for ${to}: ${String(err)}`);
268
+ return;
269
+ }
270
+ if (items.length === 0)
271
+ return;
272
+ // Only after they have written since the last failure; before that the
273
+ // window is still shut and the digest would just fail again.
274
+ const newest = Math.max(...items.map((item) => Date.parse(item.at)));
275
+ if ((this.lastInbound.get(to) ?? 0) <= newest)
276
+ return;
277
+ this.delivering.add(to);
278
+ this.sendChain = this.sendChain.then(async () => {
279
+ try {
280
+ // A superseded instance (instance-guard.ts) leaves this to the new one.
281
+ if (this.disposed) {
282
+ this.delivering.delete(to);
283
+ return;
284
+ }
285
+ const digest = await this.sendDigest(to, items);
286
+ if (digest.delivered.length > 0)
287
+ this.noteBacklogDelivered(digest.delivered);
288
+ if (!digest.complete) {
289
+ this.delivering.delete(to);
290
+ return;
291
+ }
292
+ // Uploads can take a minute: they run off the outbound chain, so the
293
+ // next replies are not held up behind them.
294
+ void this.sendKeptFiles(to, items)
295
+ .catch((err) => logger.error(`backlog: kept files for ${to} failed: ${String(err)}`))
296
+ .finally(() => this.delivering.delete(to));
297
+ }
298
+ catch (err) {
299
+ // Never let the outbound chain reject (DSH exits on an unhandled rejection).
300
+ logger.error(`backlog: delivery for ${to} failed: ${String(err)}`);
301
+ this.delivering.delete(to);
302
+ }
303
+ });
304
+ }
305
+ /** The digest, part by part; each part's items are settled once it is out. */
306
+ async sendDigest(to, items) {
307
+ const byId = new Map(items.map((item) => [item.id, item]));
308
+ const delivered = [];
309
+ for (const chunk of digestChunks(items, { fileExists: (p) => existsSync(p) })) {
310
+ try {
311
+ await this.sendText(to, chunk.text);
312
+ }
313
+ catch (err) {
314
+ logger.warn(`backlog: digest for ${to} not delivered (${String(err)}); keeping the rest for next time`);
315
+ return { delivered, complete: false };
316
+ }
317
+ const carried = chunk.ids.map((id) => byId.get(id));
318
+ // A text or notice is delivered now, and so is a file that is gone (the
319
+ // digest said so). A file that is there has been announced: it follows.
320
+ const settled = carried.filter((item) => item.kind !== "file" || !existsSync(item.path));
321
+ this.forget(to, settled.map((item) => item.id));
322
+ try {
323
+ this.backlog.markAnnounced(to, carried.filter((item) => item.kind === "file" && existsSync(item.path)).map((item) => item.id));
324
+ }
325
+ catch (err) {
326
+ logger.warn(`backlog: could not mark files as announced for ${to}: ${String(err)}`);
327
+ }
328
+ delivered.push(...settled.filter((item) => item.kind !== "file"));
329
+ }
330
+ return { delivered, complete: true };
331
+ }
332
+ /** Files a digest said would follow; give up with one line after FILE_ATTEMPTS. */
333
+ async sendKeptFiles(to, items) {
334
+ const sentFiles = [];
335
+ for (const item of items) {
336
+ if (this.disposed)
337
+ break;
338
+ if (item.kind !== "file" || !existsSync(item.path))
339
+ continue;
340
+ const sent = this.deps.sendFile === undefined
341
+ ? { ok: false, windowClosed: false, permanent: true, message: "no file sender" }
342
+ : await this.deps.sendFile(to, { path: item.path, caption: item.caption, original: item.original })
343
+ .catch((err) => ({ ok: false, windowClosed: isSendWindowClosed(err), permanent: false, message: String(err) }));
344
+ if (sent.ok) {
345
+ this.forget(to, [item.id]);
346
+ sentFiles.push(item);
347
+ continue;
348
+ }
349
+ logger.warn(`backlog: kept file ${item.path} not sent: ${sent.message}`);
350
+ // Too big for WeChat never changes. A shut window or a network/CDN
351
+ // failure may: it is retried after their next message, a few times at most.
352
+ let attempts = FILE_ATTEMPTS;
353
+ if (!sent.permanent) {
354
+ try {
355
+ attempts = this.backlog.bumpAttempts(to, item.id);
356
+ }
357
+ catch { /* treated as used up */ }
358
+ }
359
+ if (attempts < FILE_ATTEMPTS)
360
+ continue;
361
+ this.forget(to, [item.id]);
362
+ // The digest said it would follow: say once that it will not.
363
+ const why = sent.permanent ? "超过了微信能收的大小" : `补发了 ${FILE_ATTEMPTS} 次都没发出去`;
364
+ const line = `〔${dueStamp(new Date(item.at))}〕${fileLabel(item.path)} ${why},没能补发。`;
365
+ try {
366
+ await this.sendText(to, line);
367
+ }
368
+ catch (err) {
369
+ logger.warn(`backlog: could not tell ${to} that a file was given up: ${String(err)}`);
370
+ }
371
+ this.noteSession(`[补发] ${line}`);
372
+ }
373
+ logger.info(`backlog: sent ${sentFiles.length} kept file(s) to ${to}`);
374
+ if (sentFiles.length > 0)
375
+ this.noteBacklogDelivered(sentFiles);
376
+ }
377
+ /**
378
+ * After a turn the worker did not drive (a reminder, a web turn) that
379
+ * someone's WeChat message was steered into: once the agent is idle, a
380
+ * message that turn never read (it failed) is answered first; then what
381
+ * WeChat refused earlier goes out.
382
+ */
383
+ afterOtherTurn(senders) {
384
+ const live = this.ctx.agents.get(this.sessionId);
385
+ if (live === undefined)
386
+ return;
387
+ void live.whenIdle().then(() => {
388
+ if (this.disposed || this.worker !== null)
389
+ return; // the worker answers and delivers
390
+ this.requeueUnread(live);
391
+ if (this.queue.length > 0) {
392
+ this.runWorker();
393
+ return;
394
+ }
395
+ for (const sender of senders)
396
+ this.deliverBacklog(sender);
397
+ }).catch((err) => logger.warn(`afterOtherTurn: ${String(err)}`));
398
+ }
399
+ /** Drop delivered (or hopeless) items from the backlog. */
400
+ forget(to, ids) {
401
+ if (ids.length === 0)
402
+ return;
403
+ try {
404
+ this.backlog.remove(to, ids);
405
+ }
406
+ catch (err) {
407
+ logger.error(`backlog: could not clear ${ids.length} item(s) for ${to}: ${String(err)}`);
408
+ }
409
+ }
410
+ /**
411
+ * Tell the bot what just went out late, so a reply to one of those messages
412
+ * makes sense to it. Injected, not followed up: it rides along with the next turn.
413
+ */
414
+ noteBacklogDelivered(items) {
415
+ const live = this.ctx.agents.get(this.sessionId);
416
+ if (!live)
417
+ return;
418
+ const times = items.map((item) => Date.parse(item.at)).sort((a, b) => a - b);
419
+ const first = dueStamp(new Date(times[0]));
420
+ const last = dueStamp(new Date(times[times.length - 1]));
421
+ const span = first === last ? first : `${first} 至 ${last}`;
422
+ this.noteSession(`[补发] 刚才把之前没送达的 ${items.length} 条消息(原定 ${span})补发给了对方。`);
423
+ }
424
+ /** A line for the bot about what was (or was not) delivered late; it rides along with the next turn. */
425
+ noteSession(text) {
426
+ try {
427
+ this.ctx.agents.get(this.sessionId)?.inject(wechatUserMessage([{ type: "text", text }]));
428
+ }
429
+ catch (err) {
430
+ logger.warn(`backlog: could not note the delivery in the session: ${String(err)}`);
431
+ }
432
+ }
181
433
  get id() {
182
434
  return this.sessionId;
183
435
  }
@@ -191,7 +443,7 @@ export class WechatBridge {
191
443
  const sender = this.currentSender ?? this.deps.getAccount()?.userId;
192
444
  if (!sender || signal?.aborted)
193
445
  return Promise.resolve(null);
194
- this.sendTextTo(sender, question, { uncapped: true });
446
+ this.sendTextTo(sender, question, { uncapped: true, transient: true });
195
447
  return new Promise((resolve) => {
196
448
  let settled = false;
197
449
  const entry = {
@@ -751,27 +1003,69 @@ export class WechatBridge {
751
1003
  ? "\n(图片没有附在本条消息里,请用视觉工具读上面那个路径来查看。)"
752
1004
  : "\n(上面这张图已附在本条消息里,直接看图回应,不用再调视觉工具。)";
753
1005
  }
754
- const message = createUserMessage({
755
- content: block === null
756
- ? [{ type: "text", text: marked }]
757
- : [{ type: "text", text: marked }, block],
758
- // v4 sessions refuse the retired `{ kind: "plugin", plugin }` wrapper
759
- // outright ("format v4 message requires a producer-owned source kind"),
760
- // so every inbound WeChat message would fail to append. This is the exact
761
- // kind the v3→v4 converter gives this plugin's history
762
- // (`plugin:${name}` for a third-party producer), so old and new agree.
763
- source: { kind: "plugin:wechat-clawbot" },
764
- });
1006
+ const parts = block === null
1007
+ ? [{ type: "text", text: marked }]
1008
+ : [{ type: "text", text: marked }, block];
1009
+ const message = wechatUserMessage(parts);
1010
+ const task = { sender, text, message, parts };
1011
+ // Now it reaches the bot (an image may have taken a while to download).
1012
+ this.lastInbound.set(sender, Date.now());
765
1013
  const live = this.ctx.agents.get(this.sessionId);
766
- if (live && live.status === "running") {
767
- // Interrupt-style insertion: steer into the running turn (next-step).
768
- logger.info(`enqueueMessage: steering message (${text.length} chars) into running turn`);
1014
+ if (this.worker !== null && sender === this.currentSender && this.mergeIntoWaitingTurn(live, sender, parts, text)) {
1015
+ this.typing.start(sender);
1016
+ return;
1017
+ }
1018
+ if (live && live.status === "running" && mayRestartTurn({
1019
+ wechatTurn: this.worker !== null && this.turnMessage !== undefined,
1020
+ turnSender: this.currentSender,
1021
+ sender,
1022
+ recorded: this.turnMessage?.recordedAt !== undefined
1023
+ && this.turnMessage.recordedAt.turn === this.hostTurn && this.turnMessage.recordedAt.step === this.hostStep,
1024
+ toolCalls: this.toolCallsThisTurn,
1025
+ restarts: this.restarts,
1026
+ })) {
1027
+ // Still on its first thought, nothing called or sent: start over with
1028
+ // both (Claude Code's "send now"). Cancel first, keeping the inbox, then
1029
+ // follow up: the host opens the new turn once the aborted one settles (in
1030
+ // the other order the message would sit in the inbox with nothing to wake it).
1031
+ const restart = wechatUserMessage([...parts, { type: "text", text: TOGETHER_HINT }]);
1032
+ try {
1033
+ live.cancel({ kind: "hook", reason: "wechat: newer message from the same sender before any reply" }, { keepInbox: true });
1034
+ live.followup(restart);
1035
+ this.trackInbox({ sender, text, message: restart, parts });
1036
+ this.restarts += 1;
1037
+ this.chainTexts.push(text);
1038
+ this.turnMessage = { id: restart.id, parts: [...parts], restarted: true };
1039
+ logger.info(`enqueueMessage: newer message while the bot was still thinking; restarting the turn to answer both together (${this.restarts}/${MAX_RESTARTS})`);
1040
+ this.typing.start(sender);
1041
+ return;
1042
+ }
1043
+ catch (err) {
1044
+ logger.warn(`enqueueMessage: restart failed (${String(err)}); steering instead`);
1045
+ }
1046
+ }
1047
+ // Steer only into a turn that answers this sender (or nobody yet, a web
1048
+ // turn): steering someone else's message in would re-address the running
1049
+ // turn's reply to them. Theirs waits for its own turn in the queue.
1050
+ if (live && live.status === "running" && (this.currentSender === undefined || sender === this.currentSender)) {
1051
+ // The bot is already working: let the step finish and read it at the
1052
+ // next one, as Claude Code does with a message sent by Enter (see
1053
+ // coalesce.ts). Before the turn has answered, it is marked to be answered
1054
+ // together, and the reply tools hold until it has been read.
1055
+ const together = this.worker !== null && sender === this.currentSender && !this.answeredThisTurn;
1056
+ const steered = together ? wechatUserMessage([...parts, { type: "text", text: TOGETHER_HINT }]) : message;
1057
+ logger.info(`enqueueMessage: steering message (${text.length} chars) into running turn${together ? " (to be answered together)" : ""}`);
769
1058
  // Attribute the running turn's reply to the WeChat sender so the
770
1059
  // steered response (which may merge GUI + WeChat context) reaches the
771
1060
  // phone and is not dropped as "GUI-only".
772
1061
  this.currentSender = sender;
773
1062
  try {
774
- live.steer(message);
1063
+ live.steer(steered);
1064
+ this.trackInbox({ ...task, message: steered });
1065
+ if (this.worker !== null)
1066
+ this.chainTexts.push(text);
1067
+ else
1068
+ this.steeredIntoOtherTurn.add(sender);
775
1069
  this.typing.start(sender);
776
1070
  return;
777
1071
  }
@@ -779,10 +1073,123 @@ export class WechatBridge {
779
1073
  logger.warn(`enqueueMessage: steer failed (${String(err)}); falling back to queue`);
780
1074
  }
781
1075
  }
782
- this.queue.push({ sender, text, message });
1076
+ this.queue.push(task);
783
1077
  logger.info(`enqueueMessage: queued sender=${sender} msgId=${message.id} queueDepth=${this.queue.length}`);
784
1078
  void this.runWorker();
785
1079
  }
1080
+ /**
1081
+ * Add a newer message to the one the running turn has not picked up yet (a
1082
+ * restart settling, or maintenance such as compaction holding the agent).
1083
+ * False once the host has taken it; then the usual rules apply.
1084
+ */
1085
+ mergeIntoWaitingTurn(live, sender, parts, text) {
1086
+ const turn = this.turnMessage;
1087
+ if (live === undefined || turn === undefined || turn.recordedAt !== undefined)
1088
+ return false;
1089
+ const combined = [...turn.parts, ...parts];
1090
+ const merged = wechatUserMessage(turn.restarted ? [...combined, { type: "text", text: TOGETHER_HINT }] : combined);
1091
+ let replaced = false;
1092
+ try {
1093
+ replaced = live.inbox.replace(turn.id, merged);
1094
+ }
1095
+ catch (err) {
1096
+ logger.warn(`enqueueMessage: merging into the waiting message failed (${String(err)})`);
1097
+ }
1098
+ if (!replaced)
1099
+ return false;
1100
+ this.turnMessage = { ...turn, id: merged.id, parts: combined };
1101
+ const before = this.inboxTasks.get(turn.id);
1102
+ this.inboxTasks.delete(turn.id);
1103
+ this.trackInbox({ sender, text: before ? `${before.text}\n${text}` : text, message: merged, parts: combined });
1104
+ this.chainTexts.push(text);
1105
+ logger.info(`enqueueMessage: the bot had not picked up its message yet; merged this one into it`);
1106
+ return true;
1107
+ }
1108
+ /** Remember a message `task.sender` put into the agent's inbox (unread while it is still there). */
1109
+ trackInbox(task) {
1110
+ const ids = this.inboxIds.get(task.sender) ?? new Set();
1111
+ ids.add(task.message.id);
1112
+ this.inboxIds.set(task.sender, ids);
1113
+ this.inboxTasks.set(task.message.id, task);
1114
+ }
1115
+ /** A message from `sender` reached clawbot (+1) or the bridge (-1); see INCOMING_WAIT_MS. */
1116
+ noteIncoming(sender, delta) {
1117
+ const n = (this.incoming.get(sender) ?? 0) + delta;
1118
+ if (n > 0)
1119
+ this.incoming.set(sender, n);
1120
+ else
1121
+ this.incoming.delete(sender);
1122
+ }
1123
+ /**
1124
+ * After the worker's turn: messages still waiting in the agent's inbox (the
1125
+ * turn failed, or ended before reading them) are taken out and answered
1126
+ * next, instead of waiting for whatever the user sends after them.
1127
+ */
1128
+ requeueUnread(agent) {
1129
+ const waiting = new Set([...agent.inbox.nextStep, ...agent.inbox.nextTurn].map((m) => m.id));
1130
+ for (const [id, task] of this.inboxTasks) {
1131
+ if (!waiting.has(id)) {
1132
+ this.inboxTasks.delete(id);
1133
+ continue;
1134
+ }
1135
+ try {
1136
+ if (!agent.inbox.remove(task.message.id))
1137
+ continue;
1138
+ }
1139
+ catch (err) {
1140
+ logger.warn(`drainQueue: could not take back an unread message (${String(err)})`);
1141
+ continue;
1142
+ }
1143
+ this.inboxTasks.delete(id);
1144
+ this.inboxIds.get(task.sender)?.delete(id);
1145
+ this.queue.push(task);
1146
+ logger.info(`drainQueue: a message was still unread after the turn; answering it now`);
1147
+ }
1148
+ }
1149
+ /**
1150
+ * Whether `sender` has a message the next step will read: one still waiting
1151
+ * in the agent's next-step inbox. One queued for a later turn does not count;
1152
+ * holding a reply for it would only make the model wait for nothing.
1153
+ */
1154
+ hasUnread(sender) {
1155
+ const ids = this.inboxIds.get(sender);
1156
+ if (ids === undefined || ids.size === 0)
1157
+ return false;
1158
+ const inbox = this.ctx.agents.get(this.sessionId)?.inbox;
1159
+ const waiting = new Set((inbox?.nextStep ?? []).map((m) => m.id));
1160
+ for (const id of ids)
1161
+ if (!waiting.has(id))
1162
+ ids.delete(id);
1163
+ return ids.size > 0;
1164
+ }
1165
+ /**
1166
+ * Read before replying (see coalesce.ts): true when a reply to `sender` has
1167
+ * to wait because they wrote more that the model has not read yet. The
1168
+ * reply tool then returns HOLD_MESSAGE and the next step reads it.
1169
+ */
1170
+ async holdReply(sender, signal) {
1171
+ // A message from them is still on its way (an image downloading): let it
1172
+ // arrive first, unless the turn is stopped meanwhile (the tool then checks
1173
+ // its signal and sends nothing).
1174
+ for (let waited = 0; (this.incoming.get(sender) ?? 0) > 0 && waited < INCOMING_WAIT_MS && signal?.aborted !== true; waited += 100) {
1175
+ await new Promise((resolve) => setTimeout(resolve, 100));
1176
+ }
1177
+ if (signal?.aborted === true)
1178
+ return false;
1179
+ if (!shouldHoldReply({ unread: this.hasUnread(sender), holds: this.holdsThisTurn }))
1180
+ return false;
1181
+ this.holdsThisTurn += 1;
1182
+ logger.info(`reply held (${this.holdsThisTurn}/${MAX_HOLDS}): ${sender} wrote more that the bot has not read yet`);
1183
+ return true;
1184
+ }
1185
+ /** The text a held reply tool returns. */
1186
+ get holdMessage() {
1187
+ return HOLD_MESSAGE;
1188
+ }
1189
+ /** A reply tool went ahead: later messages this turn are follow-ups, not part of the same answer. */
1190
+ noteAnswered() {
1191
+ this.answeredThisTurn = true;
1192
+ }
786
1193
  /** Start the serialized worker if it is not already running. */
787
1194
  runWorker() {
788
1195
  if (this.worker)
@@ -794,23 +1201,46 @@ export class WechatBridge {
794
1201
  /** Drive queued turns one at a time; never rejects. */
795
1202
  async drainQueue() {
796
1203
  while (!this.disposed && this.queue.length > 0) {
797
- const task = this.queue.shift();
798
- this.currentSender = task.sender;
799
- this.turnMessageCount = 0; // 新回合重置发送计数
800
- this.typing.start(task.sender);
1204
+ // Messages that piled up from one sender (an image and its text, a quick
1205
+ // burst) go in as one message, so they get one answer.
1206
+ const first = this.queue.shift();
1207
+ const batch = [first];
1208
+ while (this.queue.length > 0 && this.queue[0].sender === first.sender)
1209
+ batch.push(this.queue.shift());
1210
+ const parts = batch.flatMap((t) => t.parts);
1211
+ const message = batch.length === 1 ? first.message : wechatUserMessage(parts);
1212
+ if (batch.length > 1)
1213
+ logger.info(`drainQueue: ${batch.length} messages from the same sender answered together`);
1214
+ this.typing.start(first.sender);
801
1215
  const started = Date.now();
802
1216
  try {
803
1217
  const agent = await this.ensureAgent();
1218
+ if (agent.status === "running" && this.currentSender !== undefined && this.currentSender !== first.sender) {
1219
+ // A turn for someone else (a reminder for the owner, another sender)
1220
+ // is running: let it finish rather than re-address its reply.
1221
+ logger.info(`drainQueue: waiting for the running turn to finish before answering ${first.sender}`);
1222
+ await agent.whenIdle();
1223
+ }
1224
+ this.currentSender = first.sender;
1225
+ this.turnMessageCount = 0; // 新回合重置发送计数
1226
+ this.chainTexts = batch.map((t) => t.text);
1227
+ this.toolCallsThisTurn = 0;
1228
+ this.restarts = 0;
1229
+ this.turnMessage = undefined;
804
1230
  if (agent.status === "running") {
805
1231
  // Mid-turn steer (unexpected via queue): inject into next-step so
806
1232
  // the running turn absorbs the message instead of starting a new one.
807
1233
  logger.info(`drainQueue: steering queued message into running turn`);
808
- agent.steer(task.message);
1234
+ agent.steer(message);
809
1235
  }
810
1236
  else {
811
- agent.followup(task.message);
1237
+ this.turnMessage = { id: message.id, parts, restarted: false };
1238
+ agent.followup(message);
812
1239
  }
1240
+ this.trackInbox({ sender: first.sender, text: batch.map((t) => t.text).join("\n"), message, parts });
813
1241
  await agent.whenIdle();
1242
+ this.turnMessage = undefined;
1243
+ this.requeueUnread(agent);
814
1244
  // Automatic memory fallback: capture durable user facts from this
815
1245
  // turn's message without relying on the model calling
816
1246
  // remember_user_info (which it often skips).
@@ -820,7 +1250,7 @@ export class WechatBridge {
820
1250
  // prompt assembly, so the NEXT user message already benefits. Doing
821
1251
  // it off the worker's tail keeps rapid consecutive messages from
822
1252
  // being delayed by file I/O or the LLM confirm call.
823
- const turnText = task.text;
1253
+ const turnTexts = [...this.chainTexts];
824
1254
  // Opt-in (see ClawbotConfig.autoMemory). Since 2026-09-22 the
825
1255
  // classifier goes through the host `llm` service on **this session's
826
1256
  // own route**, so it is no longer a second data destination — the text
@@ -828,7 +1258,7 @@ export class WechatBridge {
828
1258
  if (this.config.autoMemory) {
829
1259
  void Promise.resolve().then(async () => {
830
1260
  try {
831
- await captureTurnMemory([turnText], this.memoryJudge());
1261
+ await captureTurnMemory(turnTexts, this.memoryJudge());
832
1262
  }
833
1263
  catch (err) {
834
1264
  logger.warn(`memory-auto: capture failed: ${String(err)}`);
@@ -838,12 +1268,15 @@ export class WechatBridge {
838
1268
  logger.debug(`drainQueue: idle after ${Date.now() - started}ms`);
839
1269
  }
840
1270
  catch (err) {
841
- logger.error(`drainQueue: turn failed sender=${task.sender} err=${String(err)}`);
1271
+ logger.error(`drainQueue: turn failed sender=${first.sender} err=${String(err)}`);
1272
+ this.turnMessage = undefined;
842
1273
  }
843
1274
  // 后面还有排队的消息就接着显示,否则收起「正在输入」,开始等空闲压缩。
844
1275
  if (this.queue.length === 0) {
845
1276
  this.typing.stop();
846
1277
  this.idleCompact.noteIdle();
1278
+ // Answered: now what WeChat would not take before (after the reply on the chain).
1279
+ this.deliverBacklog(first.sender);
847
1280
  }
848
1281
  }
849
1282
  this.currentSender = undefined;
@@ -872,6 +1305,39 @@ export class WechatBridge {
872
1305
  }
873
1306
  // Real work after a reply (search, shell, files…): 「正在输入」 comes back now
874
1307
  // instead of after the quiet window. A reply tool is the answer itself.
1308
+ if (event.type === "turn/start") {
1309
+ this.answeredThisTurn = false;
1310
+ this.holdsThisTurn = 0;
1311
+ this.toolCallsThisTurn = 0;
1312
+ this.reminderDueAt = undefined;
1313
+ const turn = event.data?.turn;
1314
+ this.hostTurn = typeof turn === "number" ? turn : this.hostTurn + 1;
1315
+ this.hostStep = 0;
1316
+ }
1317
+ if (event.type === "step/start") {
1318
+ const step = event.data?.step;
1319
+ this.hostStep = typeof step === "number" ? step : this.hostStep + 1;
1320
+ }
1321
+ if (event.type === "tool/call")
1322
+ this.toolCallsThisTurn += 1;
1323
+ // The host takes a message out of the inbox before the step and writes it
1324
+ // into the history only when the step starts; until this event a restart
1325
+ // would cancel the turn and lose the message. Pinned to this turn and
1326
+ // step: a reminder the host runs next in the same driver is never cancelled.
1327
+ if (event.type === "user/message" && this.turnMessage !== undefined
1328
+ && event.data?.id === this.turnMessage.id) {
1329
+ this.turnMessage = { ...this.turnMessage, recordedAt: { turn: this.hostTurn, step: this.hostStep } };
1330
+ }
1331
+ if (event.type === "user/message") {
1332
+ const source = event.data?.source;
1333
+ if (source?.kind === "schedule" || source?.plugin === "schedule") {
1334
+ // What a refused reminder is stamped with: when it was due (even if it
1335
+ // fired late), not when the bot got round to it.
1336
+ const text = (event.data?.content ?? [])
1337
+ .map((b) => (b.type === "text" ? b.text ?? "" : "")).join("\n");
1338
+ this.reminderDueAt = occurrenceAt(text) ?? new Date().toISOString();
1339
+ }
1340
+ }
875
1341
  if (event.type === "tool/call" && this.currentSender) {
876
1342
  const name = event.data?.name;
877
1343
  if (typeof name === "string" && !REPLY_TOOLS.has(name))
@@ -882,6 +1348,10 @@ export class WechatBridge {
882
1348
  if (event.type === "turn/end" && !this.worker) {
883
1349
  this.typing.stop();
884
1350
  this.idleCompact.noteIdle();
1351
+ const senders = [...this.steeredIntoOtherTurn];
1352
+ this.steeredIntoOtherTurn.clear();
1353
+ if (senders.length > 0)
1354
+ this.afterOtherTurn(senders);
885
1355
  }
886
1356
  if (event.type === "user/message" && !this.worker) {
887
1357
  // v4 drops the `plugin` field: dsh-schedule now writes `{ kind: "schedule" }`