@mindlink-ai/dsh-wechat-bot 0.0.0-stage → 1.0.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/index.js ADDED
@@ -0,0 +1,798 @@
1
+ /**
2
+ * Host half of @local/wechat-bot.
3
+ *
4
+ * 通过微信官方 iLink(ClawBot)通道把个人微信桥接进 DSH:
5
+ * - 扫码登录(二维码链接在侧边栏面板里);长轮询保持会话、刷新 context_token;
6
+ * - Agent 工具:wechat_status / wechat_login / wechat_send / wechat_recent;
7
+ * - 同源 HTTP 路由 /wechat-bot/* 供侧边栏面板读取状态、触发登录与测试推送。
8
+ *
9
+ * 状态与凭证保存在 ~/.dsh/wechat-bot/(可用环境变量 DSH_WECHAT_BOT_DIR 覆盖);
10
+ * 首次启动会尝试从旧版 daily-news/wechat 目录迁移凭证与群/私聊上下文。
11
+ */
12
+ import { randomUUID } from 'node:crypto'
13
+ import fs from 'node:fs'
14
+ import { createRequire } from 'node:module'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { getBotQrcode, pollQrcodeStatus, getUpdates, sendText, ILinkError } from './bridge/ilink.js'
19
+ import { renderDigest, chunkByBytes } from './bridge/render.js'
20
+
21
+ export const name = 'wechat-bot'
22
+ export const inject = ['tools']
23
+
24
+ const here = path.dirname(fileURLToPath(import.meta.url))
25
+ const DATA_DIR = process.env.DSH_WECHAT_BOT_DIR || path.join(os.homedir(), '.dsh', 'wechat-bot')
26
+ const TEXT_LIMIT = 1900
27
+ const RECENT_MAX = 100
28
+
29
+ export function apply(ctx) {
30
+ const settingsFile = path.join(DATA_DIR, 'settings.json')
31
+ const credFile = path.join(DATA_DIR, 'credentials.json')
32
+ const stateFile = path.join(DATA_DIR, 'state.json')
33
+ const pushLogFile = path.join(DATA_DIR, 'push.log')
34
+ const dirs = [DATA_DIR]
35
+
36
+ for (const dir of dirs) fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
37
+
38
+ const readJson = (file) => {
39
+ try {
40
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
41
+ } catch {
42
+ return null
43
+ }
44
+ }
45
+ const writeJson = (file, value, mode) => {
46
+ const tmp = `${file}.tmp`
47
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode })
48
+ fs.renameSync(tmp, file)
49
+ }
50
+
51
+ // --------------------------------------------------------------- QR 渲染(纯 JS)
52
+ // 登录二维码内容是一个 liteapp 链接;用随插件打包的 qrcode-generator(MIT)在本地生成
53
+ // GIF data URL,不依赖 Python、不访问网络。
54
+ let qrcodeLib = null
55
+ try {
56
+ qrcodeLib = createRequire(import.meta.url)('./vendor/qrcode.cjs')
57
+ } catch (error) {
58
+ qrcodeLib = null
59
+ ctx.logger?.warn?.(`[wechat-bot] qrcode vendor unavailable: ${error?.message ?? error}`)
60
+ }
61
+
62
+ /** 返回 data:image/gif;base64,... 或空串 */
63
+ function renderQrDataUrl(text) {
64
+ try {
65
+ if (!qrcodeLib) return ''
66
+ const qr = qrcodeLib(0, 'M')
67
+ qr.addData(String(text))
68
+ qr.make()
69
+ return qr.createDataURL(6, 2)
70
+ } catch (error) {
71
+ ctx.logger?.warn?.(`[wechat-bot] qr render failed: ${error?.message ?? error}`)
72
+ return ''
73
+ }
74
+ }
75
+
76
+ // ---------------------------------------------------------------- settings
77
+ const settings = {
78
+ mode: 'direct',
79
+ targetUserId: '',
80
+ maxChars: TEXT_LIMIT,
81
+ autoStart: true,
82
+ legacyDir: '',
83
+ chatForward: true,
84
+ chatSessionId: '',
85
+ workspaceCwd: os.homedir(),
86
+ ...(readJson(settingsFile) || {}),
87
+ }
88
+ const saveSettings = () => {
89
+ try {
90
+ writeJson(settingsFile, settings)
91
+ } catch (error) {
92
+ ctx.logger?.warn?.(`[wechat-bot] cannot save settings: ${error?.message ?? error}`)
93
+ }
94
+ }
95
+
96
+ // ---------------------------------------------------------- credentials/state
97
+ const saved = readJson(credFile)
98
+ let creds = saved && saved.token ? saved : null
99
+ const persisted = readJson(stateFile) || {}
100
+ const rt = {
101
+ creds,
102
+ conn: { state: creds ? 'connecting' : 'unpaired', error: '', since: Date.now() },
103
+ account: creds
104
+ ? { botId: creds.accountId || '', userId: creds.userId || '', baseUrl: creds.baseUrl || '', savedAt: creds.savedAt || '' }
105
+ : { botId: '', userId: '', baseUrl: '', savedAt: '' },
106
+ qr: { url: '', ts: 0, active: false, dataUrl: '' },
107
+ cursor: typeof persisted.cursor === 'string' ? persisted.cursor : '',
108
+ directs: persisted.directs && typeof persisted.directs === 'object' ? persisted.directs : {},
109
+ loginGen: 0,
110
+ counters: { received: 0, sent: 0, failed: 0, drops: 0 },
111
+ lastPush: persisted.lastPush || { at: 0, ok: false, error: '', chunks: 0, chars: 0 },
112
+ recent: [],
113
+ pushLog: [],
114
+ }
115
+ let stops = { poll: new AbortController(), login: 0 }
116
+ let disposed = false
117
+
118
+ const saveState = () => {
119
+ try {
120
+ writeJson(stateFile, {
121
+ version: 1,
122
+ cursor: rt.cursor,
123
+ directs: rt.directs,
124
+ lastPush: rt.lastPush,
125
+ updatedAt: Date.now(),
126
+ })
127
+ } catch (error) {
128
+ ctx.logger?.warn?.(`[wechat-bot] cannot save state: ${error?.message ?? error}`)
129
+ }
130
+ }
131
+
132
+ const pushAudit = (entry) => {
133
+ try {
134
+ fs.appendFileSync(pushLogFile, `${JSON.stringify({ ts: Date.now(), ...entry })}\n`)
135
+ } catch {
136
+ /* 审计写入失败不影响主流程 */
137
+ }
138
+ }
139
+
140
+ /** 设置当前登录二维码,并生成 GIF data URL(渲染失败则面板回退为链接) */
141
+ function setQr(qr) {
142
+ rt.qr = { url: qr.url, ts: Date.now(), active: true, base: qr.base, dataUrl: renderQrDataUrl(qr.url) }
143
+ return rt.qr
144
+ }
145
+
146
+ // ------------------------------------------------------------- legacy import
147
+ try {
148
+ const legacy = settings.legacyDir
149
+ const legacyCred = legacy ? path.join(legacy, 'secrets', 'credentials.json') : ''
150
+ const legacyState = legacy ? path.join(legacy, 'state.json') : ''
151
+ if (!creds && legacyCred && fs.existsSync(legacyCred)) {
152
+ const value = JSON.parse(fs.readFileSync(legacyCred, 'utf8'))
153
+ if (value?.token) {
154
+ creds = {
155
+ version: 1,
156
+ token: value.token,
157
+ accountId: value.accountId || '',
158
+ userId: value.userId || '',
159
+ baseUrl: value.baseUrl || 'https://ilinkai.weixin.qq.com',
160
+ savedAt: value.savedAt || new Date().toISOString(),
161
+ }
162
+ rt.creds = creds
163
+ rt.account = { botId: creds.accountId, userId: creds.userId, baseUrl: creds.baseUrl, savedAt: creds.savedAt }
164
+ writeJson(credFile, creds, 0o600)
165
+ rt.conn = { state: 'connecting', error: '', since: Date.now() }
166
+ ctx.logger?.info?.('[wechat-bot] imported legacy credentials')
167
+ }
168
+ }
169
+ const legacyCtx = legacyState && fs.existsSync(legacyState) ? JSON.parse(fs.readFileSync(legacyState, 'utf8')) : null
170
+ if (legacyCtx) {
171
+ if (!rt.cursor && typeof legacyCtx.cursor === 'string') rt.cursor = legacyCtx.cursor
172
+ const directs = legacyCtx.directs && typeof legacyCtx.directs === 'object' ? legacyCtx.directs : {}
173
+ for (const [uid, value] of Object.entries(directs)) {
174
+ if (!rt.directs[uid] && value?.contextToken) rt.directs[uid] = value
175
+ }
176
+ if (!settings.targetUserId) {
177
+ const ids = Object.keys(rt.directs)
178
+ if (ids.length) settings.targetUserId = ids[0]
179
+ }
180
+ if (rt.cursor || Object.keys(directs).length) saveState()
181
+ ctx.logger?.info?.('[wechat-bot] imported legacy cursor/context tokens')
182
+ }
183
+ } catch (error) {
184
+ ctx.logger?.warn?.(`[wechat-bot] legacy import skipped: ${error?.message ?? error}`)
185
+ }
186
+
187
+ // ------------------------------------------------------------------ runtime
188
+ const setConn = (state, error = '') => {
189
+ if (rt.conn.state !== state) rt.conn = { ...rt.conn, state, error, since: Date.now() }
190
+ else rt.conn.error = error
191
+ }
192
+
193
+ let polling = false
194
+ async function pollLoop() {
195
+ if (polling || disposed || !rt.creds) return
196
+ polling = true
197
+ const controller = stops.poll
198
+ let failures = 0
199
+ setConn('online')
200
+ try {
201
+ while (!disposed && !controller.signal.aborted) {
202
+ try {
203
+ const { msgs, cursor } = await getUpdates(rt.creds, rt.cursor, controller.signal, 35000)
204
+ failures = 0
205
+ if (cursor) rt.cursor = cursor
206
+ let changed = Boolean(cursor)
207
+ for (const msg of Array.isArray(msgs) ? msgs : []) {
208
+ rt.counters.received += 1
209
+ rt.recent.push({
210
+ at: Date.now(),
211
+ from: msg?.from_user_id || '',
212
+ group: typeof msg?.group_id === 'string' ? msg.group_id : '',
213
+ text: (msg?.item_list || []).map((i) => i?.text_item?.text).filter(Boolean).join(' ').slice(0, 300),
214
+ })
215
+ if (rt.recent.length > RECENT_MAX) rt.recent.splice(0, rt.recent.length - RECENT_MAX)
216
+ const uid = msg?.from_user_id
217
+ const isGroup = typeof msg?.group_id === 'string' && msg.group_id
218
+ if (isGroup) {
219
+ rt.counters.drops += 1
220
+ continue
221
+ }
222
+ if (msg?.message_type === 2) {
223
+ /* 机器人回显 */
224
+ continue
225
+ }
226
+ const text = (msg?.item_list || []).map((i) => i?.text_item?.text).filter(Boolean).join(' ').trim()
227
+ if (typeof uid === 'string' && uid.endsWith('@im.wechat') && msg?.context_token) {
228
+ const token = String(msg.context_token)
229
+ rt.directs[uid] = { contextToken: token, updatedAt: Date.now(), text: '' }
230
+ changed = true
231
+ if (text.startsWith('/')) void handleCommand(text, uid, token)
232
+ else if (text && settings.chatForward) void forwardToChat(text, uid, token)
233
+ }
234
+ }
235
+ if (changed) saveState()
236
+ if (rt.conn.state !== 'online') setConn('online')
237
+ } catch (error) {
238
+ if (error?.code === 'session-expired') {
239
+ setConn('expired', '微信连接已失效(-14),请重新扫码登录')
240
+ saveState()
241
+ break
242
+ }
243
+ failures += 1
244
+ setConn(failures >= 3 ? 'error' : rt.conn.state, error?.message || String(error))
245
+ await new Promise((resolve) => setTimeout(resolve, failures >= 3 ? 30000 : 2000))
246
+ }
247
+ }
248
+ } finally {
249
+ polling = false
250
+ }
251
+ }
252
+
253
+ // 登录:beginLogin 立即返回当前二维码(非阻塞),runLogin 在后台轮询扫码结果
254
+ async function beginLogin() {
255
+ const gen = ++rt.loginGen
256
+ const qr = await getBotQrcode(creds?.baseUrl || undefined)
257
+ await setQr(qr)
258
+ setConn(creds ? 'connecting' : 'unpaired', '等待手机微信扫码确认')
259
+ void runLogin(gen, qr)
260
+ return { ok: true, online: false, url: rt.qr.url, hasQr: Boolean(rt.qr.dataUrl) }
261
+ }
262
+
263
+ async function runLogin(gen, qr) {
264
+ try {
265
+ while (!disposed && rt.loginGen === gen) {
266
+ const status = await pollQrcodeStatus(qr.qrcode, qr.base)
267
+ if (rt.loginGen !== gen) return
268
+ if (status.status === 'expired') {
269
+ const next = await getBotQrcode(creds?.baseUrl || undefined)
270
+ qr = next
271
+ await setQr(next)
272
+ setConn(creds ? 'connecting' : 'unpaired', '二维码已刷新,等待手机微信扫码确认')
273
+ continue
274
+ }
275
+ if (status.status === 'scaned') {
276
+ setConn('connecting', '已扫码,等待手机端确认')
277
+ continue
278
+ }
279
+ if (status.status === 'confirmed') {
280
+ if (!status.bot_token || !status.ilink_bot_id) throw new Error('登录确认但未返回完整凭证')
281
+ creds = {
282
+ version: 1,
283
+ token: status.bot_token,
284
+ accountId: status.ilink_bot_id,
285
+ userId: status.ilink_user_id || '',
286
+ baseUrl: status.baseurl || qr.base || 'https://ilinkai.weixin.qq.com',
287
+ savedAt: new Date().toISOString(),
288
+ }
289
+ rt.creds = creds
290
+ rt.account = { botId: creds.accountId, userId: creds.userId, baseUrl: creds.baseUrl, savedAt: creds.savedAt }
291
+ writeJson(credFile, creds, 0o600)
292
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
293
+ rt.cursor = ''
294
+ rt.directs = {}
295
+ rt.loginGen = 0
296
+ saveState()
297
+ setConn('online')
298
+ pollLoop()
299
+ return
300
+ }
301
+ }
302
+ } catch (error) {
303
+ setConn('error', error?.message || String(error))
304
+ rt.qr = { ...rt.qr, active: false }
305
+ }
306
+ }
307
+
308
+ function logout() {
309
+ rt.loginGen = 0
310
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
311
+ stops.poll.abort()
312
+ stops.poll = new AbortController()
313
+ rt.creds = null
314
+ creds = null
315
+ try {
316
+ fs.rmSync(credFile, { force: true })
317
+ } catch {
318
+ /* ignore */
319
+ }
320
+ rt.cursor = ''
321
+ saveState()
322
+ setConn('unpaired', '')
323
+ return { ok: true, online: false }
324
+ }
325
+
326
+ // -------------------------------------------------------------------- push
327
+ function pickTarget() {
328
+ const uid = settings.targetUserId && rt.directs[settings.targetUserId] ? settings.targetUserId : null
329
+ if (uid) return { uid, token: rt.directs[uid]?.contextToken || '' }
330
+ const ids = Object.keys(rt.directs)
331
+ if (!ids.length) return null
332
+ ids.sort((a, b) => (rt.directs[b]?.updatedAt || 0) - (rt.directs[a]?.updatedAt || 0))
333
+ return { uid: ids[0], token: rt.directs[ids[0]]?.contextToken || '' }
334
+ }
335
+
336
+ async function pushText(rawText, { source = 'tool' } = {}) {
337
+ if (!rt.creds) return { ok: false, error: 'not_logged_in', message: '微信 bot 尚未登录,请先在面板中扫码登录' }
338
+ if (rt.conn.state !== 'online') return { ok: false, error: 'not_online', message: `连接状态:${rt.conn.state}(${rt.conn.error || '未就绪'})` }
339
+ const target = pickTarget()
340
+ if (!target?.token) {
341
+ return { ok: false, error: 'no_context', message: '还没有可推送的会话凭证:请在微信里给机器人发一条任意消息,让 bot 记录 context_token' }
342
+ }
343
+ const maxChars = Math.max(200, Number(settings.maxChars) || TEXT_LIMIT)
344
+ const chunks = chunkByBytes(String(rawText || '').trim(), maxChars).slice(0, 3)
345
+ if (!chunks[0]) return { ok: false, error: 'empty', message: '没有可发送的内容' }
346
+ const sent = []
347
+ for (const chunk of chunks) {
348
+ try {
349
+ await sendText(rt.creds, { toUserId: target.uid, contextToken: target.token, text: chunk })
350
+ sent.push(chunk.length)
351
+ rt.counters.sent += 1
352
+ } catch (error) {
353
+ rt.counters.failed += 1
354
+ rt.lastPush = { at: Date.now(), ok: false, error: error?.message || String(error), chunks: sent.length, chars: sent.reduce((a, b) => a + b, 0) }
355
+ if (error?.code === 'session-expired') setConn('expired', '微信连接已失效(-14),请重新扫码登录')
356
+ saveState()
357
+ pushAudit({ ok: false, source, target: target.uid, error: error?.message || String(error) })
358
+ return { ok: false, error: error?.code || 'send_failed', message: error?.message || String(error), chunks: sent.length }
359
+ }
360
+ if (chunk !== chunks[chunks.length - 1]) await new Promise((resolve) => setTimeout(resolve, 1200))
361
+ }
362
+ rt.lastPush = { at: Date.now(), ok: true, error: '', chunks: sent.length, chars: sent.reduce((a, b) => a + b, 0) }
363
+ saveState()
364
+ pushAudit({ ok: true, source, target: target.uid, chunks: sent.length, chars: rt.lastPush.chars })
365
+ return { ok: true, chunks: sent.length, chars: rt.lastPush.chars, target: target.uid }
366
+ }
367
+
368
+ // ------------------------------------------------------- 微信 ⇄ DSH 会话转发
369
+ const chatPending = []
370
+ let chatAccum = ''
371
+
372
+ /** 直接回复到当前微信会话(使用入站消息带来的最新 context_token) */
373
+ async function sendToWeChat(uid, token, body) {
374
+ if (!rt.creds) return { ok: false, error: 'not_logged_in' }
375
+ const chunks = chunkByBytes(String(body ?? '').trim(), Math.max(200, Number(settings.maxChars) || TEXT_LIMIT)).slice(0, 3)
376
+ if (!chunks[0]) return { ok: false, error: 'empty' }
377
+ for (let i = 0; i < chunks.length; i += 1) {
378
+ await sendText(rt.creds, { toUserId: uid, contextToken: token, text: chunks[i] })
379
+ rt.counters.sent += 1
380
+ if (i < chunks.length - 1) await new Promise((resolve) => setTimeout(resolve, 1200))
381
+ }
382
+ return { ok: true, chunks: chunks.length }
383
+ }
384
+
385
+ const helpText = () =>
386
+ [
387
+ '可用指令:',
388
+ '/help 查看指令',
389
+ '/status 连接与账号状态',
390
+ '/login 扫码登录(返回二维码链接)',
391
+ '/logout 退出登录',
392
+ '/recent 最近收到的消息',
393
+ '/news 让 DSH 跑今天的新闻简报',
394
+ '/new 重置对话会话(下一条消息新建 DSH 会话)',
395
+ '',
396
+ '其余消息会转交给 DSH 会话处理,处理结果自动回传到微信。',
397
+ ].join('\n')
398
+
399
+ async function ensureChatSession() {
400
+ if (settings.chatSessionId) return settings.chatSessionId
401
+ const sessions = ctx.get('sessionController')
402
+ if (!sessions) return ''
403
+ const created = await sessions.create({ cwd: settings.workspaceCwd })
404
+ settings.chatSessionId = created?.sessionId || ''
405
+ if (settings.chatSessionId) saveSettings()
406
+ return settings.chatSessionId
407
+ }
408
+
409
+ /** 把一条微信消息转交给 DSH 会话;回合结束后由 flushChatTurn 回传 */
410
+ async function forwardToChat(text, uid, token) {
411
+ const sessions = ctx.get('sessionController')
412
+ if (!sessions) {
413
+ await sendToWeChat(uid, token, 'DSH 会话服务不可用,消息未转交').catch(() => {})
414
+ return { ok: false, error: 'no_session_service' }
415
+ }
416
+ try {
417
+ const sessionId = await ensureChatSession()
418
+ if (!sessionId) {
419
+ await sendToWeChat(uid, token, '无法创建 DSH 会话,消息未转交').catch(() => {})
420
+ return { ok: false, error: 'no_session' }
421
+ }
422
+ chatPending.push({ uid, token, at: Date.now() })
423
+ if (chatPending.length > 20) chatPending.shift()
424
+ await sessions.prompt(
425
+ { requestId: randomUUID(), sessionId, mode: 'queue', content: [{ type: 'text', text }] },
426
+ new AbortController().signal,
427
+ )
428
+ return { ok: true, sessionId }
429
+ } catch (error) {
430
+ chatPending.pop()
431
+ await sendToWeChat(uid, token, `转交 DSH 会话失败:${error?.message || error}`).catch(() => {})
432
+ return { ok: false, error: 'prompt_failed', message: error?.message || String(error) }
433
+ }
434
+ }
435
+
436
+ /** 一个 DSH 回合结束:把这轮助手文本回传到发起消息的微信会话 */
437
+ function flushChatTurn() {
438
+ if (!chatPending.length) {
439
+ chatAccum = ''
440
+ return
441
+ }
442
+ const pendingTurn = chatPending.shift()
443
+ const text = chatAccum.trim()
444
+ chatAccum = ''
445
+ const body = text || '(本轮没有文本回复,完整过程见 DSH 会话)'
446
+ void sendToWeChat(pendingTurn.uid, pendingTurn.token, body).catch((error) => {
447
+ ctx.logger?.warn?.(`[wechat-bot] chat reply failed: ${error?.message ?? error}`)
448
+ })
449
+ }
450
+
451
+ async function handleCommand(text, uid, token) {
452
+ const [cmd] = String(text).split(/\s+/)
453
+ const name = (cmd || '').toLowerCase()
454
+ try {
455
+ if (name === '/help') return await sendToWeChat(uid, token, helpText())
456
+ if (name === '/status') {
457
+ const body = [
458
+ `连接:${rt.conn.state}${rt.conn.error ? `(${rt.conn.error})` : ''}`,
459
+ `bot:${rt.account.botId || '—'}`,
460
+ `计数:收 ${rt.counters.received} / 发 ${rt.counters.sent} / 失败 ${rt.counters.failed}`,
461
+ `最近推送:${rt.lastPush.at ? `${new Date(rt.lastPush.at).toLocaleString()} ${rt.lastPush.ok ? '成功' : '失败'}` : '无'}`,
462
+ ].join('\n')
463
+ return await sendToWeChat(uid, token, body)
464
+ }
465
+ if (name === '/login') {
466
+ const result = await beginLogin()
467
+ return await sendToWeChat(uid, token, result.url ? `请用手机微信打开链接并确认登录:\n${result.url}` : '二维码获取失败,请稍后重试')
468
+ }
469
+ if (name === '/logout') {
470
+ logout()
471
+ return await sendToWeChat(uid, token, '已退出登录,可在 DSH 侧边栏「微信bot」重新扫码')
472
+ }
473
+ if (name === '/recent') {
474
+ const list = rt.recent.slice(-8).map((item) => `- ${new Date(item.at).toLocaleTimeString()} ${item.text || '[非文本]'}`)
475
+ return await sendToWeChat(uid, token, list.length ? `最近消息:\n${list.join('\n')}` : '暂无消息')
476
+ }
477
+ if (name === '/news') return await forwardToChat('跑今天的新闻简报', uid, token)
478
+ if (name === '/new') {
479
+ settings.chatSessionId = ''
480
+ saveSettings()
481
+ chatAccum = ''
482
+ chatPending.length = 0
483
+ return await sendToWeChat(uid, token, '已重置对话会话,下一条消息将新建 DSH 会话')
484
+ }
485
+ return await sendToWeChat(uid, token, `未知指令:${cmd}\n\n${helpText()}`)
486
+ } catch (error) {
487
+ await sendToWeChat(uid, token, `指令执行失败:${error?.message || error}`).catch(() => {})
488
+ return { ok: false, error: 'command_failed' }
489
+ }
490
+ }
491
+
492
+ function buildState() {
493
+ return {
494
+ ok: true,
495
+ connection: { state: rt.conn.state, error: rt.conn.error, since: rt.conn.since },
496
+ account: { ...rt.account, userIdConfigured: settings.targetUserId === rt.account.userId },
497
+ qr: { url: rt.qr.url, ts: rt.qr.ts, active: rt.qr.active, hasQr: Boolean(rt.qr.dataUrl), dataUrl: rt.qr.dataUrl },
498
+ counters: { ...rt.counters },
499
+ lastPush: { ...rt.lastPush },
500
+ recent: rt.recent.slice(-20),
501
+ service: { name: 'wechatBot', methods: ['status', 'send', 'sendFile', 'sendDigest', 'login', 'recent'] },
502
+ settings: {
503
+ mode: settings.mode,
504
+ maxChars: settings.maxChars,
505
+ autoStart: settings.autoStart,
506
+ targetUserId: settings.targetUserId,
507
+ chatForward: Boolean(settings.chatForward),
508
+ chatSessionId: settings.chatSessionId,
509
+ },
510
+ updatedAt: Date.now(),
511
+ }
512
+ }
513
+
514
+ function pushFromFile(filePath) {
515
+ try {
516
+ return pushText(renderDigest(fs.readFileSync(String(filePath), 'utf8')), { source: 'file' })
517
+ } catch (error) {
518
+ return Promise.resolve({ ok: false, error: 'read_failed', message: `读取日报失败:${error?.message ?? error}` })
519
+ }
520
+ }
521
+
522
+ // -------------------------------------------------------------------- tools
523
+ const textResult = (value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }]
524
+ const tools = [
525
+ {
526
+ name: 'wechat_status',
527
+ description:
528
+ '查看本机微信 bot 的连接状态与账号信息:是否已登录、在线/失效、bot 与用户 ID、是否有待扫码的二维码、最近一次推送结果。推送前或连接异常时先调用。',
529
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
530
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => textResult(value) },
531
+ async execute() {
532
+ return buildState()
533
+ },
534
+ },
535
+ {
536
+ name: 'wechat_login',
537
+ description:
538
+ '微信 bot 扫码登录控制。action=start 生成/轮询登录二维码,返回 qrUrl 供用户在手机微信中打开确认;action=refresh 重新生成二维码;action=logout 退出登录并删除本地凭证。',
539
+ parameters: {
540
+ type: 'object',
541
+ properties: {
542
+ action: { type: 'string', enum: ['start', 'refresh', 'logout', 'cancel'], description: '登录动作' },
543
+ },
544
+ additionalProperties: false,
545
+ },
546
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => textResult(value) },
547
+ timeoutMs: 30000,
548
+ isConcurrencySafe: () => false,
549
+ async execute(args) {
550
+ const action = String(args?.action ?? 'start')
551
+ if (action === 'logout') return logout()
552
+ if (action === 'cancel') {
553
+ rt.loginGen += 1
554
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
555
+ setConn(rt.creds ? 'online' : 'unpaired', '')
556
+ return { ok: true, action, online: rt.conn.state === 'online', qrUrl: '' }
557
+ }
558
+ if (action === 'refresh') {
559
+ rt.loginGen += 1
560
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
561
+ }
562
+ const value = await beginLogin()
563
+ return { ok: value.ok !== false, action, online: rt.conn.state === 'online', qrUrl: rt.qr.url, connection: rt.conn.state, hint: rt.qr.url ? '在手机微信中打开 qrUrl 确认登录' : '' }
564
+ },
565
+ },
566
+ {
567
+ name: 'wechat_send',
568
+ description:
569
+ '把文本推送到你本人的微信(1:1 会话)。text 直接给内容;file 给工作区里日报 Markdown 的绝对路径,会自动压缩成“今日速览 + 每主题 1 条 + 链接”的短消息并按 1900 字节分片。推送前会自动检查登录与最近会话凭证。',
570
+ parameters: {
571
+ type: 'object',
572
+ properties: {
573
+ text: { type: 'string', description: '要推送的文本(与 file 二选一)' },
574
+ file: { type: 'string', description: '日报 Markdown 绝对路径(与 text 二选一)' },
575
+ },
576
+ additionalProperties: false,
577
+ },
578
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => textResult(value) },
579
+ timeoutMs: 40000,
580
+ isConcurrencySafe: () => false,
581
+ async execute(args) {
582
+ const file = String(args?.file ?? '').trim()
583
+ if (file) return pushFromFile(file)
584
+ return pushText(String(args?.text ?? '').trim(), { source: 'tool' })
585
+ },
586
+ },
587
+ {
588
+ name: 'wechat_recent',
589
+ description: '读取微信 bot 最近收到的消息(仅元数据,最多 100 条),用于确认 context_token 是否新鲜、排查收不到消息的原因。',
590
+ parameters: {
591
+ type: 'object',
592
+ properties: { limit: { type: 'number', description: '返回条数,默认 20,最大 100' } },
593
+ additionalProperties: false,
594
+ },
595
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => textResult(value) },
596
+ async execute(args) {
597
+ const limit = Math.max(1, Math.min(100, Number(args?.limit ?? 20) || 20))
598
+ return { ok: true, count: rt.recent.length, messages: rt.recent.slice(-limit) }
599
+ },
600
+ },
601
+ ]
602
+
603
+ for (const tool of tools) ctx.effect(() => ctx.tools.register(tool))
604
+
605
+ // ------------------------------------------------- Host service(供其他插件调用)
606
+ // 其他插件声明 inject: ['wechatBot'] 后即可 ctx.get('wechatBot') 使用:
607
+ // api.status() / api.send(text) / api.sendFile(mdPath) / api.sendDigest(mdPath) / api.login(action) / api.recent(limit)
608
+ const api = {
609
+ version: '1.0.0',
610
+ status: () => buildState(),
611
+ send: (text, options = {}) => pushText(String(text ?? ''), { source: options.source || 'service' }),
612
+ sendFile: (filePath) => pushFromFile(filePath),
613
+ sendDigest: (filePath) => pushFromFile(filePath),
614
+ login: async (action = 'start') => {
615
+ if (action === 'logout') return logout()
616
+ if (action === 'cancel') {
617
+ rt.loginGen += 1
618
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
619
+ setConn(rt.creds ? 'online' : 'unpaired', '')
620
+ return { ok: true, online: rt.conn.state === 'online' }
621
+ }
622
+ if (action === 'refresh') {
623
+ rt.loginGen += 1
624
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
625
+ }
626
+ return beginLogin()
627
+ },
628
+ recent: (limit = 20) => rt.recent.slice(-Math.max(1, Math.min(100, Number(limit) || 20))),
629
+ }
630
+ if (typeof ctx.provide === 'function') {
631
+ ctx.effect(() => ctx.provide('wechatBot', api))
632
+ } else {
633
+ ctx.logger?.warn?.('[wechat-bot] ctx.provide unavailable: wechatBot service not exposed')
634
+ }
635
+
636
+ // ---------------------------------------------------------------- web routes
637
+ const web = ctx.get('webServer')
638
+ if (web && typeof web.register === 'function') {
639
+ const origin = () => {
640
+ try {
641
+ return web.getOrigin?.() || ''
642
+ } catch {
643
+ return ''
644
+ }
645
+ }
646
+ const sendJson = (res, value, status = 200) => {
647
+ const body = JSON.stringify(value)
648
+ res.writeHead(status, {
649
+ 'content-type': 'application/json; charset=utf-8',
650
+ 'cache-control': 'no-store',
651
+ 'content-length': Buffer.byteLength(body),
652
+ })
653
+ res.end(body)
654
+ }
655
+ const readBody = (req) =>
656
+ new Promise((resolve, reject) => {
657
+ let raw = ''
658
+ req.setEncoding('utf8')
659
+ req.on('data', (chunk) => {
660
+ raw += chunk
661
+ if (raw.length > 1024 * 1024) {
662
+ reject(new Error('request body too large'))
663
+ req.destroy()
664
+ }
665
+ })
666
+ req.on('end', () => resolve(raw))
667
+ req.on('error', reject)
668
+ })
669
+ const page = () => `<!doctype html><html lang="zh"><head><meta charset="utf-8"><title>微信 bot</title>
670
+ <style>body{font:14px/1.6 system-ui,sans-serif;max-width:760px;margin:32px auto;padding:0 16px;color:#111}
671
+ pre{background:#f5f5f5;padding:10px;border-radius:8px;overflow:auto;max-height:420px}</style></head>
672
+ <body><h2>微信 bot(调试页)</h2><p>正式界面在左侧边栏的「微信bot」按钮里。</p><pre id="s">加载中…</pre>
673
+ <script>fetch('/wechat-bot/state').then(r=>r.json()).then(s=>{document.getElementById('s').textContent=JSON.stringify(s,null,2)})</script></body></html>`
674
+
675
+ // 注意:webServer 的 resource 形式只接受 GET/HEAD;面板需要 POST,必须用 handler 形式。
676
+ ctx.effect(() =>
677
+ web.register({
678
+ kind: 'prefix',
679
+ path: '/wechat-bot',
680
+ handler: async (req, res) => {
681
+ try {
682
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
683
+ const method = (req.method || 'GET').toUpperCase()
684
+ if (method === 'GET' && url.pathname === '/wechat-bot/state') return sendJson(res, buildState())
685
+ if (method === 'GET' && url.pathname === '/wechat-bot/qr.png') {
686
+ if (!rt.qr.dataUrl) {
687
+ res.writeHead(404, { 'cache-control': 'no-store' })
688
+ return res.end('no qr')
689
+ }
690
+ const comma = rt.qr.dataUrl.indexOf(',')
691
+ const meta = rt.qr.dataUrl.slice(5, comma) // e.g. image/gif;base64
692
+ const mime = meta.split(';')[0] || 'image/gif'
693
+ const bytes = Buffer.from(rt.qr.dataUrl.slice(comma + 1), 'base64')
694
+ res.writeHead(200, { 'content-type': mime, 'cache-control': 'no-store', 'content-length': bytes.length })
695
+ return res.end(bytes)
696
+ }
697
+ if (method === 'GET' && url.pathname === '/wechat-bot/') {
698
+ const html = page()
699
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
700
+ return res.end(html)
701
+ }
702
+ if (method === 'POST') {
703
+ const originHeader = req.headers.origin || ''
704
+ const own = origin()
705
+ if (originHeader && own && !originHeader.startsWith(own) && !originHeader.startsWith('http://127.0.0.1')) {
706
+ return sendJson(res, { ok: false, error: 'cross-origin request refused' }, 403)
707
+ }
708
+ let body = {}
709
+ try {
710
+ body = JSON.parse((await readBody(req)) || '{}')
711
+ } catch {
712
+ return sendJson(res, { ok: false, error: 'invalid json' }, 400)
713
+ }
714
+ const action = String(body.action || '')
715
+ if (url.pathname === '/wechat-bot/login') {
716
+ if (action === 'logout') {
717
+ logout()
718
+ return sendJson(res, { ok: true, state: buildState() })
719
+ }
720
+ if (action === 'cancel') {
721
+ rt.loginGen += 1
722
+ rt.qr = { url: '', ts: 0, active: false, dataUrl: '' }
723
+ setConn(rt.creds ? 'online' : 'unpaired', '')
724
+ return sendJson(res, { ok: true, state: buildState() })
725
+ }
726
+ const result = await beginLogin()
727
+ return sendJson(res, { ...result, state: buildState() })
728
+ }
729
+ if (url.pathname === '/wechat-bot/send') {
730
+ const text = String(body.text || '').trim()
731
+ if (!text) return sendJson(res, { ok: false, error: 'text required' }, 400)
732
+ return sendJson(res, await pushText(text, { source: 'panel' }))
733
+ }
734
+ return sendJson(res, { ok: false, error: 'unknown route' }, 404)
735
+ }
736
+ res.writeHead(405, { allow: 'GET, POST', 'content-type': 'text/plain; charset=utf-8' })
737
+ res.end('method not allowed')
738
+ } catch (error) {
739
+ ctx.logger?.warn?.(`[wechat-bot] http handler failed: ${error?.message ?? error}`)
740
+ if (res.headersSent) {
741
+ res.destroy()
742
+ return
743
+ }
744
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
745
+ res.end('internal error')
746
+ }
747
+ },
748
+ }),
749
+ )
750
+ } else {
751
+ ctx.logger?.warn?.('[wechat-bot] web server unavailable: sidebar panel state endpoint disabled')
752
+ }
753
+
754
+ // ------------------------------------------------------------------ lifecycle
755
+ // 会话事件:累积本回合助手文本,turn/end 时把结果回传到微信
756
+ const onSessionEvent = (session, event) => {
757
+ try {
758
+ const sid = typeof session === 'string' ? session : session?.id
759
+ if (!settings.chatSessionId || sid !== settings.chatSessionId) return
760
+ if (event?.type === 'turn/start') {
761
+ chatAccum = ''
762
+ return
763
+ }
764
+ if (event?.type === 'assistant/message') {
765
+ const content = event?.data?.message?.content
766
+ if (Array.isArray(content)) {
767
+ const text = content
768
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
769
+ .map((block) => block.text)
770
+ .join('')
771
+ if (text) chatAccum = chatAccum ? `${chatAccum}\n${text}` : text
772
+ }
773
+ return
774
+ }
775
+ if (event?.type === 'turn/end') flushChatTurn()
776
+ } catch (error) {
777
+ ctx.logger?.warn?.(`[wechat-bot] session event handler failed: ${error?.message ?? error}`)
778
+ }
779
+ }
780
+ try {
781
+ ctx.effect(() => ctx.on('session/event', onSessionEvent))
782
+ } catch (error) {
783
+ ctx.logger?.warn?.(`[wechat-bot] session/event subscription unavailable: ${error?.message ?? error}`)
784
+ }
785
+
786
+ ctx.effect(() => {
787
+ if (settings.autoStart && rt.creds) pollLoop()
788
+ return () => {
789
+ disposed = true
790
+ rt.loginGen = 0
791
+ stops.poll.abort()
792
+ for (const tool of tools) void tool
793
+ saveState()
794
+ }
795
+ })
796
+
797
+ ctx.logger?.info?.(`[wechat-bot] ready (data=${DATA_DIR}, state=${rt.conn.state})`)
798
+ }