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