agent-loft 0.2.78 → 0.2.80
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 +7 -0
- package/package.json +1 -1
- package/src/agents/claude/driver.ts +1 -1
- package/src/channels/web/api.ts +60 -1
- package/src/channels/web/conv-pages.ts +2 -2
- package/src/channels/web/server.ts +12 -0
- package/src/channels/weixin/bot.ts +583 -0
- package/src/channels/weixin/client.ts +225 -0
- package/src/channels/weixin/events.ts +5 -0
- package/src/channels/weixin/format.ts +164 -0
- package/src/channels/weixin/index.ts +52 -0
- package/src/channels/weixin/login.ts +180 -0
- package/src/core/command-catalog.ts +8 -5
- package/src/core/commands.ts +4 -1
- package/src/core/personal.ts +3 -1
- package/src/core/weixin-accounts.ts +88 -0
- package/src/main.ts +3 -0
- package/src/mcp/memory-server.ts +1 -1
- package/web/css/composer.css +3 -2
- package/web/css/mobile.css +1 -1
- package/web/css/remote.css +0 -6
- package/web/css/sidebar.css +20 -27
- package/web/css/topbar.css +7 -0
- package/web/lib/dom.js +2 -0
- package/web/lib/keyboard.js +45 -0
- package/web/settings/security.js +2 -0
- package/web/settings/weixin.js +168 -0
- package/web/views/conv-search.js +1 -1
- package/web/views/layout.js +1 -0
- package/web/views/library.js +1 -1
- package/web/views/messages.js +15 -3
- package/web/views/remote.js +1 -25
- package/web/views/sidebar.js +10 -1
- package/web/views/todos.js +1 -1
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
// 一个微信绑定 = 一条长轮询 + 一条会话(weixin:<用户 id>)。
|
|
2
|
+
//
|
|
3
|
+
// 和飞书的差别都来自微信的限制,别按飞书的习惯改回去:
|
|
4
|
+
// - 消息发出去不能改,所以不发过程,只显示「正在输入」,一轮结束发一次结果;
|
|
5
|
+
// - 没有卡片,授权和提问都是一条文字,回复数字作答;同一时间只显示一个,免得数字答错对象;
|
|
6
|
+
// - 社区实测每条入站消息之后只能发约 10 条(见 Tencent/openclaw-weixin#202),超过就发不出去。
|
|
7
|
+
// 这里自己数着:长回复分段,发不完的等用户回「继续」,这条入站又会把额度补回来;
|
|
8
|
+
// - 大约 24 小时没收到用户消息后,微信会拒绝发送(ret=-2),所以微信不是可靠的提醒渠道。
|
|
9
|
+
// 发不出去、或者接口受理了却没给 message_id,都要在 Web 上说一声,并走系统推送。
|
|
10
|
+
import { config } from "../../core/config.js";
|
|
11
|
+
import { Dedup } from "../../core/dedup.js";
|
|
12
|
+
import { hub, type EventEnvelope } from "../../core/hub.js";
|
|
13
|
+
import { parseCommand } from "../../core/commands.js";
|
|
14
|
+
import { interactions, unansweredCount, type Interaction } from "../../core/interactions.js";
|
|
15
|
+
import { getConversation, sessionOwner } from "../../core/store.js";
|
|
16
|
+
import { getUser, isAdmin, ownedBy, type User } from "../../core/users.js";
|
|
17
|
+
import { patchWeixinAccount, weixinKey, type WeixinAccount } from "../../core/weixin-accounts.js";
|
|
18
|
+
import { IlinkClient, IlinkError, isTimeout, newClientId, SESSION_EXPIRED, type WeixinMessage } from "./client.js";
|
|
19
|
+
import {
|
|
20
|
+
approvalPrompt,
|
|
21
|
+
commandReplyText,
|
|
22
|
+
currentQuestion,
|
|
23
|
+
inboundText,
|
|
24
|
+
parseApproval,
|
|
25
|
+
parseQuestionAnswer,
|
|
26
|
+
questionPrompt,
|
|
27
|
+
splitText,
|
|
28
|
+
toWeixinText,
|
|
29
|
+
} from "./format.js";
|
|
30
|
+
import { weixinEvents } from "./events.js";
|
|
31
|
+
|
|
32
|
+
/** 每条入站消息之后能发的条数(社区实测,官方没有公布) */
|
|
33
|
+
export const SEND_LIMIT = 10;
|
|
34
|
+
/** 一次最多发几段回复。再长就等用户回「继续」,免得一条回复刷满屏 */
|
|
35
|
+
const MAX_CHUNKS_PER_ROUND = 3;
|
|
36
|
+
/** 额度低于这个数时不发提示类消息,留给回复和授权 */
|
|
37
|
+
const NOTICE_RESERVE = 3;
|
|
38
|
+
/** 授权请求刚换过时,这么短时间内收到的数字可能是在回答上一个,不认 */
|
|
39
|
+
const ANSWER_GRACE_MS = 2000;
|
|
40
|
+
const TYPING_KEEPALIVE_MS = 5000;
|
|
41
|
+
const TYPING_MAX_MS = 30 * 60_000;
|
|
42
|
+
const TICKET_TTL_MS = 12 * 3600_000;
|
|
43
|
+
/** Web 上「可能没送到」的提示隔多久才再说一次 */
|
|
44
|
+
const WARN_INTERVAL_MS = 10 * 60_000;
|
|
45
|
+
const EXPIRED_RETRY_MS = 3600_000;
|
|
46
|
+
const RETRY_DELAY_MS = 2000;
|
|
47
|
+
const BACKOFF_DELAY_MS = 30_000;
|
|
48
|
+
const MAX_CONSECUTIVE_FAILURES = 3;
|
|
49
|
+
const ORIGIN = { channel: "weixin", name: "微信" };
|
|
50
|
+
|
|
51
|
+
export type WeixinStatus = {
|
|
52
|
+
state: "connecting" | "connected" | "reconnecting" | "expired" | "stopped";
|
|
53
|
+
since: number;
|
|
54
|
+
error?: string;
|
|
55
|
+
/** 最近一次发送的结果。unconfirmed:接口受理了但没给 message_id,手机可能没收到 */
|
|
56
|
+
delivery?: "ok" | "unconfirmed" | "failed";
|
|
57
|
+
deliveryAt?: number;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export class WeixinBot {
|
|
61
|
+
readonly client: IlinkClient;
|
|
62
|
+
readonly key: string;
|
|
63
|
+
status: WeixinStatus = { state: "stopped", since: Date.now() };
|
|
64
|
+
private dedup = new Dedup();
|
|
65
|
+
private stop_ = new AbortController();
|
|
66
|
+
private offs: (() => void)[] = [];
|
|
67
|
+
/** 发送串行:回复、授权的先后不能乱 */
|
|
68
|
+
private sendChain: Promise<unknown> = Promise.resolve();
|
|
69
|
+
/** 入站串行:前一条还在处理(比如换专家)时,后一条不能抢在前面 */
|
|
70
|
+
private inboundChain: Promise<unknown> = Promise.resolve();
|
|
71
|
+
/** 最后一个说话的渠道:Web 上说的话,回复留在 Web,不花微信的额度 */
|
|
72
|
+
private lastOrigin: string | undefined;
|
|
73
|
+
/** 还没发出去的回复分段 */
|
|
74
|
+
private pendingChunks: string[] = [];
|
|
75
|
+
/** 微信上正显示着的授权 / 提问 */
|
|
76
|
+
private shown: { id: string; at: number; question: number } | undefined;
|
|
77
|
+
private typing: { ticket: string; timer: NodeJS.Timeout; deadline: number } | undefined;
|
|
78
|
+
private ticket: { value: string; at: number } | undefined;
|
|
79
|
+
/** 每种提示上次在 Web 上说的时间 */
|
|
80
|
+
private warned = new Map<string, number>();
|
|
81
|
+
/** 这一轮还要不要「正在输入」:等 ticket 的空当里这一轮可能已经结束了 */
|
|
82
|
+
private typingWanted = false;
|
|
83
|
+
/** 自己发的提示不再发回微信,否则发送失败时会循环 */
|
|
84
|
+
private ownNotice = false;
|
|
85
|
+
|
|
86
|
+
constructor(readonly account: WeixinAccount) {
|
|
87
|
+
this.client = new IlinkClient(account.baseUrl, account.botToken);
|
|
88
|
+
this.key = weixinKey(account.userId);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private get user(): User | undefined {
|
|
92
|
+
const user = getUser(this.account.userId);
|
|
93
|
+
return user && !user.disabled ? user : undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private get admin(): boolean {
|
|
97
|
+
return isAdmin(this.user);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private setStatus(state: WeixinStatus["state"], error?: string): void {
|
|
101
|
+
if (this.status.state === state && !error) return;
|
|
102
|
+
const { delivery, deliveryAt } = this.status;
|
|
103
|
+
this.status = { state, since: Date.now(), ...(error ? { error } : {}), ...(delivery ? { delivery } : {}), ...(deliveryAt ? { deliveryAt } : {}) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------- 生命周期 ----------
|
|
107
|
+
|
|
108
|
+
start(): void {
|
|
109
|
+
const onEvent = (env: EventEnvelope) => {
|
|
110
|
+
if (env.key === this.key) this.onHubEvent(env);
|
|
111
|
+
};
|
|
112
|
+
hub.on("event", onEvent);
|
|
113
|
+
this.offs.push(() => hub.off("event", onEvent));
|
|
114
|
+
|
|
115
|
+
const onCreated = (i: Interaction) => {
|
|
116
|
+
if (i.convKey === this.key) this.showNextPrompt();
|
|
117
|
+
};
|
|
118
|
+
const onUpdated = (i: Interaction) => {
|
|
119
|
+
if (i.id !== this.shown?.id) return;
|
|
120
|
+
const q = currentQuestion(i);
|
|
121
|
+
if (q >= 0 && q !== this.shown.question) this.showPrompt(i);
|
|
122
|
+
};
|
|
123
|
+
const onSettled = (i: Interaction) => {
|
|
124
|
+
if (i.convKey !== this.key || i.id !== this.shown?.id) return;
|
|
125
|
+
this.shown = undefined;
|
|
126
|
+
this.showNextPrompt();
|
|
127
|
+
if (!this.shown && hub.info(this.key)?.busy) void this.startTyping();
|
|
128
|
+
};
|
|
129
|
+
interactions.on("created", onCreated);
|
|
130
|
+
interactions.on("updated", onUpdated);
|
|
131
|
+
interactions.on("settled", onSettled);
|
|
132
|
+
this.offs.push(() => {
|
|
133
|
+
interactions.off("created", onCreated);
|
|
134
|
+
interactions.off("updated", onUpdated);
|
|
135
|
+
interactions.off("settled", onSettled);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
this.setStatus("connecting");
|
|
139
|
+
void this.client.notifyStart().catch((err) => console.warn(`${this.tag} notifystart 失败(不影响收发): ${errText(err)}`));
|
|
140
|
+
void this.pollLoop();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** silent:解绑后 token 不再有效,不用再告诉微信 */
|
|
144
|
+
stop(opts: { silent?: boolean } = {}): void {
|
|
145
|
+
this.stop_.abort();
|
|
146
|
+
for (const off of this.offs.splice(0)) off();
|
|
147
|
+
void this.stopTyping();
|
|
148
|
+
if (!opts.silent) void this.client.notifyStop().catch(() => {});
|
|
149
|
+
this.setStatus("stopped");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
private get tag(): string {
|
|
153
|
+
return `[微信:${this.account.userId}]`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------- 收消息 ----------
|
|
157
|
+
|
|
158
|
+
private async pollLoop(): Promise<void> {
|
|
159
|
+
const signal = this.stop_.signal;
|
|
160
|
+
let cursor = this.account.cursor;
|
|
161
|
+
let timeoutMs: number | undefined;
|
|
162
|
+
let failures = 0;
|
|
163
|
+
while (!signal.aborted) {
|
|
164
|
+
try {
|
|
165
|
+
const resp = await this.client.getUpdates(cursor, timeoutMs, signal);
|
|
166
|
+
if (resp.longpolling_timeout_ms && resp.longpolling_timeout_ms > 0) timeoutMs = resp.longpolling_timeout_ms;
|
|
167
|
+
if ((resp.ret !== undefined && resp.ret !== 0) || (resp.errcode !== undefined && resp.errcode !== 0)) {
|
|
168
|
+
if (resp.ret === SESSION_EXPIRED || resp.errcode === SESSION_EXPIRED) {
|
|
169
|
+
this.onSessionExpired();
|
|
170
|
+
failures = 0;
|
|
171
|
+
await this.sleep(EXPIRED_RETRY_MS);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
throw new IlinkError("getupdates", resp.ret, resp.errcode, resp.errmsg);
|
|
175
|
+
}
|
|
176
|
+
failures = 0;
|
|
177
|
+
this.setStatus("connected");
|
|
178
|
+
if (resp.get_updates_buf && resp.get_updates_buf !== cursor) {
|
|
179
|
+
cursor = resp.get_updates_buf;
|
|
180
|
+
this.account.cursor = cursor;
|
|
181
|
+
patchWeixinAccount(this.account.userId, { cursor });
|
|
182
|
+
}
|
|
183
|
+
for (const msg of resp.msgs ?? []) this.onInbound(msg);
|
|
184
|
+
} catch (err) {
|
|
185
|
+
if (signal.aborted) return;
|
|
186
|
+
// 长轮询超时是常态:这段时间没有新消息
|
|
187
|
+
if (isTimeout(err)) continue;
|
|
188
|
+
failures += 1;
|
|
189
|
+
this.setStatus("reconnecting", errText(err));
|
|
190
|
+
console.error(`${this.tag} 收消息失败(${failures}/${MAX_CONSECUTIVE_FAILURES}): ${errText(err)}`);
|
|
191
|
+
await this.sleep(failures >= MAX_CONSECUTIVE_FAILURES ? BACKOFF_DELAY_MS : RETRY_DELAY_MS);
|
|
192
|
+
if (failures >= MAX_CONSECUTIVE_FAILURES) failures = 0;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private sleep(ms: number): Promise<void> {
|
|
198
|
+
return new Promise((resolve) => {
|
|
199
|
+
const timer = setTimeout(resolve, ms);
|
|
200
|
+
timer.unref?.();
|
|
201
|
+
this.stop_.signal.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true });
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private onSessionExpired(): void {
|
|
206
|
+
if (this.status.state === "expired") return;
|
|
207
|
+
this.setStatus("expired", "微信登录已失效");
|
|
208
|
+
console.error(`${this.tag} 微信登录已失效,需要重新扫码`);
|
|
209
|
+
this.warnWeb("微信登录已失效,收不到微信消息了。请到「设置 → 账号 → 微信」重新扫码。", true);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private onInbound(msg: WeixinMessage): void {
|
|
213
|
+
// 只处理真人发的私聊。bot 自己的消息、群消息都不是给这条会话的
|
|
214
|
+
if (msg.message_type !== 1 || msg.group_id) return;
|
|
215
|
+
if (msg.from_user_id !== this.account.ilinkUserId) {
|
|
216
|
+
console.warn(`${this.tag} 忽略非绑定微信号发来的消息`);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (msg.message_id !== undefined && this.dedup.isDuplicate(String(msg.message_id))) return;
|
|
220
|
+
// 新的入站消息:令牌换新、额度补满。写在排队之前,紧接着的发送就能用上
|
|
221
|
+
if (msg.context_token) this.account.contextToken = msg.context_token;
|
|
222
|
+
this.account.lastInboundAt = Date.now();
|
|
223
|
+
this.account.sentSinceInbound = 0;
|
|
224
|
+
patchWeixinAccount(this.account.userId, {
|
|
225
|
+
...(msg.context_token ? { contextToken: msg.context_token } : {}),
|
|
226
|
+
lastInboundAt: this.account.lastInboundAt,
|
|
227
|
+
sentSinceInbound: 0,
|
|
228
|
+
});
|
|
229
|
+
this.inboundChain = this.inboundChain
|
|
230
|
+
.then(() => this.handleInbound(msg))
|
|
231
|
+
.catch((err) => {
|
|
232
|
+
console.error(`${this.tag} 处理消息失败:`, err);
|
|
233
|
+
this.say(`出错了:${errText(err)}`);
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** 专家:新会话选第一个能用的,手上的专家不能用了就换掉 */
|
|
238
|
+
private async ensureConversation(user: User): Promise<string[] | undefined> {
|
|
239
|
+
const allowed = hub.enabledAgents().map((d) => d.id);
|
|
240
|
+
const choices = hub.expertChoices(user.id, allowed);
|
|
241
|
+
if (choices.length === 0) return undefined;
|
|
242
|
+
const first = choices[0]!;
|
|
243
|
+
const existed = getConversation(this.key);
|
|
244
|
+
if (!existed) {
|
|
245
|
+
hub.ensure({
|
|
246
|
+
key: this.key,
|
|
247
|
+
channel: "weixin",
|
|
248
|
+
channelId: user.id,
|
|
249
|
+
defaultAgent: first.engine,
|
|
250
|
+
expert: first.id,
|
|
251
|
+
owner: user.id,
|
|
252
|
+
title: "微信",
|
|
253
|
+
});
|
|
254
|
+
} else if (!choices.some((e) => e.id === (existed.expert ?? existed.agent))) {
|
|
255
|
+
await hub.setExpert(this.key, first.id, allowed);
|
|
256
|
+
}
|
|
257
|
+
return allowed;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
private async handleInbound(msg: WeixinMessage): Promise<void> {
|
|
261
|
+
const user = this.user;
|
|
262
|
+
if (!user) return;
|
|
263
|
+
const { text, unsupported } = inboundText(msg);
|
|
264
|
+
if (unsupported) {
|
|
265
|
+
this.say("暂时只能处理文字和语音(语音要微信能转成文字)。图片、文件、视频请到网页上发。");
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (!text) return;
|
|
269
|
+
|
|
270
|
+
const allowed = await this.ensureConversation(user);
|
|
271
|
+
if (!allowed) {
|
|
272
|
+
this.say("你现在没有可用的专家。所选专家可能已取消共享、删除,或引擎已停用。");
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const command = parseCommand(text);
|
|
277
|
+
if (command.kind !== "chat") {
|
|
278
|
+
const reply = await hub.command(this.key, command, {
|
|
279
|
+
allowedAgents: allowed,
|
|
280
|
+
by: "微信命令",
|
|
281
|
+
channel: "weixin",
|
|
282
|
+
sessionVisible: (id) => ownedBy(user, sessionOwner(id)),
|
|
283
|
+
convVisible: (k) => ownedBy(user, getConversation(k)?.owner),
|
|
284
|
+
allowGlobalAlways: this.admin,
|
|
285
|
+
allowFullAccess: this.admin,
|
|
286
|
+
});
|
|
287
|
+
const shown = commandReplyText(reply, (a) => hub.label(a));
|
|
288
|
+
if (shown) this.reply(shown);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (this.answerPrompt(text)) return;
|
|
293
|
+
|
|
294
|
+
if (this.pendingChunks.length > 0 && text === "继续") {
|
|
295
|
+
this.enqueueSend(() => this.sendRound());
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// 回了别的话,上一条没看完的就不再接着发了(网页上有完整内容)
|
|
300
|
+
this.enqueueSend(async () => {
|
|
301
|
+
this.pendingChunks = [];
|
|
302
|
+
});
|
|
303
|
+
this.lastOrigin = ORIGIN.channel;
|
|
304
|
+
hub.send(this.key, { text, attachments: [] }, { ...ORIGIN, channelId: user.id });
|
|
305
|
+
void this.startTyping();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---------- 授权和提问 ----------
|
|
309
|
+
|
|
310
|
+
/** 看这条消息是不是在回答正显示的授权 / 提问。返回 true 表示用掉了,不再发给 agent */
|
|
311
|
+
private answerPrompt(text: string): boolean {
|
|
312
|
+
const shown = this.shown;
|
|
313
|
+
if (!shown) return false;
|
|
314
|
+
const i = interactions.get(shown.id);
|
|
315
|
+
if (!i || i.settled) {
|
|
316
|
+
this.shown = undefined;
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
const by = "已在微信处理";
|
|
320
|
+
const tooSoon = Date.now() - shown.at < ANSWER_GRACE_MS;
|
|
321
|
+
|
|
322
|
+
if (i.spec.kind === "approval") {
|
|
323
|
+
const decision = parseApproval(text, i, this.admin);
|
|
324
|
+
if (decision === undefined) {
|
|
325
|
+
this.say(`还有一个授权在等你:回复 1 允许一次,回复 0 拒绝。这条消息已排队,处理完授权才会发给 agent。`);
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
if (tooSoon) {
|
|
329
|
+
this.say("刚换了一个新的授权请求,请看清内容后再回复。");
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
interactions.decide(i.id, decision, by);
|
|
333
|
+
return true;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const answer = parseQuestionAnswer(text, i);
|
|
337
|
+
switch (answer.kind) {
|
|
338
|
+
case "skip":
|
|
339
|
+
interactions.skip(i.id, "已在微信跳过,agent 会按合理的默认继续");
|
|
340
|
+
return true;
|
|
341
|
+
case "invalid":
|
|
342
|
+
this.say("没有这个选项,请重新回复。");
|
|
343
|
+
return true;
|
|
344
|
+
case "text":
|
|
345
|
+
// 交给 hub.send:它会判断提问是否还属于当前会话,再当成自由作答
|
|
346
|
+
return false;
|
|
347
|
+
case "options": {
|
|
348
|
+
if (tooSoon) {
|
|
349
|
+
this.say("刚换了一个新的问题,请看清内容后再回复。");
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
const q = currentQuestion(i);
|
|
353
|
+
let settled = false;
|
|
354
|
+
for (const option of answer.options) {
|
|
355
|
+
settled = interactions.select(i.id, q, option, true, by)?.submitted ?? settled;
|
|
356
|
+
}
|
|
357
|
+
if (!settled) {
|
|
358
|
+
const latest = interactions.get(i.id);
|
|
359
|
+
// 多选题没有自动交卷:都答完了就替他提交
|
|
360
|
+
if (latest && !latest.settled && unansweredCount(latest) === 0) interactions.submit(i.id, by);
|
|
361
|
+
}
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Web 上发起的这一轮,Web 上有卡片,不打扰微信 */
|
|
368
|
+
private showNextPrompt(): void {
|
|
369
|
+
if (this.shown || this.lastOrigin === "web") return;
|
|
370
|
+
const next = interactions.listPending(this.key).sort((a, b) => a.createdAt - b.createdAt)[0];
|
|
371
|
+
if (next) this.showPrompt(next);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
private showPrompt(i: Interaction): void {
|
|
375
|
+
const shown = { id: i.id, at: Date.now(), question: currentQuestion(i) };
|
|
376
|
+
this.shown = shown;
|
|
377
|
+
void this.stopTyping();
|
|
378
|
+
const timeoutMin = Math.round(config().approvalTimeoutMs / 60_000);
|
|
379
|
+
this.enqueueSend(async () => {
|
|
380
|
+
const latest = interactions.get(i.id);
|
|
381
|
+
if (!latest || latest.settled) return;
|
|
382
|
+
const text =
|
|
383
|
+
latest.spec.kind === "approval"
|
|
384
|
+
? approvalPrompt(latest, this.admin, timeoutMin)
|
|
385
|
+
: questionPrompt(latest, hub.label(getConversation(this.key)?.agent ?? ""));
|
|
386
|
+
const sent = this.remaining() > 0 && (await this.sendOne(text));
|
|
387
|
+
// 真正发出去的时刻才开始算:之前收到的数字不可能是在回答这一个
|
|
388
|
+
shown.at = Date.now();
|
|
389
|
+
if (!sent) this.warnWeb("微信发不出这个授权 / 提问,请在这里处理。", true);
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ---------- 渲染 hub 事件 ----------
|
|
394
|
+
|
|
395
|
+
private onHubEvent({ ev }: EventEnvelope): void {
|
|
396
|
+
switch (ev.type) {
|
|
397
|
+
case "user":
|
|
398
|
+
this.lastOrigin = ev.origin.channel;
|
|
399
|
+
return;
|
|
400
|
+
case "result": {
|
|
401
|
+
void this.stopTyping();
|
|
402
|
+
if (ev.silent) return;
|
|
403
|
+
// Web 上说的话,回复留在 Web;定时任务的结果要发过来
|
|
404
|
+
if (this.lastOrigin === "web" && !ev.task) return;
|
|
405
|
+
const body = ev.task ? `⏰ ${ev.task.title}\n\n${ev.text}` : ev.text;
|
|
406
|
+
if (body.trim()) this.reply(body);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
case "error":
|
|
410
|
+
void this.stopTyping();
|
|
411
|
+
if (this.lastOrigin !== "web") this.say(ev.message);
|
|
412
|
+
return;
|
|
413
|
+
case "notice":
|
|
414
|
+
if (!this.ownNotice && this.lastOrigin !== "web") this.notice(ev.text);
|
|
415
|
+
return;
|
|
416
|
+
case "state":
|
|
417
|
+
if (!ev.busy) void this.stopTyping();
|
|
418
|
+
return;
|
|
419
|
+
default:
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// ---------- 发消息 ----------
|
|
425
|
+
|
|
426
|
+
private remaining(): number {
|
|
427
|
+
return SEND_LIMIT - this.account.sentSinceInbound;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** 一段完整的回复:太长就分段,发不完的留着等「继续」 */
|
|
431
|
+
private reply(markdown: string): void {
|
|
432
|
+
const chunks = splitText(toWeixinText(markdown));
|
|
433
|
+
// 改分段也排进发送队列:前一条回复可能还没发完,它不能把这条的分段也一起发了
|
|
434
|
+
this.enqueueSend(async () => {
|
|
435
|
+
this.pendingChunks = chunks;
|
|
436
|
+
await this.sendRound();
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** 发一轮分段。只在发送队列里调用 */
|
|
441
|
+
private async sendRound(): Promise<void> {
|
|
442
|
+
const rem = this.remaining();
|
|
443
|
+
if (this.pendingChunks.length > 0 && rem <= 0) {
|
|
444
|
+
this.warnWeb("微信这边的发送额度用完了,这条回复还没发过去,在这里能看到完整内容。在微信里回复「继续」就会接着发。", true);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const round = this.pendingChunks.splice(0, Math.min(MAX_CHUNKS_PER_ROUND, rem));
|
|
448
|
+
for (const [index, chunk] of round.entries()) {
|
|
449
|
+
const left = this.pendingChunks.length;
|
|
450
|
+
const tail = index === round.length - 1 && left > 0 ? `\n\n(还有 ${left} 段,回复「继续」查看,网页上有完整内容)` : "";
|
|
451
|
+
if (!(await this.sendOne(chunk + tail))) {
|
|
452
|
+
this.pendingChunks = [];
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** 一句话:错误、提示。不分段 */
|
|
459
|
+
private say(text: string): void {
|
|
460
|
+
this.enqueueSend(async () => {
|
|
461
|
+
if (this.remaining() > 0) await this.sendOne(splitText(toWeixinText(text))[0] ?? "");
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** 可有可无的提示:额度紧张时不发,留给回复和授权 */
|
|
466
|
+
private notice(text: string): void {
|
|
467
|
+
this.enqueueSend(async () => {
|
|
468
|
+
if (this.remaining() > NOTICE_RESERVE) await this.sendOne(splitText(toWeixinText(text))[0] ?? "");
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
private enqueueSend(task: () => Promise<void>): void {
|
|
473
|
+
this.sendChain = this.sendChain.then(task).catch((err) => console.error(`${this.tag} 发送失败:`, errText(err)));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** 发一条。返回 false 表示确定没发出去,后面的也不用发了 */
|
|
477
|
+
private async sendOne(text: string): Promise<boolean> {
|
|
478
|
+
if (!text.trim()) return true;
|
|
479
|
+
const contextToken = this.account.contextToken;
|
|
480
|
+
if (!contextToken) {
|
|
481
|
+
this.markDelivery("failed");
|
|
482
|
+
this.warnWeb("还没收到过你的微信消息,微信不允许先发。请先在微信里给 ClawBot 发一条消息。", true);
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
const clientId = newClientId();
|
|
486
|
+
const payload = { to: this.account.ilinkUserId, text, contextToken, clientId };
|
|
487
|
+
try {
|
|
488
|
+
let result;
|
|
489
|
+
try {
|
|
490
|
+
result = await this.client.sendText(payload);
|
|
491
|
+
} catch (err) {
|
|
492
|
+
if (err instanceof IlinkError) throw err;
|
|
493
|
+
// 网络问题重试一次。同一个 client_id,万一上次其实到了也不会重复显示
|
|
494
|
+
await this.sleep(RETRY_DELAY_MS);
|
|
495
|
+
result = await this.client.sendText(payload);
|
|
496
|
+
}
|
|
497
|
+
this.account.sentSinceInbound += 1;
|
|
498
|
+
patchWeixinAccount(this.account.userId, { sentSinceInbound: this.account.sentSinceInbound });
|
|
499
|
+
if (result.confirmed) {
|
|
500
|
+
this.markDelivery("ok");
|
|
501
|
+
} else {
|
|
502
|
+
this.markDelivery("unconfirmed");
|
|
503
|
+
this.warnWeb("微信接口受理了回复,但没有返回消息编号,手机可能没收到(微信可能在限制这个账号)。");
|
|
504
|
+
}
|
|
505
|
+
return true;
|
|
506
|
+
} catch (err) {
|
|
507
|
+
this.markDelivery("failed");
|
|
508
|
+
console.error(`${this.tag} 发送失败: ${errText(err)}`);
|
|
509
|
+
if (err instanceof IlinkError && err.sessionExpired) {
|
|
510
|
+
this.onSessionExpired();
|
|
511
|
+
} else if (err instanceof IlinkError && err.ret === -2) {
|
|
512
|
+
this.warnWeb(`微信拒绝发送这条消息(ret=-2)。${this.idleHint()}在微信里发一条消息就能恢复。`, true);
|
|
513
|
+
} else {
|
|
514
|
+
this.warnWeb(`微信发送失败:${errText(err)}`, true);
|
|
515
|
+
}
|
|
516
|
+
return false;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private idleHint(): string {
|
|
521
|
+
const at = this.account.lastInboundAt;
|
|
522
|
+
return at && Date.now() - at > 23 * 3600_000 ? "你已经超过一天没在微信里说话,微信不允许这时主动发消息。" : "";
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
private markDelivery(delivery: NonNullable<WeixinStatus["delivery"]>): void {
|
|
526
|
+
this.status = { ...this.status, delivery, deliveryAt: Date.now() };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** 在 Web 的这条对话里说一声,urgent 的同时走系统推送。隔一段时间才再说,免得刷屏 */
|
|
530
|
+
private warnWeb(text: string, urgent = false): void {
|
|
531
|
+
const now = Date.now();
|
|
532
|
+
if (now - (this.warned.get(text) ?? 0) < WARN_INTERVAL_MS) return;
|
|
533
|
+
this.warned.set(text, now);
|
|
534
|
+
this.ownNotice = true;
|
|
535
|
+
try {
|
|
536
|
+
if (getConversation(this.key)) hub.notice(this.key, text);
|
|
537
|
+
} finally {
|
|
538
|
+
this.ownNotice = false;
|
|
539
|
+
}
|
|
540
|
+
if (urgent) weixinEvents.emit("undelivered", { key: this.key, userId: this.account.userId, body: text });
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// ---------- 正在输入 ----------
|
|
544
|
+
|
|
545
|
+
private async startTyping(): Promise<void> {
|
|
546
|
+
const contextToken = this.account.contextToken;
|
|
547
|
+
this.typingWanted = true;
|
|
548
|
+
if (this.typing || !contextToken) return;
|
|
549
|
+
try {
|
|
550
|
+
if (!this.ticket || Date.now() - this.ticket.at > TICKET_TTL_MS) {
|
|
551
|
+
const value = await this.client.typingTicket(this.account.ilinkUserId, contextToken);
|
|
552
|
+
if (!value) return;
|
|
553
|
+
this.ticket = { value, at: Date.now() };
|
|
554
|
+
}
|
|
555
|
+
if (this.typing || !this.typingWanted) return;
|
|
556
|
+
const ticket = this.ticket.value;
|
|
557
|
+
const send = () => this.client.sendTyping(this.account.ilinkUserId, ticket, true).catch(() => {});
|
|
558
|
+
void send();
|
|
559
|
+
const deadline = Date.now() + TYPING_MAX_MS;
|
|
560
|
+
const timer = setInterval(() => {
|
|
561
|
+
if (Date.now() > deadline) void this.stopTyping();
|
|
562
|
+
else void send();
|
|
563
|
+
}, TYPING_KEEPALIVE_MS);
|
|
564
|
+
timer.unref?.();
|
|
565
|
+
this.typing = { ticket, timer, deadline };
|
|
566
|
+
} catch (err) {
|
|
567
|
+
console.warn(`${this.tag} 「正在输入」发送失败(不影响回复): ${errText(err)}`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
private async stopTyping(): Promise<void> {
|
|
572
|
+
this.typingWanted = false;
|
|
573
|
+
const typing = this.typing;
|
|
574
|
+
if (!typing) return;
|
|
575
|
+
this.typing = undefined;
|
|
576
|
+
clearInterval(typing.timer);
|
|
577
|
+
await this.client.sendTyping(this.account.ilinkUserId, typing.ticket, false).catch(() => {});
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function errText(err: unknown): string {
|
|
582
|
+
return err instanceof Error ? err.message : String(err);
|
|
583
|
+
}
|