@mindlink-ai/dsh-wechat-bot 1.0.4 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -9
- package/bridge/relay.js +139 -0
- package/client.js +261 -118
- package/index.js +542 -58
- package/package.json +68 -48
package/index.js
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
* 通过微信官方 iLink(ClawBot)通道把个人微信桥接进 DSH:
|
|
5
5
|
* - 扫码登录(二维码链接在侧边栏面板里);长轮询保持会话、刷新 context_token;
|
|
6
6
|
* - Agent 工具:wechat_status / wechat_login / wechat_send / wechat_recent;
|
|
7
|
-
* - 同源 HTTP 路由 /wechat-bot/*
|
|
7
|
+
* - 同源 HTTP 路由 /wechat-bot/* 供侧边栏面板读取状态、触发登录与测试推送;
|
|
8
|
+
* - 入站消息:`/` 开头由插件自己处理,其余转交给「微信专用会话」——该会话的
|
|
9
|
+
* 预设/模型/权限预设都来自 settings(不再随部署默认值漂移),回合内助手文本
|
|
10
|
+
* 逐段回传,长时间静默时回一条进度,整轮结束收尾。
|
|
8
11
|
*
|
|
9
12
|
* 状态与凭证保存在 ~/.dsh/wechat-bot/(可用环境变量 DSH_WECHAT_BOT_DIR 覆盖);
|
|
10
13
|
* 首次启动会尝试从旧版 daily-news/wechat 目录迁移凭证与群/私聊上下文。
|
|
@@ -17,20 +20,31 @@ import path from 'node:path'
|
|
|
17
20
|
import { fileURLToPath } from 'node:url'
|
|
18
21
|
import { getBotQrcode, pollQrcodeStatus, getUpdates, sendText, ILinkError } from './bridge/ilink.js'
|
|
19
22
|
import { renderDigest, chunkByBytes } from './bridge/render.js'
|
|
23
|
+
import { createTurnRelay } from './bridge/relay.js'
|
|
20
24
|
|
|
21
25
|
export const name = 'wechat-bot'
|
|
22
|
-
|
|
26
|
+
// webServer 承载侧边栏面板的状态/登录/推送接口:把它列为依赖,Cordis 会等它就绪后再激活,
|
|
27
|
+
// 否则插件先激活时拿不到 webServer,路由缺失(面板报 404 Not Found)。
|
|
28
|
+
export const inject = ['tools', 'webServer']
|
|
23
29
|
|
|
24
30
|
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
25
31
|
const DATA_DIR = process.env.DSH_WECHAT_BOT_DIR || path.join(os.homedir(), '.dsh', 'wechat-bot')
|
|
26
32
|
const TEXT_LIMIT = 1900
|
|
27
33
|
const RECENT_MAX = 100
|
|
34
|
+
/** 推送失败记录:保留条数与单条内容上限(面板可读,足够容纳一次 3 片推送) */
|
|
35
|
+
const FAILURE_MAX = 50
|
|
36
|
+
const FAILURE_CONTENT_MAX = 4000
|
|
37
|
+
/** settings 结构版本:升级后一次性把旧会话解绑,换成显式配置的专用会话 */
|
|
38
|
+
const BINDING_VERSION = 2
|
|
39
|
+
const DEFAULT_PRESET = 'standard'
|
|
40
|
+
const DEFAULT_PERMISSION_PRESET = 'read-only'
|
|
28
41
|
|
|
29
42
|
export function apply(ctx) {
|
|
30
43
|
const settingsFile = path.join(DATA_DIR, 'settings.json')
|
|
31
44
|
const credFile = path.join(DATA_DIR, 'credentials.json')
|
|
32
45
|
const stateFile = path.join(DATA_DIR, 'state.json')
|
|
33
46
|
const pushLogFile = path.join(DATA_DIR, 'push.log')
|
|
47
|
+
const failureFile = path.join(DATA_DIR, 'push-failures.json')
|
|
34
48
|
const dirs = [DATA_DIR]
|
|
35
49
|
|
|
36
50
|
for (const dir of dirs) fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
@@ -74,6 +88,7 @@ export function apply(ctx) {
|
|
|
74
88
|
}
|
|
75
89
|
|
|
76
90
|
// ---------------------------------------------------------------- settings
|
|
91
|
+
const savedSettings = readJson(settingsFile) || {}
|
|
77
92
|
const settings = {
|
|
78
93
|
mode: 'direct',
|
|
79
94
|
targetUserId: '',
|
|
@@ -83,8 +98,19 @@ export function apply(ctx) {
|
|
|
83
98
|
chatForward: true,
|
|
84
99
|
chatSessionId: '',
|
|
85
100
|
workspaceCwd: os.homedir(),
|
|
86
|
-
|
|
101
|
+
// 微信专用会话:显式钉住预设 / 模型 / 权限预设,不随部署默认值漂移
|
|
102
|
+
agentPreset: DEFAULT_PRESET,
|
|
103
|
+
model: { provider: '', model: '', reasoningEffort: '' },
|
|
104
|
+
permissionPreset: DEFAULT_PERMISSION_PRESET,
|
|
105
|
+
sessionTitle: '微信 bot(专用会话)',
|
|
106
|
+
bindingVersion: 0,
|
|
107
|
+
// 回合内进度回传:stream=每个步骤即时回传;progressEveryMs=静默多久回一条进度
|
|
108
|
+
stream: { enabled: true, progressEveryMs: 25000, minChars: 12, ack: '' },
|
|
109
|
+
...savedSettings,
|
|
87
110
|
}
|
|
111
|
+
// 新增字段用浅合并补齐,老 settings.json 不需要手改
|
|
112
|
+
settings.model = { provider: '', model: '', reasoningEffort: '', ...(savedSettings.model || {}) }
|
|
113
|
+
settings.stream = { enabled: true, progressEveryMs: 25000, minChars: 12, ack: '', ...(savedSettings.stream || {}) }
|
|
88
114
|
const saveSettings = () => {
|
|
89
115
|
try {
|
|
90
116
|
writeJson(settingsFile, settings)
|
|
@@ -93,6 +119,19 @@ export function apply(ctx) {
|
|
|
93
119
|
}
|
|
94
120
|
}
|
|
95
121
|
|
|
122
|
+
// 一次性迁移:把旧版随意新建的会话解绑,下一条微信消息将新建专用会话
|
|
123
|
+
const migrateBinding = () => {
|
|
124
|
+
if ((Number(settings.bindingVersion) || 0) >= BINDING_VERSION) return
|
|
125
|
+
const previous = settings.chatSessionId
|
|
126
|
+
settings.chatSessionId = ''
|
|
127
|
+
settings.bindingVersion = BINDING_VERSION
|
|
128
|
+
saveSettings()
|
|
129
|
+
ctx.logger?.info?.(
|
|
130
|
+
`[wechat-bot] 会话绑定已迁移(v${BINDING_VERSION}):${previous ? `旧会话 ${previous} 不再接收微信消息` : '尚无绑定会话'},下一条微信消息将新建专用会话`,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
migrateBinding()
|
|
134
|
+
|
|
96
135
|
// ---------------------------------------------------------- credentials/state
|
|
97
136
|
const saved = readJson(credFile)
|
|
98
137
|
let creds = saved && saved.token ? saved : null
|
|
@@ -111,10 +150,29 @@ export function apply(ctx) {
|
|
|
111
150
|
lastPush: persisted.lastPush || { at: 0, ok: false, error: '', chunks: 0, chars: 0 },
|
|
112
151
|
recent: [],
|
|
113
152
|
pushLog: [],
|
|
153
|
+
/** 推送失败记录(持久化到 push-failures.json,面板可读) */
|
|
154
|
+
failures: [],
|
|
155
|
+
/** 专用会话实际生效的配置(供面板/排查用) */
|
|
156
|
+
sessionProfile: { sessionId: '', agentPreset: '', model: '', permission: '' },
|
|
157
|
+
permissionPreset: '',
|
|
158
|
+
/** /wechat-bot/* 路由挂载状态(供 /status 与 wechat_status 排查 404) */
|
|
159
|
+
web: { registered: false, attempts: 0, error: '', at: 0 },
|
|
114
160
|
}
|
|
115
161
|
let stops = { poll: new AbortController(), login: 0 }
|
|
116
162
|
let disposed = false
|
|
117
163
|
|
|
164
|
+
// 失败记录跨重启保留:读不到或格式不对时按空列表处理,不影响主流程
|
|
165
|
+
try {
|
|
166
|
+
const persistedFailures = readJson(failureFile)
|
|
167
|
+
if (Array.isArray(persistedFailures)) {
|
|
168
|
+
rt.failures = persistedFailures
|
|
169
|
+
.filter((item) => item && typeof item === 'object' && Number(item.at) > 0)
|
|
170
|
+
.slice(0, FAILURE_MAX)
|
|
171
|
+
}
|
|
172
|
+
} catch (error) {
|
|
173
|
+
ctx.logger?.warn?.(`[wechat-bot] cannot load push failures: ${error?.message ?? error}`)
|
|
174
|
+
}
|
|
175
|
+
|
|
118
176
|
const saveState = () => {
|
|
119
177
|
try {
|
|
120
178
|
writeJson(stateFile, {
|
|
@@ -137,6 +195,112 @@ export function apply(ctx) {
|
|
|
137
195
|
}
|
|
138
196
|
}
|
|
139
197
|
|
|
198
|
+
// ------------------------------------------------- 推送失败记录(面板可读)
|
|
199
|
+
// 只要一次推送失败(未登录 / 连接失效 / 无会话凭证 / 内容为空 / 分片发送失败 /
|
|
200
|
+
// 日报读取失败),就把「哪个智能体、发送内容、发送时间、失败原因」写进本地文件,
|
|
201
|
+
// 侧边栏「微信bot」面板直接展示,不再依赖巡检脚本或自动补推。
|
|
202
|
+
const clipContent = (value) => {
|
|
203
|
+
const text = String(value ?? '')
|
|
204
|
+
if (text.length <= FAILURE_CONTENT_MAX) return { content: text, truncated: false }
|
|
205
|
+
return { content: text.slice(0, FAILURE_CONTENT_MAX), truncated: true }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const saveFailures = () => {
|
|
209
|
+
try {
|
|
210
|
+
writeJson(failureFile, rt.failures)
|
|
211
|
+
} catch (error) {
|
|
212
|
+
ctx.logger?.warn?.(`[wechat-bot] cannot save push failures: ${error?.message ?? error}`)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const recordFailure = (entry) => {
|
|
217
|
+
try {
|
|
218
|
+
const { content, truncated } = clipContent(entry.content)
|
|
219
|
+
const record = {
|
|
220
|
+
id: randomUUID(),
|
|
221
|
+
/** 失败发生时间(用户要看的「发送时间」) */
|
|
222
|
+
at: Date.now(),
|
|
223
|
+
startedAt: entry.startedAt || Date.now(),
|
|
224
|
+
source: entry.source || 'tool',
|
|
225
|
+
agent: entry.agent || { label: '未识别来源' },
|
|
226
|
+
content,
|
|
227
|
+
truncated,
|
|
228
|
+
chars: String(entry.content ?? '').length,
|
|
229
|
+
file: entry.file ? String(entry.file) : '',
|
|
230
|
+
error: entry.error || 'send_failed',
|
|
231
|
+
message: entry.message || '',
|
|
232
|
+
target: entry.target || '',
|
|
233
|
+
chunksSent: Number(entry.chunksSent) || 0,
|
|
234
|
+
}
|
|
235
|
+
rt.failures.unshift(record)
|
|
236
|
+
if (rt.failures.length > FAILURE_MAX) rt.failures.length = FAILURE_MAX
|
|
237
|
+
saveFailures()
|
|
238
|
+
return record
|
|
239
|
+
} catch (error) {
|
|
240
|
+
ctx.logger?.warn?.(`[wechat-bot] cannot record push failure: ${error?.message ?? error}`)
|
|
241
|
+
return null
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** 从工具执行的 Agent 句柄里提取「哪个智能体」:预设、会话与标题 */
|
|
246
|
+
function describeAgent(agent) {
|
|
247
|
+
if (!agent || typeof agent !== 'object') return null
|
|
248
|
+
try {
|
|
249
|
+
const session = agent.session
|
|
250
|
+
const header = session?.header || {}
|
|
251
|
+
let sessionTitle = ''
|
|
252
|
+
try {
|
|
253
|
+
const projections = ctx.get('sessionProjections')
|
|
254
|
+
const snapshot = projections?.snapshot?.(session, ['title'])
|
|
255
|
+
sessionTitle = String(snapshot?.values?.title || '')
|
|
256
|
+
} catch {
|
|
257
|
+
/* 标题只是辅助信息,取不到就留空 */
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
sessionId: String(agent.id || ''),
|
|
261
|
+
presetId: String(header.agentPreset || ''),
|
|
262
|
+
sessionTitle,
|
|
263
|
+
subagent: Boolean(header.parentSession) || header.origin === 'subagent',
|
|
264
|
+
}
|
|
265
|
+
} catch {
|
|
266
|
+
return null
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** 把调用来源解析成面板上可读的「智能体」标签 */
|
|
271
|
+
async function describeOrigin(source, agent) {
|
|
272
|
+
const info = describeAgent(agent)
|
|
273
|
+
if (!info) {
|
|
274
|
+
const fallback =
|
|
275
|
+
source === 'panel' ? '面板手动推送' : source === 'service' ? '其他插件(Host 服务调用)' : '未识别的调用方'
|
|
276
|
+
return { label: fallback, presetId: '', presetName: '', sessionId: '', sessionTitle: '', subagent: false }
|
|
277
|
+
}
|
|
278
|
+
let presetName = ''
|
|
279
|
+
if (info.presetId) {
|
|
280
|
+
try {
|
|
281
|
+
const rows = await listAgentPresets()
|
|
282
|
+
presetName = rows.find((row) => row.id === info.presetId)?.name || ''
|
|
283
|
+
} catch {
|
|
284
|
+
presetName = ''
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const parts = []
|
|
288
|
+
if (presetName && presetName !== info.presetId) parts.push(`${presetName}(${info.presetId})`)
|
|
289
|
+
else if (info.presetId === 'standard') parts.push('默认智能体(standard)')
|
|
290
|
+
else if (info.presetId) parts.push(info.presetId)
|
|
291
|
+
else parts.push('默认智能体')
|
|
292
|
+
if (info.subagent) parts.push('子智能体')
|
|
293
|
+
if (info.sessionTitle) parts.push(`「${info.sessionTitle}」`)
|
|
294
|
+
return {
|
|
295
|
+
label: parts.join(' · '),
|
|
296
|
+
presetId: info.presetId,
|
|
297
|
+
presetName,
|
|
298
|
+
sessionId: info.sessionId,
|
|
299
|
+
sessionTitle: info.sessionTitle,
|
|
300
|
+
subagent: info.subagent,
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
140
304
|
/** 设置当前登录二维码,并生成 GIF data URL(渲染失败则面板回退为链接) */
|
|
141
305
|
function setQr(qr) {
|
|
142
306
|
rt.qr = { url: qr.url, ts: Date.now(), active: true, base: qr.base, dataUrl: renderQrDataUrl(qr.url) }
|
|
@@ -333,16 +497,23 @@ export function apply(ctx) {
|
|
|
333
497
|
return { uid: ids[0], token: rt.directs[ids[0]]?.contextToken || '' }
|
|
334
498
|
}
|
|
335
499
|
|
|
336
|
-
async function pushText(rawText, { source = 'tool' } = {}) {
|
|
337
|
-
|
|
338
|
-
|
|
500
|
+
async function pushText(rawText, { source = 'tool', agent = null, file = '' } = {}) {
|
|
501
|
+
const content = String(rawText ?? '').trim()
|
|
502
|
+
const startedAt = Date.now()
|
|
503
|
+
const origin = await describeOrigin(source, agent)
|
|
504
|
+
const fail = (error, message, extra = {}) => {
|
|
505
|
+
recordFailure({ source, agent: origin, content, startedAt, file, error, message, ...extra })
|
|
506
|
+
return { ok: false, error, message, ...extra }
|
|
507
|
+
}
|
|
508
|
+
if (!rt.creds) return fail('not_logged_in', '微信 bot 尚未登录,请先在面板中扫码登录')
|
|
509
|
+
if (rt.conn.state !== 'online') return fail('not_online', `连接状态:${rt.conn.state}(${rt.conn.error || '未就绪'})`)
|
|
339
510
|
const target = pickTarget()
|
|
340
511
|
if (!target?.token) {
|
|
341
|
-
return
|
|
512
|
+
return fail('no_context', '还没有可推送的会话凭证:请在微信里给机器人发一条任意消息,让 bot 记录 context_token')
|
|
342
513
|
}
|
|
343
514
|
const maxChars = Math.max(200, Number(settings.maxChars) || TEXT_LIMIT)
|
|
344
|
-
const chunks = chunkByBytes(
|
|
345
|
-
if (!chunks[0]) return
|
|
515
|
+
const chunks = chunkByBytes(content, maxChars).slice(0, 3)
|
|
516
|
+
if (!chunks[0]) return fail('empty', '没有可发送的内容')
|
|
346
517
|
const sent = []
|
|
347
518
|
for (const chunk of chunks) {
|
|
348
519
|
try {
|
|
@@ -351,11 +522,23 @@ export function apply(ctx) {
|
|
|
351
522
|
rt.counters.sent += 1
|
|
352
523
|
} catch (error) {
|
|
353
524
|
rt.counters.failed += 1
|
|
354
|
-
|
|
525
|
+
const message = error?.message || String(error)
|
|
526
|
+
rt.lastPush = { at: Date.now(), ok: false, error: message, chunks: sent.length, chars: sent.reduce((a, b) => a + b, 0) }
|
|
355
527
|
if (error?.code === 'session-expired') setConn('expired', '微信连接已失效(-14),请重新扫码登录')
|
|
356
528
|
saveState()
|
|
357
|
-
pushAudit({ ok: false, source, target: target.uid, error:
|
|
358
|
-
|
|
529
|
+
pushAudit({ ok: false, source, target: target.uid, error: message })
|
|
530
|
+
recordFailure({
|
|
531
|
+
source,
|
|
532
|
+
agent: origin,
|
|
533
|
+
content,
|
|
534
|
+
startedAt,
|
|
535
|
+
file,
|
|
536
|
+
error: error?.code || 'send_failed',
|
|
537
|
+
message,
|
|
538
|
+
target: target.uid,
|
|
539
|
+
chunksSent: sent.length,
|
|
540
|
+
})
|
|
541
|
+
return { ok: false, error: error?.code || 'send_failed', message, chunks: sent.length }
|
|
359
542
|
}
|
|
360
543
|
if (chunk !== chunks[chunks.length - 1]) await new Promise((resolve) => setTimeout(resolve, 1200))
|
|
361
544
|
}
|
|
@@ -367,7 +550,6 @@ export function apply(ctx) {
|
|
|
367
550
|
|
|
368
551
|
// ------------------------------------------------------- 微信 ⇄ DSH 会话转发
|
|
369
552
|
const chatPending = []
|
|
370
|
-
let chatAccum = ''
|
|
371
553
|
|
|
372
554
|
/** 直接回复到当前微信会话(使用入站消息带来的最新 context_token) */
|
|
373
555
|
async function sendToWeChat(uid, token, body) {
|
|
@@ -382,6 +564,16 @@ export function apply(ctx) {
|
|
|
382
564
|
return { ok: true, chunks: chunks.length }
|
|
383
565
|
}
|
|
384
566
|
|
|
567
|
+
// 回合内进度回传:每个模型步骤的文本即时发;长时间静默时回一条「仍在处理」
|
|
568
|
+
const chatRelay = createTurnRelay({
|
|
569
|
+
send: (text, target) => sendToWeChat(target.uid, target.token, text),
|
|
570
|
+
stream: Boolean(settings.stream.enabled),
|
|
571
|
+
ack: String(settings.stream.ack || ''),
|
|
572
|
+
progressEveryMs: Math.max(0, Number(settings.stream.progressEveryMs) || 0),
|
|
573
|
+
minChars: Math.max(1, Number(settings.stream.minChars) || 1),
|
|
574
|
+
onError: (error) => ctx.logger?.warn?.(`[wechat-bot] chat reply failed: ${error?.message ?? error}`),
|
|
575
|
+
})
|
|
576
|
+
|
|
385
577
|
const helpText = () =>
|
|
386
578
|
[
|
|
387
579
|
'可用指令:',
|
|
@@ -396,17 +588,195 @@ export function apply(ctx) {
|
|
|
396
588
|
'其余消息会转交给 DSH 会话处理,处理结果自动回传到微信。',
|
|
397
589
|
].join('\n')
|
|
398
590
|
|
|
591
|
+
// ---- Agent 预设:名册读取 + 面板切换 --------------------------------------
|
|
592
|
+
const presetCache = { at: 0, rows: [] }
|
|
593
|
+
|
|
594
|
+
/** 读取部署已注册的 Agent 预设名册(5s 缓存,供面板轮询复用) */
|
|
595
|
+
async function listAgentPresets(force = false) {
|
|
596
|
+
const now = Date.now()
|
|
597
|
+
if (!force && presetCache.at && now - presetCache.at < 5000) return presetCache.rows
|
|
598
|
+
const registry = ctx.get('agentPresets')
|
|
599
|
+
if (!registry) return presetCache.rows
|
|
600
|
+
let rows = []
|
|
601
|
+
try {
|
|
602
|
+
const roster = (await registry.remoteExportList?.())?.presets
|
|
603
|
+
if (Array.isArray(roster)) {
|
|
604
|
+
rows = roster.map((item) => ({
|
|
605
|
+
id: String(item?.id ?? ''),
|
|
606
|
+
name: String(item?.name ?? ''),
|
|
607
|
+
description: String(item?.description ?? ''),
|
|
608
|
+
isDefault: Boolean(item?.isDefault),
|
|
609
|
+
broken: String(item?.broken ?? ''),
|
|
610
|
+
}))
|
|
611
|
+
} else {
|
|
612
|
+
const list = (await registry.list?.()) || []
|
|
613
|
+
rows = list.map((item) => ({
|
|
614
|
+
id: String(item?.id ?? ''),
|
|
615
|
+
name: String(item?.name ?? ''),
|
|
616
|
+
description: String(item?.description ?? ''),
|
|
617
|
+
isDefault: false,
|
|
618
|
+
broken: String(item?.broken ?? ''),
|
|
619
|
+
}))
|
|
620
|
+
}
|
|
621
|
+
} catch (error) {
|
|
622
|
+
ctx.logger?.warn?.(`[wechat-bot] 读取 Agent 预设名册失败:${error?.message ?? error}`)
|
|
623
|
+
return presetCache.rows
|
|
624
|
+
}
|
|
625
|
+
presetCache.at = now
|
|
626
|
+
presetCache.rows = rows.filter((row) => row.id)
|
|
627
|
+
return presetCache.rows
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** 校验预设 id:不存在或加载失败时回退到默认预设,避免建会话直接失败 */
|
|
631
|
+
async function resolveAgentPreset(preferred) {
|
|
632
|
+
if (!preferred) return ''
|
|
633
|
+
const rows = await listAgentPresets()
|
|
634
|
+
const usable = rows.filter((row) => !row.broken)
|
|
635
|
+
if (usable.length && !usable.some((row) => row.id === preferred)) {
|
|
636
|
+
const fallback = usable.find((row) => row.id === DEFAULT_PRESET)?.id || ''
|
|
637
|
+
ctx.logger?.warn?.(
|
|
638
|
+
`[wechat-bot] 预设 ${preferred} 不可用(可用:${usable.map((row) => row.id).join(', ')}),回退为 ${fallback || '部署默认'}`,
|
|
639
|
+
)
|
|
640
|
+
return fallback
|
|
641
|
+
}
|
|
642
|
+
return preferred
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** 面板切换回答预设:更新 settings 并解绑旧会话,下一条微信消息按新预设重建 */
|
|
646
|
+
async function switchAgentPreset(requested) {
|
|
647
|
+
const id = String(requested ?? '').trim()
|
|
648
|
+
const rows = await listAgentPresets(true)
|
|
649
|
+
if (id) {
|
|
650
|
+
const row = rows.find((item) => item.id === id)
|
|
651
|
+
if (!row) return { ok: false, error: 'unknown_preset', message: `未知预设:${id}`, presets: rows }
|
|
652
|
+
if (row.broken) return { ok: false, error: 'broken_preset', message: `预设 ${id} 加载失败:${row.broken}`, presets: rows }
|
|
653
|
+
}
|
|
654
|
+
const previous = settings.agentPreset || ''
|
|
655
|
+
if (previous === id && !settings.chatSessionId) return { ok: true, preset: id, previous, rebind: false, unchanged: true }
|
|
656
|
+
settings.agentPreset = id
|
|
657
|
+
const rebind = Boolean(settings.chatSessionId)
|
|
658
|
+
settings.chatSessionId = ''
|
|
659
|
+
rt.sessionProfile = { sessionId: '', agentPreset: id, model: '', permission: '' }
|
|
660
|
+
rt.permissionPreset = ''
|
|
661
|
+
saveSettings()
|
|
662
|
+
ctx.logger?.info?.(
|
|
663
|
+
`[wechat-bot] 回答预设切换:${id || '跟随部署默认'}(原 ${previous || '跟随默认'}${rebind ? ',旧会话已解绑,下一条微信消息重建' : ''})`,
|
|
664
|
+
)
|
|
665
|
+
return { ok: true, preset: id, previous, rebind }
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** 从部署已注册的权限预设里挑一个可用的;都没有就沿用部署默认 */
|
|
669
|
+
function resolvePermissionPreset() {
|
|
670
|
+
const wanted = String(settings.permissionPreset || '').trim()
|
|
671
|
+
if (!wanted) return ''
|
|
672
|
+
const pp = ctx.get('permissionPresets')
|
|
673
|
+
if (!pp) return ''
|
|
674
|
+
for (const name of [wanted, 'workspace-write']) {
|
|
675
|
+
try {
|
|
676
|
+
const known = pp.resolve?.(name) ?? pp.optionOf?.(name)
|
|
677
|
+
if (known) return name
|
|
678
|
+
} catch {
|
|
679
|
+
/* 该名称未注册,试下一个 */
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
ctx.logger?.warn?.(`[wechat-bot] 权限预设 ${wanted} 不可用,沿用部署默认权限`)
|
|
683
|
+
return ''
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** 把权限预设套到这个会话的 agent 上(需要 agent 已经存在) */
|
|
687
|
+
function applyPermissionPreset(agent) {
|
|
688
|
+
if (!agent) return ''
|
|
689
|
+
const name = rt.permissionPreset || resolvePermissionPreset()
|
|
690
|
+
if (!name) return ''
|
|
691
|
+
const pp = ctx.get('permissionPresets')
|
|
692
|
+
if (!pp || typeof pp.set !== 'function') return ''
|
|
693
|
+
try {
|
|
694
|
+
pp.set(agent, name)
|
|
695
|
+
rt.permissionPreset = name
|
|
696
|
+
rt.sessionProfile.permission = name
|
|
697
|
+
ctx.logger?.info?.(`[wechat-bot] 微信专用会话权限预设:${name}`)
|
|
698
|
+
return name
|
|
699
|
+
} catch (error) {
|
|
700
|
+
ctx.logger?.warn?.(`[wechat-bot] 设置权限预设 ${name} 失败:${error?.message ?? error}`)
|
|
701
|
+
return ''
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** 新建会话后套用模型与标题;失败只告警,不阻断消息流转 */
|
|
706
|
+
async function applySessionProfile(sessionId) {
|
|
707
|
+
const sessions = ctx.get('sessionController')
|
|
708
|
+
if (!sessions || !sessionId) return
|
|
709
|
+
const model = settings.model || {}
|
|
710
|
+
if (model.provider && model.model && typeof sessions.selectModel === 'function') {
|
|
711
|
+
try {
|
|
712
|
+
const request = { sessionId, provider: model.provider, model: model.model }
|
|
713
|
+
if (model.reasoningEffort) request.reasoningEffort = model.reasoningEffort
|
|
714
|
+
await sessions.selectModel(request)
|
|
715
|
+
rt.sessionProfile.model = `${model.provider}/${model.model}${model.reasoningEffort ? `@${model.reasoningEffort}` : ''}`
|
|
716
|
+
ctx.logger?.info?.(`[wechat-bot] 微信专用会话模型:${rt.sessionProfile.model}`)
|
|
717
|
+
} catch (error) {
|
|
718
|
+
ctx.logger?.warn?.(`[wechat-bot] 指定模型失败,沿用会话默认:${error?.message ?? error}`)
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (settings.sessionTitle && typeof sessions.rename === 'function') {
|
|
722
|
+
try {
|
|
723
|
+
await sessions.rename({ sessionId, title: String(settings.sessionTitle) })
|
|
724
|
+
} catch (error) {
|
|
725
|
+
ctx.logger?.warn?.(`[wechat-bot] 重命名会话失败:${error?.message ?? error}`)
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** 首次需要时创建微信专用会话(预设/模型/权限都来自 settings) */
|
|
399
731
|
async function ensureChatSession() {
|
|
400
732
|
if (settings.chatSessionId) return settings.chatSessionId
|
|
401
733
|
const sessions = ctx.get('sessionController')
|
|
402
734
|
if (!sessions) return ''
|
|
403
|
-
|
|
735
|
+
// 模型未显式配置时,固化当前部署默认值,之后不随默认值漂移
|
|
736
|
+
if (!settings.model.provider || !settings.model.model) {
|
|
737
|
+
try {
|
|
738
|
+
const current = ctx.get('agentDefaultModel')?.currentSelection?.()
|
|
739
|
+
if (current?.provider && current?.model) {
|
|
740
|
+
settings.model = {
|
|
741
|
+
provider: current.provider,
|
|
742
|
+
model: current.model,
|
|
743
|
+
reasoningEffort: current.reasoningEffort || '',
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
} catch (error) {
|
|
747
|
+
ctx.logger?.warn?.(`[wechat-bot] 读取默认模型失败:${error?.message ?? error}`)
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
// 未指定预设时跟随部署默认(不传 agentPreset);指定时先在名册里校验
|
|
751
|
+
const configuredPreset = String(settings.agentPreset || '')
|
|
752
|
+
const preset = configuredPreset ? await resolveAgentPreset(configuredPreset) : ''
|
|
753
|
+
const request = { cwd: settings.workspaceCwd }
|
|
754
|
+
if (preset) request.agentPreset = preset
|
|
755
|
+
let created = null
|
|
756
|
+
try {
|
|
757
|
+
created = await sessions.create(request)
|
|
758
|
+
} catch (error) {
|
|
759
|
+
if (!preset) throw error
|
|
760
|
+
ctx.logger?.warn?.(`[wechat-bot] 用预设 ${preset} 建会话失败,回退默认预设:${error?.message ?? error}`)
|
|
761
|
+
created = await sessions.create({ cwd: settings.workspaceCwd })
|
|
762
|
+
}
|
|
404
763
|
settings.chatSessionId = created?.sessionId || ''
|
|
405
|
-
if (settings.chatSessionId)
|
|
764
|
+
if (!settings.chatSessionId) return ''
|
|
765
|
+
rt.sessionProfile = {
|
|
766
|
+
sessionId: settings.chatSessionId,
|
|
767
|
+
agentPreset: created?.agentPreset || preset || 'default',
|
|
768
|
+
model: '',
|
|
769
|
+
permission: '',
|
|
770
|
+
}
|
|
771
|
+
saveSettings()
|
|
772
|
+
await applySessionProfile(settings.chatSessionId)
|
|
773
|
+
ctx.logger?.info?.(
|
|
774
|
+
`[wechat-bot] 已创建微信专用会话 ${settings.chatSessionId}(preset=${rt.sessionProfile.agentPreset})`,
|
|
775
|
+
)
|
|
406
776
|
return settings.chatSessionId
|
|
407
777
|
}
|
|
408
778
|
|
|
409
|
-
/** 把一条微信消息转交给 DSH
|
|
779
|
+
/** 把一条微信消息转交给 DSH 会话;回合内的回传由 chatRelay 负责 */
|
|
410
780
|
async function forwardToChat(text, uid, token) {
|
|
411
781
|
const sessions = ctx.get('sessionController')
|
|
412
782
|
if (!sessions) {
|
|
@@ -433,32 +803,22 @@ export function apply(ctx) {
|
|
|
433
803
|
}
|
|
434
804
|
}
|
|
435
805
|
|
|
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
806
|
async function handleCommand(text, uid, token) {
|
|
452
807
|
const [cmd] = String(text).split(/\s+/)
|
|
453
808
|
const name = (cmd || '').toLowerCase()
|
|
454
809
|
try {
|
|
455
810
|
if (name === '/help') return await sendToWeChat(uid, token, helpText())
|
|
456
811
|
if (name === '/status') {
|
|
812
|
+
const presetRows = await listAgentPresets()
|
|
457
813
|
const body = [
|
|
458
814
|
`连接:${rt.conn.state}${rt.conn.error ? `(${rt.conn.error})` : ''}`,
|
|
459
815
|
`bot:${rt.account.botId || '—'}`,
|
|
460
816
|
`计数:收 ${rt.counters.received} / 发 ${rt.counters.sent} / 失败 ${rt.counters.failed}`,
|
|
461
817
|
`最近推送:${rt.lastPush.at ? `${new Date(rt.lastPush.at).toLocaleString()} ${rt.lastPush.ok ? '成功' : '失败'}` : '无'}`,
|
|
818
|
+
`专用会话:${settings.chatSessionId || '未建立(下一条消息创建)'}`,
|
|
819
|
+
`预设 ${rt.sessionProfile.agentPreset || settings.agentPreset || '跟随部署默认'} · 模型 ${rt.sessionProfile.model || '会话默认'} · 权限 ${rt.sessionProfile.permission || rt.permissionPreset || '部署默认'}`,
|
|
820
|
+
`可用预设:${presetRows.length ? presetRows.map((row) => `${row.id}${row.isDefault ? '*' : ''}`).join(' / ') : '不可用'}`,
|
|
821
|
+
`进度回传:${settings.stream.enabled ? '按步骤流式' : '整轮一次性'}${Number(settings.stream.progressEveryMs) > 0 ? `(静默 ${Math.round(Number(settings.stream.progressEveryMs) / 1000)}s 回进度)` : ''}`,
|
|
462
822
|
].join('\n')
|
|
463
823
|
return await sendToWeChat(uid, token, body)
|
|
464
824
|
}
|
|
@@ -478,9 +838,11 @@ export function apply(ctx) {
|
|
|
478
838
|
if (name === '/new') {
|
|
479
839
|
settings.chatSessionId = ''
|
|
480
840
|
saveSettings()
|
|
481
|
-
|
|
841
|
+
chatRelay.abort()
|
|
482
842
|
chatPending.length = 0
|
|
483
|
-
|
|
843
|
+
rt.sessionProfile = { sessionId: '', agentPreset: '', model: '', permission: '' }
|
|
844
|
+
rt.permissionPreset = ''
|
|
845
|
+
return await sendToWeChat(uid, token, '已重置对话会话,下一条消息将新建 DSH 专用会话')
|
|
484
846
|
}
|
|
485
847
|
return await sendToWeChat(uid, token, `未知指令:${cmd}\n\n${helpText()}`)
|
|
486
848
|
} catch (error) {
|
|
@@ -496,6 +858,8 @@ export function apply(ctx) {
|
|
|
496
858
|
account: { ...rt.account, userIdConfigured: settings.targetUserId === rt.account.userId },
|
|
497
859
|
qr: { url: rt.qr.url, ts: rt.qr.ts, active: rt.qr.active, hasQr: Boolean(rt.qr.dataUrl), dataUrl: rt.qr.dataUrl },
|
|
498
860
|
counters: { ...rt.counters },
|
|
861
|
+
/** 推送失败记录条数(完整记录走 GET /wechat-bot/failures) */
|
|
862
|
+
failureCount: rt.failures.length,
|
|
499
863
|
lastPush: { ...rt.lastPush },
|
|
500
864
|
recent: rt.recent.slice(-20),
|
|
501
865
|
service: { name: 'wechatBot', methods: ['status', 'send', 'sendFile', 'sendDigest', 'login', 'recent'] },
|
|
@@ -506,17 +870,46 @@ export function apply(ctx) {
|
|
|
506
870
|
targetUserId: settings.targetUserId,
|
|
507
871
|
chatForward: Boolean(settings.chatForward),
|
|
508
872
|
chatSessionId: settings.chatSessionId,
|
|
873
|
+
agentPreset: settings.agentPreset,
|
|
874
|
+
permissionPreset: settings.permissionPreset,
|
|
875
|
+
model: settings.model,
|
|
876
|
+
stream: settings.stream,
|
|
877
|
+
bindingVersion: settings.bindingVersion,
|
|
878
|
+
},
|
|
879
|
+
// 专用会话:实际生效的预设/模型/权限(建会话后才有值)
|
|
880
|
+
session: {
|
|
881
|
+
id: settings.chatSessionId,
|
|
882
|
+
agentPreset: rt.sessionProfile.agentPreset,
|
|
883
|
+
model: rt.sessionProfile.model,
|
|
884
|
+
permission: rt.sessionProfile.permission || rt.permissionPreset || '',
|
|
885
|
+
cwd: settings.workspaceCwd,
|
|
509
886
|
},
|
|
887
|
+
// 回答预设:configured 为空表示跟随 DSH 部署默认
|
|
888
|
+
preset: {
|
|
889
|
+
configured: settings.agentPreset || '',
|
|
890
|
+
resolved: rt.sessionProfile.agentPreset || '',
|
|
891
|
+
followDefault: !settings.agentPreset,
|
|
892
|
+
},
|
|
893
|
+
// 部署当前注册的 Agent 预设名册(面板下拉用;服务不可用时为空数组)
|
|
894
|
+
presets: presetCache.rows,
|
|
895
|
+
// 面板状态接口挂载情况:registered=false 时侧边栏会报 404
|
|
896
|
+
web: { ...rt.web },
|
|
510
897
|
updatedAt: Date.now(),
|
|
511
898
|
}
|
|
512
899
|
}
|
|
513
900
|
|
|
514
|
-
function pushFromFile(filePath) {
|
|
901
|
+
async function pushFromFile(filePath, { agent = null } = {}) {
|
|
902
|
+
const file = String(filePath ?? '')
|
|
903
|
+
let raw
|
|
515
904
|
try {
|
|
516
|
-
|
|
905
|
+
raw = renderDigest(fs.readFileSync(file, 'utf8'))
|
|
517
906
|
} catch (error) {
|
|
518
|
-
|
|
907
|
+
const message = `读取日报失败:${error?.message ?? error}`
|
|
908
|
+
const origin = await describeOrigin('file', agent)
|
|
909
|
+
recordFailure({ source: 'file', agent: origin, content: file, file, startedAt: Date.now(), error: 'read_failed', message })
|
|
910
|
+
return { ok: false, error: 'read_failed', message }
|
|
519
911
|
}
|
|
912
|
+
return pushText(raw, { source: 'file', agent, file })
|
|
520
913
|
}
|
|
521
914
|
|
|
522
915
|
// -------------------------------------------------------------------- tools
|
|
@@ -529,6 +922,7 @@ export function apply(ctx) {
|
|
|
529
922
|
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
530
923
|
output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => textResult(value) },
|
|
531
924
|
async execute() {
|
|
925
|
+
await listAgentPresets()
|
|
532
926
|
return buildState()
|
|
533
927
|
},
|
|
534
928
|
},
|
|
@@ -578,10 +972,11 @@ export function apply(ctx) {
|
|
|
578
972
|
output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => textResult(value) },
|
|
579
973
|
timeoutMs: 40000,
|
|
580
974
|
isConcurrencySafe: () => false,
|
|
581
|
-
async execute(args) {
|
|
975
|
+
async execute(args, exec) {
|
|
976
|
+
const agent = exec?.agent || null
|
|
582
977
|
const file = String(args?.file ?? '').trim()
|
|
583
|
-
if (file) return pushFromFile(file)
|
|
584
|
-
return pushText(String(args?.text ?? '').trim(), { source: 'tool' })
|
|
978
|
+
if (file) return pushFromFile(file, { agent })
|
|
979
|
+
return pushText(String(args?.text ?? '').trim(), { source: 'tool', agent })
|
|
585
980
|
},
|
|
586
981
|
},
|
|
587
982
|
{
|
|
@@ -606,11 +1001,14 @@ export function apply(ctx) {
|
|
|
606
1001
|
// 其他插件声明 inject: ['wechatBot'] 后即可 ctx.get('wechatBot') 使用:
|
|
607
1002
|
// api.status() / api.send(text) / api.sendFile(mdPath) / api.sendDigest(mdPath) / api.login(action) / api.recent(limit)
|
|
608
1003
|
const api = {
|
|
609
|
-
version: '1.
|
|
1004
|
+
version: '1.3.0',
|
|
610
1005
|
status: () => buildState(),
|
|
611
|
-
send: (text, options = {}) =>
|
|
612
|
-
|
|
613
|
-
|
|
1006
|
+
send: (text, options = {}) =>
|
|
1007
|
+
pushText(String(text ?? ''), { source: options.source || 'service', agent: options.agent || null }),
|
|
1008
|
+
sendFile: (filePath, options = {}) => pushFromFile(filePath, { agent: options?.agent || null }),
|
|
1009
|
+
sendDigest: (filePath, options = {}) => pushFromFile(filePath, { agent: options?.agent || null }),
|
|
1010
|
+
/** 推送失败记录(面板同源,最近 FAILURE_MAX 条) */
|
|
1011
|
+
failures: (limit = FAILURE_MAX) => rt.failures.slice(0, Math.max(1, Math.min(FAILURE_MAX, Number(limit) || FAILURE_MAX))),
|
|
614
1012
|
login: async (action = 'start') => {
|
|
615
1013
|
if (action === 'logout') return logout()
|
|
616
1014
|
if (action === 'cancel') {
|
|
@@ -634,8 +1032,9 @@ export function apply(ctx) {
|
|
|
634
1032
|
}
|
|
635
1033
|
|
|
636
1034
|
// ---------------------------------------------------------------- web routes
|
|
637
|
-
|
|
638
|
-
|
|
1035
|
+
// webServer 由 web-startup 行提供,插件激活顺序并不保证;除了在 inject 里声明依赖,
|
|
1036
|
+
// 这里再做一次兜底重试,避免插件先于 webServer 激活时路由永久缺失(面板会报 404)。
|
|
1037
|
+
function mountWebRoutes(web) {
|
|
639
1038
|
const origin = () => {
|
|
640
1039
|
try {
|
|
641
1040
|
return web.getOrigin?.() || ''
|
|
@@ -681,7 +1080,15 @@ pre{background:#f5f5f5;padding:10px;border-radius:8px;overflow:auto;max-height:4
|
|
|
681
1080
|
try {
|
|
682
1081
|
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
683
1082
|
const method = (req.method || 'GET').toUpperCase()
|
|
684
|
-
if (method === 'GET' && url.pathname === '/wechat-bot/state')
|
|
1083
|
+
if (method === 'GET' && url.pathname === '/wechat-bot/state') {
|
|
1084
|
+
await listAgentPresets()
|
|
1085
|
+
return sendJson(res, buildState())
|
|
1086
|
+
}
|
|
1087
|
+
if (method === 'GET' && url.pathname === '/wechat-bot/failures') {
|
|
1088
|
+
const requested = Number(url.searchParams.get('limit'))
|
|
1089
|
+
const limit = Math.max(1, Math.min(FAILURE_MAX, Number.isFinite(requested) && requested > 0 ? requested : FAILURE_MAX))
|
|
1090
|
+
return sendJson(res, { ok: true, total: rt.failures.length, items: rt.failures.slice(0, limit) })
|
|
1091
|
+
}
|
|
685
1092
|
if (method === 'GET' && url.pathname === '/wechat-bot/qr.png') {
|
|
686
1093
|
if (!rt.qr.dataUrl) {
|
|
687
1094
|
res.writeHead(404, { 'cache-control': 'no-store' })
|
|
@@ -726,11 +1133,28 @@ pre{background:#f5f5f5;padding:10px;border-radius:8px;overflow:auto;max-height:4
|
|
|
726
1133
|
const result = await beginLogin()
|
|
727
1134
|
return sendJson(res, { ...result, state: buildState() })
|
|
728
1135
|
}
|
|
1136
|
+
if (url.pathname === '/wechat-bot/preset') {
|
|
1137
|
+
const result = await switchAgentPreset(body.id)
|
|
1138
|
+
return sendJson(res, { ...result, state: buildState() }, result.ok === false ? 400 : 200)
|
|
1139
|
+
}
|
|
729
1140
|
if (url.pathname === '/wechat-bot/send') {
|
|
730
1141
|
const text = String(body.text || '').trim()
|
|
731
1142
|
if (!text) return sendJson(res, { ok: false, error: 'text required' }, 400)
|
|
732
1143
|
return sendJson(res, await pushText(text, { source: 'panel' }))
|
|
733
1144
|
}
|
|
1145
|
+
if (url.pathname === '/wechat-bot/failures/clear') {
|
|
1146
|
+
rt.failures = []
|
|
1147
|
+
saveFailures()
|
|
1148
|
+
return sendJson(res, { ok: true, total: 0, state: buildState() })
|
|
1149
|
+
}
|
|
1150
|
+
if (url.pathname === '/wechat-bot/failures/delete') {
|
|
1151
|
+
const id = String(body.id || '')
|
|
1152
|
+
const before = rt.failures.length
|
|
1153
|
+
rt.failures = rt.failures.filter((item) => item.id !== id)
|
|
1154
|
+
if (rt.failures.length === before) return sendJson(res, { ok: false, error: 'not_found' }, 404)
|
|
1155
|
+
saveFailures()
|
|
1156
|
+
return sendJson(res, { ok: true, total: rt.failures.length, state: buildState() })
|
|
1157
|
+
}
|
|
734
1158
|
return sendJson(res, { ok: false, error: 'unknown route' }, 404)
|
|
735
1159
|
}
|
|
736
1160
|
res.writeHead(405, { allow: 'GET, POST', 'content-type': 'text/plain; charset=utf-8' })
|
|
@@ -747,32 +1171,74 @@ pre{background:#f5f5f5;padding:10px;border-radius:8px;overflow:auto;max-height:4
|
|
|
747
1171
|
},
|
|
748
1172
|
}),
|
|
749
1173
|
)
|
|
750
|
-
} else {
|
|
751
|
-
ctx.logger?.warn?.('[wechat-bot] web server unavailable: sidebar panel state endpoint disabled')
|
|
752
1174
|
}
|
|
753
1175
|
|
|
1176
|
+
/** 注册 /wechat-bot/* ;返回是否成功挂载 */
|
|
1177
|
+
function registerWebRoutes() {
|
|
1178
|
+
const attempt = rt.web.attempts + 1
|
|
1179
|
+
const web = ctx.get('webServer')
|
|
1180
|
+
if (!web || typeof web.register !== 'function') {
|
|
1181
|
+
rt.web = { registered: false, attempts: attempt, error: 'webServer 服务尚不可用', at: Date.now() }
|
|
1182
|
+
return false
|
|
1183
|
+
}
|
|
1184
|
+
try {
|
|
1185
|
+
mountWebRoutes(web)
|
|
1186
|
+
rt.web = { registered: true, attempts: attempt, error: '', at: Date.now() }
|
|
1187
|
+
ctx.logger?.info?.('[wechat-bot] 已注册 /wechat-bot 路由')
|
|
1188
|
+
return true
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
rt.web = { registered: false, attempts: attempt, error: error?.message || String(error), at: Date.now() }
|
|
1191
|
+
ctx.logger?.warn?.(`[wechat-bot] 注册 web 路由失败:${rt.web.error}`)
|
|
1192
|
+
return false
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
let webRetryTimer = null
|
|
1197
|
+
const stopWebRetry = () => {
|
|
1198
|
+
if (webRetryTimer) {
|
|
1199
|
+
clearTimeout(webRetryTimer)
|
|
1200
|
+
webRetryTimer = null
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
const scheduleWebRetry = () => {
|
|
1204
|
+
if (disposed || rt.web.registered) return
|
|
1205
|
+
if (rt.web.attempts >= 20) {
|
|
1206
|
+
ctx.logger?.warn?.(
|
|
1207
|
+
`[wechat-bot] webServer 重试 ${rt.web.attempts} 次仍不可用,面板状态接口未启用(${rt.web.error || '未知原因'})`,
|
|
1208
|
+
)
|
|
1209
|
+
return
|
|
1210
|
+
}
|
|
1211
|
+
webRetryTimer = setTimeout(() => {
|
|
1212
|
+
webRetryTimer = null
|
|
1213
|
+
if (disposed || rt.web.registered) return
|
|
1214
|
+
if (registerWebRoutes()) return
|
|
1215
|
+
scheduleWebRetry()
|
|
1216
|
+
}, 500)
|
|
1217
|
+
if (webRetryTimer.unref) webRetryTimer.unref()
|
|
1218
|
+
}
|
|
1219
|
+
if (!registerWebRoutes()) scheduleWebRetry()
|
|
1220
|
+
|
|
754
1221
|
// ------------------------------------------------------------------ lifecycle
|
|
755
|
-
//
|
|
1222
|
+
// 会话事件:turn/start 取出发起消息的目标,assistant/message 增量回传,turn/end 收尾
|
|
756
1223
|
const onSessionEvent = (session, event) => {
|
|
757
1224
|
try {
|
|
758
1225
|
const sid = typeof session === 'string' ? session : session?.id
|
|
759
1226
|
if (!settings.chatSessionId || sid !== settings.chatSessionId) return
|
|
760
1227
|
if (event?.type === 'turn/start') {
|
|
761
|
-
|
|
1228
|
+
chatRelay.begin(chatPending.shift() || null)
|
|
762
1229
|
return
|
|
763
1230
|
}
|
|
764
1231
|
if (event?.type === 'assistant/message') {
|
|
765
1232
|
const content = event?.data?.message?.content
|
|
766
|
-
if (Array.isArray(content))
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
}
|
|
1233
|
+
if (!Array.isArray(content)) return
|
|
1234
|
+
const text = content
|
|
1235
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
1236
|
+
.map((block) => block.text)
|
|
1237
|
+
.join('')
|
|
1238
|
+
if (text) chatRelay.push(text)
|
|
773
1239
|
return
|
|
774
1240
|
}
|
|
775
|
-
if (event?.type === 'turn/end')
|
|
1241
|
+
if (event?.type === 'turn/end') chatRelay.end()
|
|
776
1242
|
} catch (error) {
|
|
777
1243
|
ctx.logger?.warn?.(`[wechat-bot] session event handler failed: ${error?.message ?? error}`)
|
|
778
1244
|
}
|
|
@@ -783,12 +1249,30 @@ pre{background:#f5f5f5;padding:10px;border-radius:8px;overflow:auto;max-height:4
|
|
|
783
1249
|
ctx.logger?.warn?.(`[wechat-bot] session/event subscription unavailable: ${error?.message ?? error}`)
|
|
784
1250
|
}
|
|
785
1251
|
|
|
1252
|
+
// 专用会话的 agent 起来时套用权限预设(权限 API 需要活的 agent 句柄)
|
|
1253
|
+
const onAgentCreated = (payload) => {
|
|
1254
|
+
try {
|
|
1255
|
+
const agent = payload?.agent
|
|
1256
|
+
if (!agent || !settings.chatSessionId || agent.id !== settings.chatSessionId) return
|
|
1257
|
+
applyPermissionPreset(agent)
|
|
1258
|
+
} catch (error) {
|
|
1259
|
+
ctx.logger?.warn?.(`[wechat-bot] agent/created handler failed: ${error?.message ?? error}`)
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
try {
|
|
1263
|
+
ctx.effect(() => ctx.on('agent/created', onAgentCreated))
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
ctx.logger?.warn?.(`[wechat-bot] agent/created subscription unavailable: ${error?.message ?? error}`)
|
|
1266
|
+
}
|
|
1267
|
+
|
|
786
1268
|
ctx.effect(() => {
|
|
787
1269
|
if (settings.autoStart && rt.creds) pollLoop()
|
|
788
1270
|
return () => {
|
|
789
1271
|
disposed = true
|
|
790
1272
|
rt.loginGen = 0
|
|
791
1273
|
stops.poll.abort()
|
|
1274
|
+
stopWebRetry()
|
|
1275
|
+
chatRelay.abort()
|
|
792
1276
|
for (const tool of tools) void tool
|
|
793
1277
|
saveState()
|
|
794
1278
|
}
|