返回 CodeWhale
lib.mjs
1 import crypto from "node:crypto";
2
3 import {
4 activeTurnBlock,
5 commandAction,
6 compactRuntimeError,
7 envFirst,
8 latestRunningTurn,
9 parseApprovalDecisionArgs,
10 parseBool,
11 parseCommand,
12 parseList,
13 preservedChatStateFields,
14 splitMessage,
15 } from "../../bridge-core/src/lib.mjs";
16
17 // ============================================================================
18 // iLink Bot API 协议层 — 参考 @tencent-weixin/openclaw-weixin
19 // ============================================================================
20
21 const DEFAULT_API_TIMEOUT_MS = 30_000;
22 const LONGPOLL_DEFAULT_TIMEOUT_MS = 35_000;
23
24 export {
25 activeTurnBlock,
26 commandAction,
27 compactRuntimeError,
28 envFirst,
29 latestRunningTurn,
30 parseApprovalDecisionArgs,
31 parseBool,
32 parseCommand,
33 parseList,
34 preservedChatStateFields,
35 splitMessage,
36 };
37
38 /**
39 * Handle one getUpdates batch, then advance the poll cursor. The cursor moves
40 * only after every message in the batch was handled, so a crash replays the
41 * batch from iLink instead of dropping a prompt. Each message is claimed
42 * durably first: on replay, finished messages are skipped, and one a crashed
43 * process was still handling is reported through `interrupted` rather than
44 * run twice (its effect is unknown).
45 */
46 export async function processUpdateBatch({ messages, nextCursor, store, keyOf, handle, interrupted, commitCursor }) {
47 for (const msg of messages || []) {
48 const key = keyOf(msg);
49 if (!key) continue;
50 await store.handleMessageOnce(key, () => handle(msg), () => interrupted(msg));
51 }
52 if (nextCursor) await commitCursor(nextCursor);
53 }
54
55 export function randomUin() {
56 const uint32 = crypto.randomBytes(4).readUInt32BE(0);
57 return Buffer.from(String(uint32), "utf-8").toString("base64");
58 }
59
60 // iLink-App-Id: 从 openclaw-weixin 的 package.json 已知为 "bot"
61 const ILINK_APP_ID = "bot";
62
63 // iLink-App-ClientVersion: 0x00MMNNPP (major<<16 | minor<<8 | patch)
64 function buildClientVersion(version) {
65 const [major = 0, minor = 0, patch = 0] = version.split(".").map(Number);
66 return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff);
67 }
68 const ILINK_APP_CLIENT_VERSION = String(buildClientVersion("2.4.4"));
69
70 // ---------------------------------------------------------------------------
71 // 消息提取
72 // ---------------------------------------------------------------------------
73
74 export const MessageItemType = {
75 NONE: 0,
76 TEXT: 1,
77 IMAGE: 2,
78 VOICE: 3,
79 FILE: 4,
80 VIDEO: 5,
81 TOOL_CALL_START: 11,
82 TOOL_CALL_RESULT: 12,
83 };
84
85 export function extractText(itemList) {
86 if (!Array.isArray(itemList) || !itemList.length) return "";
87 for (const item of itemList) {
88 if (!item) continue;
89 if (item.type === MessageItemType.TEXT && item.text_item?.text != null) {
90 const text = String(item.text_item.text);
91 if (text.trim()) return text;
92 }
93 if (item.type === MessageItemType.VOICE && item.voice_item?.text != null) {
94 const text = String(item.voice_item.text);
95 if (text.trim()) return text;
96 }
97 }
98 return "";
99 }
100
101 // ---------------------------------------------------------------------------
102 // 帮助文本
103 // ---------------------------------------------------------------------------
104
105 export function helpText() {
106 return [
107 "CodeWhale Weixin Bot 命令:",
108 "/help (/帮助) - 显示此帮助",
109 "/status (/状态) - 运行时和工作区状态,并重新发出待批准的批准码",
110 "/threads (/对话) - 最近运行时线程",
111 "/new (/新对话) - 为此聊天创建新线程",
112 "/resume <thread_id> - 绑定到已有线程",
113 "/model <name|default> - 设置或重置此聊天的模型",
114 "/stop (/interrupt, /停止) - 中断活跃 turn",
115 "/compact - 压缩当前线程",
116 "1 <批准码> / 2 <批准码> - 允许或拒绝工具调用",
117 "/allow <approval_id> [remember] - 批准工具调用",
118 "/deny <approval_id> - 拒绝工具调用",
119 "继续 - 查看剩余的回复",
120 "",
121 "其他所有内容均作为 CodeWhale 提示发送。",
122 ].join("\n");
123 }
124
125 const COMMAND_ALIASES = { 帮助: "help", 状态: "status", 对话: "threads", 新对话: "new", 停止: "interrupt", stop: "interrupt" };
126
127 export function parseWeixinCommand(text) {
128 const command = parseCommand(text);
129 const alias = COMMAND_ALIASES[command.name];
130 return alias ? { ...command, name: alias } : command;
131 }
132
133 const CONTINUE_REPLIES = new Set(["继续", "more", "continue"]);
134
135 export function isContinueReply(text) {
136 return CONTINUE_REPLIES.has(String(text || "").trim().toLowerCase());
137 }
138
139 const CODE_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz";
140 const APPROVAL_REPLY = /^(1|2|y|n|yes|no|允许|同意|拒绝)\s+([23456789a-hjkmnp-z]{6})$/u;
141 const ALLOW_WORDS = new Set(["1", "y", "yes", "允许", "同意"]);
142
143 export function mintCode(length = 6) {
144 return Array.from(crypto.randomBytes(length), (byte) => CODE_ALPHABET[byte % CODE_ALPHABET.length]).join("");
145 }
146
147 export function parseApprovalReply(text) {
148 const match = String(text || "").trim().toLowerCase().match(APPROVAL_REPLY);
149 if (!match) return null;
150 return { decision: ALLOW_WORDS.has(match[1]) ? "allow" : "deny", code: match[2] };
151 }
152
153 function clip(text, max) {
154 const value = String(text || "").trim();
155 return value.length > max ? `${value.slice(0, max - 1)}…` : value;
156 }
157
158 export function approvalText(approval, code) {
159 const what = [approval.tool_name, approval.intent_summary || approval.summary || approval.description].filter(Boolean).join(": ");
160 return [
161 "需要你的批准 / Approval needed",
162 clip(what, 400),
163 `回复 1 ${code} 允许,2 ${code} 拒绝`,
164 `Reply 1 ${code} to allow, 2 ${code} to deny`,
165 ].filter(Boolean).join("\n");
166 }
167
168 export { questionText, parseQuestionAnswers } from "../../bridge-core/src/lib.mjs";
169
170 export function isSessionExpired(response) {
171 return response?.ret === -14 || response?.errcode === -14;
172 }
173
174 // ============================================================================
175 // iLink Bot HTTP API 调用
176 // ============================================================================
177
178 export const ILinkLoginBase = "https://ilinkai.weixin.qq.com";
179
180 function authHeaders({ token } = {}) {
181 const headers = {
182 "Content-Type": "application/json",
183 AuthorizationType: "ilink_bot_token",
184 "X-WECHAT-UIN": randomUin(),
185 "iLink-App-Id": ILINK_APP_ID,
186 "iLink-App-ClientVersion": ILINK_APP_CLIENT_VERSION,
187 };
188 if (token) {
189 headers["Authorization"] = `Bearer ${token}`;
190 }
191 return headers;
192 }
193
194 /**
195 * 通用 POST 到 iLink API。
196 */
197 export async function apiPost({ baseUrl, endpoint, body, token, timeoutMs, signal }) {
198 signal?.throwIfAborted();
199 const url = `${baseUrl.replace(/\/+$/, "")}/${endpoint}`;
200 const ms = timeoutMs || DEFAULT_API_TIMEOUT_MS;
201 const controller = new AbortController();
202 const timer = setTimeout(() => controller.abort(), ms);
203 const onAbort = () => controller.abort(signal.reason);
204 signal?.addEventListener("abort", onAbort, { once: true });
205
206 try {
207 const response = await fetch(url, {
208 method: "POST",
209 headers: authHeaders({ token }),
210 body,
211 signal: controller.signal,
212 });
213 const text = await response.text();
214 if (!response.ok) {
215 throw new Error(
216 `iLink API ${endpoint} failed: HTTP ${response.status}`
217 );
218 }
219 return text;
220 } finally {
221 clearTimeout(timer);
222 signal?.removeEventListener("abort", onAbort);
223 }
224 }
225
226 /**
227 * 通用 GET 到 iLink API(用于轮询扫码状态等)。
228 */
229 export async function apiGet({ baseUrl, endpoint, token, timeoutMs, signal }) {
230 const url = `${baseUrl.replace(/\/+$/, "")}/${endpoint}`;
231 const ms = timeoutMs || DEFAULT_API_TIMEOUT_MS;
232 const controller = new AbortController();
233 const timer = setTimeout(() => controller.abort(), ms);
234 signal?.addEventListener("abort", () => controller.abort(), { once: true });
235
236 try {
237 const response = await fetch(url, {
238 method: "GET",
239 headers: authHeaders({ token }),
240 signal: controller.signal,
241 });
242 const text = await response.text();
243 if (!response.ok) {
244 // 长轮询超时是正常的,不抛错
245 if (response.status === 524 || text.includes("timeout")) {
246 return text;
247 }
248 throw new Error(
249 `iLink API ${endpoint} failed: HTTP ${response.status} — ${text.slice(0, 200)}`
250 );
251 }
252 return text;
253 } finally {
254 clearTimeout(timer);
255 }
256 }
257
258 // ============================================================================
259 // 扫码登录
260 // ============================================================================
261
262 /**
263 * 获取登录二维码。
264 * 参考 login-qr.ts:79-90 — 端点 get_bot_qrcode,bot_type 是 query 参数。
265 * @returns {Promise<{qrcode: string, qrcodeUrl: string, sessionKey: string}>}
266 */
267 export async function getLoginQR({ botType = "3" } = {}) {
268 const raw = await apiPost({
269 baseUrl: ILinkLoginBase,
270 endpoint: `ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(botType)}`,
271 body: JSON.stringify({ local_token_list: [] }),
272 });
273 const data = JSON.parse(raw);
274 const qrcodeUrl = data.qrcode_img_content || "";
275 const sessionKey = data.qrcode || crypto.randomUUID();
276 return { qrcode: data.qrcode, qrcodeUrl, sessionKey };
277 }
278
279 /**
280 * 轮询扫码状态直到确认或超时。
281 * 参考 login-qr.ts:112-136 — 端点 get_qrcode_status,GET 方法。
282 * @returns {Promise<{connected: boolean, botToken?: string, accountId?: string, baseUrl?: string, userId?: string, message: string}>}
283 */
284 export async function waitForLogin({ sessionKey, timeoutMs = 300_000 } = {}) {
285 const deadline = Date.now() + timeoutMs;
286
287 while (Date.now() < deadline) {
288 let raw;
289 try {
290 raw = await apiGet({
291 baseUrl: ILinkLoginBase,
292 endpoint: `ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(sessionKey)}`,
293 timeoutMs: 35_000, // 长轮询超时
294 });
295 } catch {
296 // 超时等网络错误 → 视为 wait,继续轮询
297 await new Promise((r) => setTimeout(r, 1000));
298 continue;
299 }
300
301 const data = JSON.parse(raw);
302 const status = data.status;
303
304 if (status === "confirmed") {
305 return {
306 connected: true,
307 botToken: data.bot_token,
308 accountId: data.ilink_bot_id,
309 baseUrl: data.baseurl || ILinkLoginBase,
310 userId: data.ilink_user_id,
311 message: "已连接微信。",
312 };
313 }
314
315 if (status === "expired" || status === "binded_redirect") {
316 return { connected: false, message: status === "expired" ? "二维码已过期,请重试。" : "已连接过此桥接,无需重复连接。" };
317 }
318
319 // 等 1 秒再轮询
320 await new Promise((r) => setTimeout(r, 1000));
321 }
322
323 return { connected: false, message: "登录超时,请重试。" };
324 }
325
326 // ============================================================================
327 // 消息 API
328 // ============================================================================
329
330 /**
331 * 长轮询获取新消息。
332 */
333 export async function getUpdates({ baseUrl, token, get_updates_buf = "", timeoutMs = LONGPOLL_DEFAULT_TIMEOUT_MS, signal }) {
334 const raw = await apiPost({
335 baseUrl,
336 endpoint: "ilink/bot/getupdates",
337 body: JSON.stringify({
338 get_updates_buf,
339 base_info: { bot_agent: "CodeWhale/1.0" },
340 }),
341 token,
342 timeoutMs,
343 signal,
344 });
345 return JSON.parse(raw);
346 }
347
348 /**
349 * Send a message and return the parsed API acceptance response, not a recipient
350 * delivery receipt. Tencent's reference allows omitted status fields; explicit
351 * statuses must be numeric zero. Ambiguous failures must not be retried as if
352 * the provider had rejected the message.
353 */
354 export async function sendMessage({ baseUrl, token, body, timeoutMs }) {
355 let raw;
356 try {
357 raw = await apiPost({
358 baseUrl,
359 endpoint: "ilink/bot/sendmessage",
360 body: JSON.stringify({
361 ...body,
362 base_info: { bot_agent: "CodeWhale/1.0" },
363 }),
364 token,
365 timeoutMs,
366 });
367 } catch (error) {
368 const failure = error instanceof Error ? error : new Error("iLink sendMessage transport failed");
369 failure.deliveryStatus = "uncertain";
370 throw failure;
371 }
372
373 let response;
374 try {
375 response = JSON.parse(raw);
376 } catch {
377 throw Object.assign(new Error("iLink sendMessage returned invalid JSON"), { deliveryStatus: "uncertain" });
378 }
379 if (!response || typeof response !== "object" || Array.isArray(response)) {
380 throw Object.assign(new Error("iLink sendMessage returned a non-object response"), { deliveryStatus: "uncertain" });
381 }
382 const statusFields = ["ret", "errcode"].filter((field) => Object.hasOwn(response, field));
383 if (statusFields.some((field) => !Number.isFinite(response[field]))) {
384 throw Object.assign(new Error("iLink sendMessage returned an invalid status"), { deliveryStatus: "uncertain" });
385 }
386 const failure = statusFields.find((field) => response[field] !== 0);
387 if (failure) {
388 throw Object.assign(new Error(`iLink sendMessage rejected: ${failure}=${response[failure]}`), {
389 deliveryStatus: "rejected",
390 sessionExpired: isSessionExpired(response),
391 rateLimited: typeof response.errmsg === "string" && /rate.?limit/i.test(response.errmsg),
392 });
393 }
394 return response;
395 }
396
397 /**
398 * 发送/取消输入状态。
399 */
400 export async function sendTyping({ baseUrl, token, ilinkUserId, typingTicket, status = 1 }) {
401 await apiPost({
402 baseUrl,
403 endpoint: "ilink/bot/sendtyping",
404 body: JSON.stringify({
405 ilink_user_id: ilinkUserId,
406 typing_ticket: typingTicket,
407 status,
408 base_info: { bot_agent: "CodeWhale/1.0" },
409 }),
410 token,
411 timeoutMs: 10_000,
412 });
413 }
414
415 /**
416 * 获取账号配置(含 typing_ticket)。
417 */
418 export async function getConfig({ baseUrl, token, ilinkUserId, contextToken }) {
419 const raw = await apiPost({
420 baseUrl,
421 endpoint: "ilink/bot/getconfig",
422 body: JSON.stringify({
423 ilink_user_id: ilinkUserId,
424 context_token: contextToken,
425 base_info: { bot_agent: "CodeWhale/1.0" },
426 }),
427 token,
428 timeoutMs: 10_000,
429 });
430 return JSON.parse(raw);
431 }
432
433 /**
434 * 通知上线。
435 */
436 export async function notifyStart({ baseUrl, token }) {
437 const raw = await apiPost({
438 baseUrl,
439 endpoint: "ilink/bot/msg/notifystart",
440 body: JSON.stringify({ base_info: { bot_agent: "CodeWhale/1.0" } }),
441 token,
442 });
443 return JSON.parse(raw);
444 }
445
446 /**
447 * 通知下线。
448 */
449 export async function notifyStop({ baseUrl, token }) {
450 const raw = await apiPost({
451 baseUrl,
452 endpoint: "ilink/bot/msg/notifystop",
453 body: JSON.stringify({ base_info: { bot_agent: "CodeWhale/1.0" } }),
454 token,
455 });
456 return JSON.parse(raw);
457 }
458
458 lines Plain Text