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.
@@ -0,0 +1,225 @@
1
+ // 微信 iLink Bot 协议的薄客户端。协议见腾讯的 docs/protocol.md:
2
+ // https://github.com/Tencent/openclaw-weixin/blob/main/docs/protocol.md
3
+ //
4
+ // 几条和普通 HTTP 接口不一样的地方:
5
+ // - HTTP 200 不代表成功,业务结果看 ret / errcode;
6
+ // - sendmessage 返回 ret=0 也只表示「接口受理了」,不保证手机收到。微信可能静默限制账号或消息,
7
+ // 这时通常没有 message_id(见 Tencent/openclaw-weixin#278、#280);
8
+ // - message_id 是 uint64,超过 JS 安全整数,要在 JSON.parse 之前转成字符串。
9
+ import crypto from "node:crypto";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ export const DEFAULT_ILINK_BASE_URL = process.env.AGENT_LOFT_ILINK_BASE_URL || "https://ilinkai.weixin.qq.com";
15
+
16
+ /** 对齐的官方插件协议版本。服务端可能按它判断能力,所以这里写协议版本,不写 agent-loft 自己的版本 */
17
+ const PROTOCOL_VERSION = "2.4.10";
18
+ const ILINK_APP_ID = "bot";
19
+ const BOT_TYPE = "3";
20
+
21
+ const LONG_POLL_TIMEOUT_MS = 35_000;
22
+ const API_TIMEOUT_MS = 15_000;
23
+ const LIGHT_TIMEOUT_MS = 10_000;
24
+
25
+ /** 会话已失效(bot_token 不能用了),要重新扫码 */
26
+ export const SESSION_EXPIRED = -14;
27
+
28
+ function clientVersion(version: string): number {
29
+ const [major = 0, minor = 0, patch = 0] = version.split(".").map((p) => parseInt(p, 10));
30
+ return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff);
31
+ }
32
+
33
+ function loftVersion(): string {
34
+ try {
35
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
36
+ return (JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")) as { version?: string }).version ?? "0";
37
+ } catch {
38
+ return "0";
39
+ }
40
+ }
41
+
42
+ const baseInfo = { channel_version: PROTOCOL_VERSION, bot_agent: `agent-loft/${loftVersion()}` };
43
+
44
+ function commonHeaders(): Record<string, string> {
45
+ return { "iLink-App-Id": ILINK_APP_ID, "iLink-App-ClientVersion": String(clientVersion(PROTOCOL_VERSION)) };
46
+ }
47
+
48
+ function jsonHeaders(token?: string): Record<string, string> {
49
+ const uin = crypto.randomBytes(4).readUInt32BE(0);
50
+ return {
51
+ "Content-Type": "application/json",
52
+ AuthorizationType: "ilink_bot_token",
53
+ "X-WECHAT-UIN": Buffer.from(String(uin), "utf8").toString("base64"),
54
+ ...commonHeaders(),
55
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
56
+ };
57
+ }
58
+
59
+ /** 业务层失败:HTTP 通了,但 ret / errcode 不是 0 */
60
+ export class IlinkError extends Error {
61
+ constructor(
62
+ readonly endpoint: string,
63
+ readonly ret: number | undefined,
64
+ readonly errcode: number | undefined,
65
+ readonly errmsg: string | undefined,
66
+ ) {
67
+ super(`${endpoint} ret=${ret ?? "-"} errcode=${errcode ?? "-"} ${errmsg ?? ""}`.trim());
68
+ this.name = "IlinkError";
69
+ }
70
+
71
+ get sessionExpired(): boolean {
72
+ return this.ret === SESSION_EXPIRED || this.errcode === SESSION_EXPIRED;
73
+ }
74
+ }
75
+
76
+ /** 把 uint64 的消息编号转成字符串再解析。JSON 字符串里的引号都带转义,这个正则碰不到正文 */
77
+ export function parseIlinkJson<T>(raw: string): T {
78
+ const text = raw.trim();
79
+ if (!text) return {} as T;
80
+ return JSON.parse(text.replace(/"(message_id|msg_id|svr_id)"(\s*:\s*)(\d+)/g, '"$1"$2"$3"')) as T;
81
+ }
82
+
83
+ function endpointUrl(baseUrl: string, endpoint: string): string {
84
+ return new URL(endpoint, baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`).toString();
85
+ }
86
+
87
+ async function request<T>(url: string, init: RequestInit, label: string, timeoutMs: number, signal?: AbortSignal): Promise<T> {
88
+ const timeout = AbortSignal.timeout(timeoutMs);
89
+ const res = await fetch(url, { ...init, signal: signal ? AbortSignal.any([timeout, signal]) : timeout });
90
+ const raw = await res.text();
91
+ if (!res.ok) throw new Error(`${label} HTTP ${res.status}`);
92
+ return parseIlinkJson<T>(raw);
93
+ }
94
+
95
+ export type WeixinMessageItem = {
96
+ type?: number;
97
+ text_item?: { text?: string };
98
+ voice_item?: { text?: string };
99
+ };
100
+
101
+ export type WeixinMessage = {
102
+ message_id?: string | number;
103
+ from_user_id?: string;
104
+ to_user_id?: string;
105
+ group_id?: string;
106
+ message_type?: number;
107
+ item_list?: WeixinMessageItem[];
108
+ context_token?: string;
109
+ };
110
+
111
+ type BaseResp = { ret?: number; errcode?: number; errmsg?: string };
112
+ export type GetUpdatesResp = BaseResp & { msgs?: WeixinMessage[]; get_updates_buf?: string; longpolling_timeout_ms?: number };
113
+ type SendResp = BaseResp & { message_id?: string };
114
+ type ConfigResp = BaseResp & { typing_ticket?: string };
115
+
116
+ export const isTimeout = (err: unknown): boolean => err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
117
+
118
+ export class IlinkClient {
119
+ constructor(
120
+ readonly baseUrl: string,
121
+ private readonly token: string,
122
+ ) {}
123
+
124
+ private post<T>(endpoint: string, body: object, label: string, timeoutMs: number, signal?: AbortSignal): Promise<T> {
125
+ return request<T>(
126
+ endpointUrl(this.baseUrl, `ilink/bot/${endpoint}`),
127
+ { method: "POST", headers: jsonHeaders(this.token), body: JSON.stringify({ ...body, base_info: baseInfo }) },
128
+ label,
129
+ timeoutMs,
130
+ signal,
131
+ );
132
+ }
133
+
134
+ /** 长轮询。业务错误原样返回,由轮询循环决定退避还是暂停 */
135
+ getUpdates(buf: string, timeoutMs = LONG_POLL_TIMEOUT_MS, signal?: AbortSignal): Promise<GetUpdatesResp> {
136
+ return this.post<GetUpdatesResp>("getupdates", { get_updates_buf: buf }, "getupdates", timeoutMs, signal);
137
+ }
138
+
139
+ /** 发一条文字。ret 不是 0 时抛 IlinkError。confirmed=false:接口受理了但没给 message_id,可能没送到 */
140
+ async sendText(params: { to: string; text: string; contextToken: string; clientId: string }): Promise<{ confirmed: boolean; messageId?: string }> {
141
+ const resp = await this.post<SendResp>(
142
+ "sendmessage",
143
+ {
144
+ msg: {
145
+ from_user_id: "",
146
+ to_user_id: params.to,
147
+ client_id: params.clientId,
148
+ message_type: 2,
149
+ message_state: 2,
150
+ context_token: params.contextToken,
151
+ item_list: [{ type: 1, text_item: { text: params.text } }],
152
+ },
153
+ },
154
+ "sendmessage",
155
+ API_TIMEOUT_MS,
156
+ );
157
+ if ((resp.ret !== undefined && resp.ret !== 0) || (resp.errcode !== undefined && resp.errcode !== 0)) {
158
+ throw new IlinkError("sendmessage", resp.ret, resp.errcode, resp.errmsg);
159
+ }
160
+ return resp.message_id ? { confirmed: true, messageId: String(resp.message_id) } : { confirmed: false };
161
+ }
162
+
163
+ async typingTicket(userId: string, contextToken: string): Promise<string | undefined> {
164
+ const resp = await this.post<ConfigResp>("getconfig", { ilink_user_id: userId, context_token: contextToken }, "getconfig", LIGHT_TIMEOUT_MS);
165
+ return resp.ret === 0 || resp.ret === undefined ? resp.typing_ticket || undefined : undefined;
166
+ }
167
+
168
+ async sendTyping(userId: string, ticket: string, typing: boolean): Promise<void> {
169
+ await this.post("sendtyping", { ilink_user_id: userId, typing_ticket: ticket, status: typing ? 1 : 2 }, "sendtyping", LIGHT_TIMEOUT_MS);
170
+ }
171
+
172
+ async notifyStart(): Promise<void> {
173
+ await this.post("msg/notifystart", {}, "notifystart", LIGHT_TIMEOUT_MS);
174
+ }
175
+
176
+ async notifyStop(): Promise<void> {
177
+ await this.post("msg/notifystop", {}, "notifystop", LIGHT_TIMEOUT_MS);
178
+ }
179
+ }
180
+
181
+ export function newClientId(): string {
182
+ return `agent-loft:${Date.now()}-${crypto.randomBytes(4).toString("hex")}`;
183
+ }
184
+
185
+ // ---------- 扫码登录 ----------
186
+
187
+ export type QrCode = { qrcode: string; qrcodeUrl: string };
188
+
189
+ export type QrStatus = {
190
+ status: "wait" | "scaned" | "confirmed" | "expired" | "scaned_but_redirect" | "need_verifycode" | "verify_code_blocked" | "binded_redirect";
191
+ bot_token?: string;
192
+ ilink_bot_id?: string;
193
+ baseurl?: string;
194
+ ilink_user_id?: string;
195
+ redirect_host?: string;
196
+ };
197
+
198
+ /** localTokens:这个用户手上已有的 bot token,服务端据此判断是不是重复绑定 */
199
+ export async function fetchQrCode(localTokens: string[], baseUrl = DEFAULT_ILINK_BASE_URL): Promise<QrCode> {
200
+ const resp = await request<{ qrcode?: string; qrcode_img_content?: string }>(
201
+ endpointUrl(baseUrl, `ilink/bot/get_bot_qrcode?bot_type=${BOT_TYPE}`),
202
+ { method: "POST", headers: jsonHeaders(), body: JSON.stringify({ local_token_list: localTokens.slice(0, 10) }) },
203
+ "get_bot_qrcode",
204
+ API_TIMEOUT_MS,
205
+ );
206
+ if (!resp.qrcode || !resp.qrcode_img_content) throw new Error("微信没有返回二维码");
207
+ return { qrcode: resp.qrcode, qrcodeUrl: resp.qrcode_img_content };
208
+ }
209
+
210
+ /** 长轮询扫码状态。超时和网络错误都当作还在等:手机上的操作不会因为这边断一下就没了 */
211
+ export async function pollQrStatus(baseUrl: string, qrcode: string, verifyCode?: string, signal?: AbortSignal): Promise<QrStatus> {
212
+ const query = `qrcode=${encodeURIComponent(qrcode)}${verifyCode ? `&verify_code=${encodeURIComponent(verifyCode)}` : ""}`;
213
+ try {
214
+ return await request<QrStatus>(
215
+ endpointUrl(baseUrl, `ilink/bot/get_qrcode_status?${query}`),
216
+ { method: "GET", headers: commonHeaders() },
217
+ "get_qrcode_status",
218
+ LONG_POLL_TIMEOUT_MS,
219
+ signal,
220
+ );
221
+ } catch (err) {
222
+ if (signal?.aborted) throw err;
223
+ return { status: "wait" };
224
+ }
225
+ }
@@ -0,0 +1,5 @@
1
+ // 微信渠道发给 Web 的事件。单独一个文件:Web 只想听事件时不用把轮询和发送都带上。
2
+ import { EventEmitter } from "node:events";
3
+
4
+ /** undelivered:微信发不出去的提醒,改走系统推送 */
5
+ export const weixinEvents = new EventEmitter<{ undelivered: [{ key: string; userId: string; body: string }] }>();
@@ -0,0 +1,164 @@
1
+ // 微信这边只有文字:把回复、授权请求、提问和命令结果都画成纯文本,把数字回复解析回来。
2
+ import { albumsToText } from "../../core/albums.js";
3
+ import { chartsToTables } from "../../core/charts.js";
4
+ import type { CommandReply } from "../../core/hub.js";
5
+ import type { Interaction } from "../../core/interactions.js";
6
+ import type { ApprovalDecision } from "../../core/types.js";
7
+ import type { WeixinMessage } from "./client.js";
8
+
9
+ /** 官方插件的单条上限是 4000。留点余量,分段提示接在最后一段后面 */
10
+ export const CHUNK_LIMIT = 3800;
11
+
12
+ const ITEM_TEXT = 1;
13
+ const ITEM_VOICE = 3;
14
+
15
+ /** 入站消息里的文字:文字项,或者微信给语音转好的文字。其它类型 unsupported=true */
16
+ export function inboundText(msg: WeixinMessage): { text: string; unsupported: boolean } {
17
+ const items = msg.item_list ?? [];
18
+ for (const item of items) {
19
+ if (item.type === ITEM_TEXT && item.text_item?.text != null) return { text: String(item.text_item.text).trim(), unsupported: false };
20
+ if (item.type === ITEM_VOICE && item.voice_item?.text) return { text: String(item.voice_item.text).trim(), unsupported: false };
21
+ }
22
+ return { text: "", unsupported: items.length > 0 };
23
+ }
24
+
25
+ /** 回复正文:图表换成表格、相册换成摘要;微信发不了 Markdown 图片,只留说明文字 */
26
+ export function toWeixinText(markdown: string): string {
27
+ return chartsToTables(albumsToText(markdown))
28
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, (_all, alt: string) => (alt ? `[图片:${alt}]` : "[图片]"))
29
+ .trim();
30
+ }
31
+
32
+ /** 按行切成不超过 limit 的段;单行太长就硬切,但不切开 emoji 这种代理对 */
33
+ export function splitText(text: string, limit = CHUNK_LIMIT): string[] {
34
+ const chunks: string[] = [];
35
+ let rest = text;
36
+ while (rest.length > limit) {
37
+ let at = rest.lastIndexOf("\n", limit);
38
+ if (at < limit / 2) {
39
+ at = limit;
40
+ const code = rest.charCodeAt(at - 1);
41
+ if (code >= 0xd800 && code <= 0xdbff) at -= 1;
42
+ }
43
+ chunks.push(rest.slice(0, at).trimEnd());
44
+ rest = rest.slice(at).replace(/^\n+/, "");
45
+ }
46
+ if (rest.trim()) chunks.push(rest);
47
+ return chunks;
48
+ }
49
+
50
+ const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
51
+
52
+ // ---------- 授权 ----------
53
+ //
54
+ // 数字的含义固定,不按显示的项目重新编号:1 永远是允许一次、0 永远是拒绝,手滑也不会点到别的权限上。
55
+
56
+ export function canAlways(spec: Extract<Interaction["spec"], { kind: "approval" }>, isAdmin: boolean): boolean {
57
+ return !!spec.alwaysLabel && (!spec.alwaysGlobal || isAdmin);
58
+ }
59
+
60
+ export function approvalPrompt(i: Interaction, isAdmin: boolean, timeoutMin: number): string {
61
+ const spec = i.spec;
62
+ if (spec.kind !== "approval") throw new Error("不是审批");
63
+ return [
64
+ `🔐 ${spec.title}`,
65
+ "",
66
+ clip(spec.detail, 2500),
67
+ "",
68
+ "回复数字:",
69
+ "1 允许一次",
70
+ ...(spec.allowSession ? ["2 本会话全部允许"] : []),
71
+ ...(canAlways(spec, isAdmin) ? [`3 ${spec.alwaysLabel}`] : []),
72
+ "0 拒绝",
73
+ "",
74
+ `网页上也能处理。${timeoutMin} 分钟没回应按拒绝。`,
75
+ ].join("\n");
76
+ }
77
+
78
+ /** 解析授权回复。undefined:这条消息不是在回答授权 */
79
+ export function parseApproval(text: string, i: Interaction, isAdmin: boolean): ApprovalDecision | undefined {
80
+ const spec = i.spec;
81
+ if (spec.kind !== "approval") return undefined;
82
+ const t = text.trim();
83
+ if (t === "1" || t === "允许") return "allow-once";
84
+ if (t === "0" || t === "拒绝") return "deny";
85
+ if (t === "2" && spec.allowSession) return "allow-session";
86
+ if (t === "3" && canAlways(spec, isAdmin)) return "allow-always";
87
+ return undefined;
88
+ }
89
+
90
+ // ---------- 提问 ----------
91
+
92
+ /** 第一个还没答的问题的下标,都答了就是 -1 */
93
+ export function currentQuestion(i: Interaction): number {
94
+ return i.selections.findIndex((picked, q) => picked.length === 0 && !i.freeText[q]);
95
+ }
96
+
97
+ export function questionPrompt(i: Interaction, agentLabel: string): string {
98
+ const spec = i.spec;
99
+ if (spec.kind !== "question") throw new Error("不是提问");
100
+ const qi = Math.max(0, currentQuestion(i));
101
+ const q = spec.questions[qi]!;
102
+ const lines = [`❓ ${spec.title || `${agentLabel} 想确认一下`}${spec.questions.length > 1 ? `(第 ${qi + 1}/${spec.questions.length} 问)` : ""}`, ""];
103
+ lines.push([q.header, q.question].filter(Boolean).join(":"));
104
+ if (q.options.length > 0) {
105
+ lines.push("");
106
+ q.options.forEach((opt, oi) => lines.push(`${oi + 1} ${clip(opt.label, 80)}${opt.description ? ` —— ${clip(opt.description, 120)}` : ""}`));
107
+ lines.push("", q.multiSelect ? "回复数字,多选用空格隔开。" : "回复数字。", "都不合适就直接回复文字。回复「跳过」让 agent 按默认继续。");
108
+ } else {
109
+ lines.push("", "直接回复文字。回复「跳过」让 agent 按默认继续。");
110
+ }
111
+ return lines.join("\n");
112
+ }
113
+
114
+ export type QuestionAnswer =
115
+ | { kind: "skip" }
116
+ /** 选项下标(从 0 开始) */
117
+ | { kind: "options"; options: number[] }
118
+ /** 是数字,但没有这个选项 */
119
+ | { kind: "invalid" }
120
+ /** 不是选项,当成自由作答 */
121
+ | { kind: "text" };
122
+
123
+ export function parseQuestionAnswer(text: string, i: Interaction): QuestionAnswer {
124
+ const spec = i.spec;
125
+ if (spec.kind !== "question") return { kind: "text" };
126
+ const t = text.trim();
127
+ if (t === "跳过") return { kind: "skip" };
128
+ const q = spec.questions[Math.max(0, currentQuestion(i))];
129
+ if (!q || q.options.length === 0) return { kind: "text" };
130
+ const tokens = t.split(/[\s,,、]+/).filter(Boolean);
131
+ if (tokens.length === 0 || !tokens.every((s) => /^\d{1,3}$/.test(s))) return { kind: "text" };
132
+ if (!q.multiSelect && tokens.length > 1) return { kind: "invalid" };
133
+ const options = [...new Set(tokens.map((s) => Number(s) - 1))];
134
+ return options.every((o) => o >= 0 && o < q.options.length) ? { kind: "options", options } : { kind: "invalid" };
135
+ }
136
+
137
+ // ---------- 命令结果 ----------
138
+
139
+ export function commandReplyText(reply: CommandReply, label: (agent: string) => string): string | undefined {
140
+ switch (reply.type) {
141
+ case "text":
142
+ return reply.text;
143
+ case "sessions":
144
+ if (reply.sessions.length === 0) return `${label(reply.agent)} 还没有历史会话。`;
145
+ return [
146
+ `${label(reply.agent)} 的历史会话${reply.fellBack ? "(当前目录没有,列出全部目录)" : ""}:`,
147
+ "",
148
+ ...reply.sessions.map((s) => `${s.id === reply.current ? "▶ " : ""}${clip(s.title || "(未命名)", 40)}\n/resume ${s.id}`),
149
+ ].join("\n");
150
+ case "models":
151
+ return [
152
+ `${label(reply.agent)} 的模型${reply.current ? `(当前 ${reply.current})` : ""}:`,
153
+ "",
154
+ ...reply.models.map((m) => `/model ${m.id}${m.label && m.label !== m.id ? ` —— ${m.label}` : ""}`),
155
+ ...(reply.effortSupported ? ["", `思考程度${reply.currentEffort ? `(当前 ${reply.currentEffort})` : ""}:发 /effort 程度`] : []),
156
+ ].join("\n");
157
+ case "agents":
158
+ return ["可用的专家(换了会开新会话):", "", ...reply.agents.map((a) => `${a.id === reply.current ? "▶ " : ""}${a.label}\n/expert ${a.id}`)].join("\n");
159
+ case "commands":
160
+ return ["可用的命令:", "", ...reply.commands.slice(0, 40).map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""} —— ${c.description}`)].join("\n");
161
+ case "none":
162
+ return undefined;
163
+ }
164
+ }
@@ -0,0 +1,52 @@
1
+ // 微信渠道:按绑定拉起 / 停掉长轮询。扫码、解绑、停用用户后就地对账,不用重启进程。
2
+ import { getUser, userEvents } from "../../core/users.js";
3
+ import { listWeixinAccounts, weixinAccountEvents, type WeixinAccount } from "../../core/weixin-accounts.js";
4
+ import { WeixinBot, type WeixinStatus } from "./bot.js";
5
+ import { stopWeixinLogins } from "./login.js";
6
+
7
+ const bots = new Map<string, WeixinBot>();
8
+ let started = false;
9
+
10
+ function reconcile(): void {
11
+ const wanted = new Map<string, WeixinAccount>();
12
+ for (const account of listWeixinAccounts()) {
13
+ const user = getUser(account.userId);
14
+ if (user && !user.disabled) wanted.set(account.userId, account);
15
+ }
16
+ for (const [userId, bot] of bots) {
17
+ const next = wanted.get(userId);
18
+ if (next?.botToken === bot.account.botToken) continue;
19
+ // 绑定没了或者重新扫码:旧 token 已经作废,不用再通知微信
20
+ bot.stop({ silent: true });
21
+ bots.delete(userId);
22
+ console.log(`[微信] 已停止 ${userId} 的连接`);
23
+ }
24
+ for (const [userId, account] of wanted) {
25
+ if (bots.has(userId)) continue;
26
+ const bot = new WeixinBot(account);
27
+ bots.set(userId, bot);
28
+ bot.start();
29
+ console.log(`[微信] 已启动 ${userId} 的连接`);
30
+ }
31
+ }
32
+
33
+ export function startWeixin(): void {
34
+ if (started) return;
35
+ started = true;
36
+ reconcile();
37
+ weixinAccountEvents.on("changed", reconcile);
38
+ userEvents.on("changed", reconcile);
39
+ }
40
+
41
+ export function stopWeixin(): void {
42
+ started = false;
43
+ weixinAccountEvents.off("changed", reconcile);
44
+ userEvents.off("changed", reconcile);
45
+ stopWeixinLogins();
46
+ for (const bot of bots.values()) bot.stop();
47
+ bots.clear();
48
+ }
49
+
50
+ export function weixinStatus(userId: string): WeixinStatus | undefined {
51
+ return bots.get(userId)?.status;
52
+ }
@@ -0,0 +1,180 @@
1
+ // 微信扫码登录:Web 上发起,服务端在后台轮询,页面每隔两秒来取一次状态。
2
+ //
3
+ // 手机可能要求输入屏幕上显示的数字(need_verifycode),这时轮询停下来等页面把数字交上来。
4
+ // 手机上提示「运行环境存在风险」时服务端不会有任何状态变化,所以这种情况只能靠界面上的说明。
5
+ import crypto from "node:crypto";
6
+ import QRCode from "qrcode";
7
+ import { bindWeixinAccount, getWeixinAccount } from "../../core/weixin-accounts.js";
8
+ import { DEFAULT_ILINK_BASE_URL, fetchQrCode, pollQrStatus } from "./client.js";
9
+
10
+ export type LoginState = "wait" | "scaned" | "need_verifycode" | "verify_wrong" | "confirmed" | "already" | "failed";
11
+
12
+ export type LoginView = { id: string; state: LoginState; qrUrl: string; qrSvg: string; message?: string };
13
+
14
+ type Session = LoginView & {
15
+ userId: string;
16
+ stop: AbortController;
17
+ verifyCode?: string;
18
+ /** 等验证码时挂在这里,交上来就继续 */
19
+ wake?: () => void;
20
+ };
21
+
22
+ /** 官方插件的上限:一轮登录最多 8 分钟,二维码最多换 3 次 */
23
+ const LOGIN_TIMEOUT_MS = 8 * 60_000;
24
+ const MAX_QR_REFRESH = 3;
25
+ /** 结束之后留一会儿,页面还要来取结果 */
26
+ const KEEP_FINISHED_MS = 5 * 60_000;
27
+
28
+ const sessions = new Map<string, Session>();
29
+
30
+ const svgOf = (url: string): Promise<string> => QRCode.toString(url, { type: "svg", margin: 1, width: 240 });
31
+
32
+ const view = ({ id, state, qrUrl, qrSvg, message }: Session): LoginView => ({ id, state, qrUrl, qrSvg, ...(message ? { message } : {}) });
33
+
34
+ function finish(session: Session, state: LoginState, message?: string): void {
35
+ session.state = state;
36
+ if (message) session.message = message;
37
+ session.wake?.();
38
+ setTimeout(() => sessions.delete(session.id), KEEP_FINISHED_MS).unref?.();
39
+ }
40
+
41
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
42
+
43
+ async function run(session: Session, qrcodeFirst: string): Promise<void> {
44
+ const deadline = Date.now() + LOGIN_TIMEOUT_MS;
45
+ let qrcode = qrcodeFirst;
46
+ let baseUrl = DEFAULT_ILINK_BASE_URL;
47
+ let refreshes = 1;
48
+ const signal = session.stop.signal;
49
+
50
+ const refresh = async (): Promise<boolean> => {
51
+ refreshes++;
52
+ if (refreshes > MAX_QR_REFRESH) return false;
53
+ const account = getWeixinAccount(session.userId);
54
+ const next = await fetchQrCode(account ? [account.botToken] : []);
55
+ qrcode = next.qrcode;
56
+ baseUrl = DEFAULT_ILINK_BASE_URL;
57
+ session.qrUrl = next.qrcodeUrl;
58
+ session.qrSvg = await svgOf(next.qrcodeUrl);
59
+ session.state = "wait";
60
+ return true;
61
+ };
62
+
63
+ while (Date.now() < deadline && !signal.aborted) {
64
+ const code: string | undefined = session.verifyCode;
65
+ const status = await pollQrStatus(baseUrl, qrcode, code, signal);
66
+ switch (status.status) {
67
+ case "wait":
68
+ break;
69
+ case "scaned":
70
+ // 带着验证码还能回 scaned:数字对了
71
+ session.verifyCode = undefined;
72
+ session.state = "scaned";
73
+ break;
74
+ case "scaned_but_redirect":
75
+ if (status.redirect_host) baseUrl = `https://${status.redirect_host}`;
76
+ session.state = "scaned";
77
+ break;
78
+ case "need_verifycode":
79
+ session.state = code ? "verify_wrong" : "need_verifycode";
80
+ session.verifyCode = undefined;
81
+ await new Promise<void>((resolve) => {
82
+ session.wake = resolve;
83
+ const left = Math.max(0, deadline - Date.now());
84
+ setTimeout(resolve, left).unref?.();
85
+ signal.addEventListener("abort", () => resolve(), { once: true });
86
+ });
87
+ session.wake = undefined;
88
+ continue;
89
+ case "expired":
90
+ case "verify_code_blocked": {
91
+ const blocked = status.status === "verify_code_blocked";
92
+ session.verifyCode = undefined;
93
+ if (!(await refresh())) {
94
+ finish(session, "failed", blocked ? "数字多次输入错误,请稍后再试。" : "二维码多次过期,请重新开始。");
95
+ return;
96
+ }
97
+ if (blocked) session.message = "数字多次输入错误,已换了一个二维码。";
98
+ break;
99
+ }
100
+ case "binded_redirect": {
101
+ // 服务端认出这个微信已经连着这台 agent-loft:不发新凭据。本地有记录就算成功,没有就只能先在手机上断开
102
+ if (getWeixinAccount(session.userId)) finish(session, "already", "这个微信已经连接,不需要重复连接。");
103
+ else finish(session, "failed", "微信认为已经连接过,但这里没有凭据。请先在手机微信的 ClawBot 里断开连接,再重新扫码。");
104
+ return;
105
+ }
106
+ case "confirmed": {
107
+ if (!status.bot_token || !status.ilink_bot_id || !status.ilink_user_id) {
108
+ // 没有 ilink_user_id 就没法确认后面的消息是不是扫码人发的,不能先连上再说
109
+ finish(session, "failed", "微信没有返回完整的连接信息,无法确认扫码人身份。");
110
+ return;
111
+ }
112
+ bindWeixinAccount({
113
+ userId: session.userId,
114
+ botId: status.ilink_bot_id,
115
+ botToken: status.bot_token,
116
+ baseUrl: status.baseurl || DEFAULT_ILINK_BASE_URL,
117
+ ilinkUserId: status.ilink_user_id,
118
+ });
119
+ finish(session, "confirmed");
120
+ return;
121
+ }
122
+ }
123
+ await sleep(1000);
124
+ }
125
+ if (!signal.aborted) finish(session, "failed", "等待超时,请重新开始。");
126
+ }
127
+
128
+ /** 发起一次登录。同一个人再发起,上一轮作废 */
129
+ export async function startWeixinLogin(userId: string): Promise<LoginView> {
130
+ for (const s of sessions.values()) {
131
+ if (s.userId === userId) {
132
+ s.stop.abort();
133
+ sessions.delete(s.id);
134
+ }
135
+ }
136
+ const account = getWeixinAccount(userId);
137
+ const qr = await fetchQrCode(account ? [account.botToken] : []);
138
+ const session: Session = {
139
+ id: crypto.randomBytes(8).toString("hex"),
140
+ userId,
141
+ state: "wait",
142
+ qrUrl: qr.qrcodeUrl,
143
+ qrSvg: await svgOf(qr.qrcodeUrl),
144
+ stop: new AbortController(),
145
+ };
146
+ sessions.set(session.id, session);
147
+ void run(session, qr.qrcode).catch((err) => {
148
+ if (session.stop.signal.aborted) return;
149
+ console.error("[微信] 扫码登录失败:", err instanceof Error ? err.message : err);
150
+ finish(session, "failed", "连接微信失败,请检查网络后重试。");
151
+ });
152
+ return view(session);
153
+ }
154
+
155
+ /** 只有发起的人能看 */
156
+ export function weixinLoginStatus(id: string, userId: string): LoginView | undefined {
157
+ const session = sessions.get(id);
158
+ return session?.userId === userId ? view(session) : undefined;
159
+ }
160
+
161
+ export function submitWeixinVerifyCode(id: string, userId: string, code: string): boolean {
162
+ const session = sessions.get(id);
163
+ if (session?.userId !== userId || (session.state !== "need_verifycode" && session.state !== "verify_wrong")) return false;
164
+ session.verifyCode = code;
165
+ session.state = "scaned";
166
+ session.wake?.();
167
+ return true;
168
+ }
169
+
170
+ export function cancelWeixinLogin(id: string, userId: string): void {
171
+ const session = sessions.get(id);
172
+ if (session?.userId !== userId) return;
173
+ session.stop.abort();
174
+ sessions.delete(id);
175
+ }
176
+
177
+ export function stopWeixinLogins(): void {
178
+ for (const s of sessions.values()) s.stop.abort();
179
+ sessions.clear();
180
+ }
@@ -14,6 +14,8 @@ export type BuiltinSpec = {
14
14
  multiAgentOnly?: boolean;
15
15
  /** 只在飞书里有意义(挂到 Web 会话上 / 退回来),Web 的补全里不列 */
16
16
  feishuOnly?: boolean;
17
+ /** 网页上不能用(对话中途不能换专家),飞书、微信能用 */
18
+ chatOnly?: boolean;
17
19
  };
18
20
 
19
21
  // 按常用程度排:这也是设置 → 命令、「/」列表和 /help 里的默认顺序
@@ -30,10 +32,10 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
30
32
  { name: "fork", description: "从当前会话分叉,原会话保留" },
31
33
  { name: "permission", args: "[ask|edit|full|default]", description: "查看 / 切换本对话的权限级别(逐次询问、自动改文件、完全允许)" },
32
34
  { name: "autoedit", args: "[on|off]", description: "本对话自动允许改工作目录内的文件(等于 /permission edit)" },
33
- // 网页上的对话中途不能换专家(新建对话时选),这几个只在飞书里有
34
- { name: "expert", args: "[名称]", description: "查看 / 换专家(换了会开新会话)", feishuOnly: true },
35
- { name: "claude", description: "换成 Claude Code 专家(开新会话)", multiAgentOnly: true, feishuOnly: true },
36
- { name: "codex", description: "换成 Codex 专家(开新会话)", multiAgentOnly: true, feishuOnly: true },
35
+ // 网页上的对话中途不能换专家(新建对话时选),这几个只在飞书、微信里有
36
+ { name: "expert", args: "[名称]", description: "查看 / 换专家(换了会开新会话)", chatOnly: true },
37
+ { name: "claude", description: "换成 Claude Code 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
38
+ { name: "codex", description: "换成 Codex 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
37
39
  { name: "web", description: "接上一条 Web 会话,在飞书里查看和回复", feishuOnly: true },
38
40
  { name: "detach", description: "不再接着 Web 会话,回到这个聊天自己的会话", feishuOnly: true },
39
41
  { name: "bind", args: "<绑定码>", description: "把这个飞书账号绑定到你的 agent-loft 用户(绑定码在 Web 的「设置 → 账号」里生成)", feishuOnly: true },
@@ -151,7 +153,7 @@ export function buildCatalog(params: {
151
153
  allowedAgents: string[];
152
154
  native: AgentCommand[];
153
155
  prefs: CommandPrefs | undefined;
154
- /** 给哪个渠道看:不是飞书就不列飞书专用的命令。不给就全列(设置页排序用) */
156
+ /** 给哪个渠道看:不是飞书就不列飞书专用的命令,网页上不列换专家。不给就全列(设置页排序用) */
155
157
  channel?: string;
156
158
  }): CommandEntry[] {
157
159
  const multi = params.allowedAgents.length > 1;
@@ -159,6 +161,7 @@ export function buildCatalog(params: {
159
161
  (c) =>
160
162
  (!c.multiAgentOnly || multi) &&
161
163
  (!c.feishuOnly || params.channel === undefined || params.channel === "feishu") &&
164
+ (!c.chatOnly || params.channel !== "web") &&
162
165
  // /claude /codex 只在这个渠道能用对应 agent 时才有意义
163
166
  (!["claude", "codex"].includes(c.name) || params.allowedAgents.includes(c.name)),
164
167
  ).map((c) => ({