dsh-plugin-dingtalk-bridge 0.0.0-stage → 0.3.3
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/LICENSE +21 -0
- package/README.md +183 -2
- package/client.js +2519 -0
- package/cordis.patch.yml +23 -0
- package/docs/images/auth-device.png +0 -0
- package/docs/images/auth-loopback.png +0 -0
- package/docs/images/auth-qr.png +0 -0
- package/docs/images/confirm-modal.png +0 -0
- package/docs/images/duplicate-hint.png +0 -0
- package/docs/images/group-at-reply.png +0 -0
- package/docs/images/help-view.png +0 -0
- package/docs/images/icon-source.png +0 -0
- package/docs/images/icon.png +0 -0
- package/docs/images/inbox-panel.png +0 -0
- package/docs/images/inbox-real.png +0 -0
- package/docs/images/settings.png +0 -0
- package/docs/images/sources-collapsed.png +0 -0
- package/docs/images/sources-expanded.png +0 -0
- package/docs/images/window-setting.png +0 -0
- package/docs//344/275/277/347/224/250/350/257/264/346/230/216.md +1841 -0
- package/icon-128.png +0 -0
- package/icon-64.png +0 -0
- package/icon.png +0 -0
- package/icon.svg +6 -0
- package/index.js +37 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +78 -4
- package/src/host/config.js +147 -0
- package/src/host/dws.js +277 -0
- package/src/host/service.js +2352 -0
- package/src/host/suggest.js +307 -0
|
@@ -0,0 +1,2352 @@
|
|
|
1
|
+
import { readFile, writeFile, rename, mkdir, unlink, appendFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { join, dirname } from 'node:path'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
describeFailure,
|
|
8
|
+
killTree,
|
|
9
|
+
parseDeviceFlow,
|
|
10
|
+
parseLooseJson,
|
|
11
|
+
runDws,
|
|
12
|
+
spawnDws,
|
|
13
|
+
toText,
|
|
14
|
+
createLineReader,
|
|
15
|
+
} from './dws.js'
|
|
16
|
+
import QRCode from 'qrcode'
|
|
17
|
+
|
|
18
|
+
import { buildSuggestPrompt, generateSuggestion, formatClock } from './suggest.js'
|
|
19
|
+
|
|
20
|
+
export const ROUTE_PREFIX = '/api/dingtalk-bridge'
|
|
21
|
+
/** 每次改动宿主行为就换个标记:界面与 http-debug.log 都会带上,用来确认「跑的是新代码」。 */
|
|
22
|
+
export const HOST_BUILD = '0.3.3-20261117T1145'
|
|
23
|
+
|
|
24
|
+
/** 私信(单聊)全部消息。 */
|
|
25
|
+
const O2O_KEY = 'user_im_message_receive_o2o_all'
|
|
26
|
+
/** 群聊中 @ 我的消息。 */
|
|
27
|
+
const AT_KEY = 'user_im_message_receive_at'
|
|
28
|
+
|
|
29
|
+
const MAX_SEEN = 4000
|
|
30
|
+
const SEEN_TTL = 10 * 60 * 1000
|
|
31
|
+
const HEALTH_INTERVAL = 5 * 60 * 1000
|
|
32
|
+
const MIN_STABLE_MS = 30 * 1000
|
|
33
|
+
const SUGGEST_CONCURRENCY = 2
|
|
34
|
+
const BODY_LIMIT = 64 * 1024
|
|
35
|
+
|
|
36
|
+
function asBool(value, fallback) {
|
|
37
|
+
return typeof value === 'boolean' ? value : fallback
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function asNumber(value, fallback, min, max) {
|
|
41
|
+
const number = typeof value === 'number' ? value : Number.parseFloat(String(value ?? ''))
|
|
42
|
+
if (!Number.isFinite(number)) return fallback
|
|
43
|
+
return Math.min(max, Math.max(min, number))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function asString(value, fallback) {
|
|
47
|
+
return typeof value === 'string' ? value : fallback
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function asStringArray(value) {
|
|
51
|
+
if (!Array.isArray(value)) return []
|
|
52
|
+
return value.map((item) => String(item ?? '').trim()).filter((item) => item !== '')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 时间戳归一化为毫秒:支持秒/毫秒数字与「2026-11-14 11:31:27」这类日期字符串。 */
|
|
56
|
+
function normalizeTimestamp(value) {
|
|
57
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
58
|
+
if (text !== '' && !/^\d+(?:\.\d+)?$/.test(text)) {
|
|
59
|
+
const parsed = Date.parse(text.replace(' ', 'T'))
|
|
60
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : Date.now()
|
|
61
|
+
}
|
|
62
|
+
const number = typeof value === 'number' ? value : Number.parseFloat(String(value ?? ''))
|
|
63
|
+
if (!Number.isFinite(number) || number <= 0) return Date.now()
|
|
64
|
+
return number < 1e11 ? Math.round(number * 1000) : Math.round(number)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const EARLIEST_PLAUSIBLE = Date.UTC(2020, 0, 1)
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 修正历史存档里的脏时间戳。
|
|
71
|
+
* 早期版本用 Number.parseFloat 处理 "2026-11-14 11:31:27" 这类字符串,得到 2026 → 2026000,
|
|
72
|
+
* 面板上就显示成 1970-01-24。读档时把明显不合理的值重置为「现在」,
|
|
73
|
+
* 避免旧记录一直挂在 1970 年(正文与状态都保留,只修时间)。
|
|
74
|
+
*/
|
|
75
|
+
function repairStoredTime(value) {
|
|
76
|
+
const repaired = normalizeTimestamp(value)
|
|
77
|
+
const latest = Date.now() + 24 * 60 * 60 * 1000
|
|
78
|
+
if (repaired < EARLIEST_PLAUSIBLE || repaired > latest) return Date.now()
|
|
79
|
+
return repaired
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 早期版本发送命令缺少 --yes,dws 会以 confirmation_required 拒绝,失败结果被写进存档。
|
|
84
|
+
* 这类失败是插件自身的 bug、不是消息本身的问题:读档时清掉失败标记,
|
|
85
|
+
* 让卡片回到「有建议、可直接发送」的状态,避免用户看到永远不会自愈的红色报错。
|
|
86
|
+
*/
|
|
87
|
+
function healLegacyFailure(message) {
|
|
88
|
+
const replyError = String(message.reply?.error ?? '')
|
|
89
|
+
const legacy = /confirmation_required|需要用户确认/i.test(replyError) || /confirmation_required|需要用户确认/i.test(String(message.error ?? ''))
|
|
90
|
+
if (!legacy || message.reply?.ok === true) return message
|
|
91
|
+
const suggestion = message.suggestion && typeof message.suggestion.text === 'string' && message.suggestion.text !== ''
|
|
92
|
+
return {
|
|
93
|
+
...message,
|
|
94
|
+
reply: null,
|
|
95
|
+
error: '',
|
|
96
|
+
status: suggestion ? 'suggested' : 'received',
|
|
97
|
+
needsHuman: false,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function collapseWhitespace(text) {
|
|
102
|
+
return String(text ?? '')
|
|
103
|
+
.replace(/\r\n/g, '\n')
|
|
104
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '')
|
|
105
|
+
.trim()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 从事件里提取可展示的正文。 */
|
|
109
|
+
export function extractEventText(event) {
|
|
110
|
+
const candidate = []
|
|
111
|
+
const content = event?.content
|
|
112
|
+
|
|
113
|
+
if (typeof content === 'string') candidate.push(content)
|
|
114
|
+
else if (content && typeof content === 'object') {
|
|
115
|
+
candidate.push(content.text, content.content, content.title, content.markdown)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
candidate.push(event?.text, event?.markdown)
|
|
119
|
+
|
|
120
|
+
for (const item of candidate) {
|
|
121
|
+
if (typeof item !== 'string') continue
|
|
122
|
+
const trimmed = item.trim()
|
|
123
|
+
if (trimmed === '') continue
|
|
124
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
125
|
+
const parsed = parseLooseJson(trimmed)
|
|
126
|
+
if (parsed && typeof parsed === 'object') {
|
|
127
|
+
const nested = [parsed.text, parsed.content, parsed.title, parsed.markdown, parsed.fileName]
|
|
128
|
+
.find((value) => typeof value === 'string' && value.trim() !== '')
|
|
129
|
+
if (nested) return collapseWhitespace(nested)
|
|
130
|
+
}
|
|
131
|
+
// 解析不出 JSON 时按普通正文继续(例如 '[图片消息](mediaId=…)' 这种 markdown,
|
|
132
|
+
// 曾经因为以 '[' 开头被当成 JSON 直接丢掉)。
|
|
133
|
+
}
|
|
134
|
+
return collapseWhitespace(trimmed)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const msgtype = String(event?.msgtype || event?.message_type || '')
|
|
138
|
+
if (msgtype !== '' && !/text/i.test(msgtype)) return `[${msgtype} 消息]`
|
|
139
|
+
return ''
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 判定消息来源类型:私信还是群 @。 */
|
|
143
|
+
export function detectMessageKind(event) {
|
|
144
|
+
const type = String(event?.type || event?.event_type || '').toLowerCase()
|
|
145
|
+
if (type.includes('_o2o') || type.includes('direct') || type.includes('single')) return 'dm'
|
|
146
|
+
if (type.includes('_at') || type.endsWith('at') || type.includes('group')) return 'group'
|
|
147
|
+
const conversationType = String(event?.conversation_type ?? event?.chat_type ?? '')
|
|
148
|
+
if (conversationType === '2' || conversationType.toLowerCase().includes('group')) return 'group'
|
|
149
|
+
if (String(event?.conversation_title ?? '').trim() !== '') return 'group'
|
|
150
|
+
return 'dm'
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function sourceKeyOf(record) {
|
|
154
|
+
return record.kind === 'group'
|
|
155
|
+
? `group:${record.conversationId || record.conversationTitle || 'unknown'}`
|
|
156
|
+
: `dm:${record.senderId || record.sender || 'unknown'}`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 钉钉图片消息在正文里的标记:`[图片消息](mediaId=@xxxx)`。 */
|
|
160
|
+
const IMAGE_MARKER = /\[图片消息\]\s*\(\s*mediaId\s*=\s*([^\s)]+)\s*\)/gi
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 从事件正文里抽出图片 mediaId(钉钉事件不提供结构化媒体字段,
|
|
164
|
+
* 只能从 content 的 markdown 标记里取,再用 dws 下载)。
|
|
165
|
+
*/
|
|
166
|
+
export function extractImageRefs(event) {
|
|
167
|
+
const raw = extractEventText(event)
|
|
168
|
+
const refs = []
|
|
169
|
+
if (raw === '') return refs
|
|
170
|
+
IMAGE_MARKER.lastIndex = 0
|
|
171
|
+
let match = IMAGE_MARKER.exec(raw)
|
|
172
|
+
while (match) {
|
|
173
|
+
const mediaId = String(match[1] || '').trim()
|
|
174
|
+
if (mediaId !== '' && !refs.some((item) => item.mediaId === mediaId)) {
|
|
175
|
+
refs.push({ mediaId })
|
|
176
|
+
}
|
|
177
|
+
match = IMAGE_MARKER.exec(raw)
|
|
178
|
+
}
|
|
179
|
+
return refs
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 钉钉在图片消息正文里附带的下载提示,对用户和模型都是噪音,直接丢掉。 */
|
|
183
|
+
const IMAGE_HINT = /注意[::]\s*如需下载[^]*?命令下载|如需下载使用\s*dws[^\n]*?下载/gi
|
|
184
|
+
|
|
185
|
+
/** 把正文里的图片标记替换成可读占位,避免把一段 markdown 直接丢给模型。 */
|
|
186
|
+
export function stripImageMarkers(text) {
|
|
187
|
+
return String(text ?? '')
|
|
188
|
+
.replace(IMAGE_MARKER, '[图片]')
|
|
189
|
+
.replace(IMAGE_HINT, ' ')
|
|
190
|
+
.replace(/\[\s*\]/g, ' ')
|
|
191
|
+
.replace(/\s+/g, ' ')
|
|
192
|
+
.trim()
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** 按文件头判断图片类型(dws 落盘的文件没有扩展名保证)。 */
|
|
196
|
+
export function sniffImageMediaType(buffer) {
|
|
197
|
+
if (!buffer || buffer.length < 12) return ''
|
|
198
|
+
if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return 'image/png'
|
|
199
|
+
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return 'image/jpeg'
|
|
200
|
+
if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) return 'image/gif'
|
|
201
|
+
if (
|
|
202
|
+
buffer.length >= 12 &&
|
|
203
|
+
buffer.toString('ascii', 0, 4) === 'RIFF' &&
|
|
204
|
+
buffer.toString('ascii', 8, 12) === 'WEBP'
|
|
205
|
+
) {
|
|
206
|
+
return 'image/webp'
|
|
207
|
+
}
|
|
208
|
+
return ''
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 钉钉侧的幂等键冲突:同一个 `--idempotency-key` 再提交一次会被拒,
|
|
213
|
+
* 报错形如 `sendPersonalMessageByServerPush error: Request is repeated with uuid '…'`。
|
|
214
|
+
* 这既可能是「上一次其实已经发出去了」,也可能是老版本插件反复用同一个键导致永远发不出去,
|
|
215
|
+
* 所以 UI 要单独提示并允许换键重发。
|
|
216
|
+
*/
|
|
217
|
+
export function isDuplicateSendFailure(text) {
|
|
218
|
+
const value = String(text ?? '')
|
|
219
|
+
return /Request is repeated with uuid/i.test(value) || /is repeated with uuid/i.test(value) || /幂等/.test(value)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 群消息回复时先 @ 对方:dws 要求正文里带 `<@openDingTalkId>` 占位符,
|
|
224
|
+
* 并且用 `--at-open-dingtalk-ids` 声明要 @ 的人,钉钉会把它渲染成真正的 @提及。
|
|
225
|
+
*/
|
|
226
|
+
export function composeReplyBody({ record, text, replyPrefix = '', atSender = false }) {
|
|
227
|
+
const plain = String(text ?? '')
|
|
228
|
+
const prefix = String(replyPrefix ?? '')
|
|
229
|
+
const mention =
|
|
230
|
+
atSender && record && record.kind === 'group' && record.senderId ? `<@${String(record.senderId)}> ` : ''
|
|
231
|
+
return `${mention}${prefix}${plain}`.trim()
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 把一次回复拆成「要依次发出的多条消息」。
|
|
236
|
+
* - `multiSend` 关闭时永远只发一条(多条用换行连起来);
|
|
237
|
+
* - 自动回复优先用模型给的 `replies`,人工回复按换行拆分(空行/单换行都算分隔);
|
|
238
|
+
* - 最多 `max` 条,空串与相邻重复会被丢掉。
|
|
239
|
+
*/
|
|
240
|
+
export function planReplyParts({ text = '', replies = [], multiSend = true, max = 5 }) {
|
|
241
|
+
const raw = String(text ?? '')
|
|
242
|
+
if (!multiSend) return [raw.trim()].filter((item) => item !== '')
|
|
243
|
+
const limit = Math.max(1, Math.min(10, Math.round(Number(max) || 5)))
|
|
244
|
+
const fromModel = Array.isArray(replies)
|
|
245
|
+
? replies.map((item) => String(item ?? '').trim()).filter((item) => item !== '')
|
|
246
|
+
: []
|
|
247
|
+
const candidates =
|
|
248
|
+
fromModel.length > 1
|
|
249
|
+
? fromModel
|
|
250
|
+
: raw
|
|
251
|
+
.split(/\r?\n+/)
|
|
252
|
+
.map((item) => item.trim())
|
|
253
|
+
.filter((item) => item !== '')
|
|
254
|
+
const parts = []
|
|
255
|
+
for (const item of candidates.length > 0 ? candidates : [raw.trim()]) {
|
|
256
|
+
if (item === '') continue
|
|
257
|
+
if (parts.length > 0 && parts[parts.length - 1] === item) continue
|
|
258
|
+
parts.push(item)
|
|
259
|
+
if (parts.length >= limit) break
|
|
260
|
+
}
|
|
261
|
+
return parts
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 组装 `dws chat +messages-send` 参数(纯函数,便于自测)。 */
|
|
265
|
+
export function buildSendArgs({ record, body, auto = false, dryRun = false, attempt = 0, atSender = false, partIndex = 1 }) {
|
|
266
|
+
const args = ['chat', '+messages-send', '--as', 'user']
|
|
267
|
+
if (record.kind === 'group') {
|
|
268
|
+
args.push('--group', String(record.conversationId ?? ''))
|
|
269
|
+
} else {
|
|
270
|
+
args.push('--open-dingtalk-id', String(record.senderId ?? ''))
|
|
271
|
+
}
|
|
272
|
+
args.push('--text', String(body))
|
|
273
|
+
// 群 @ 回复:明确 @ 回发送人,保证「谁 @ 我,我就 @ 谁」。
|
|
274
|
+
if (atSender && record.kind === 'group' && record.senderId) {
|
|
275
|
+
args.push('--at-open-dingtalk-ids', String(record.senderId))
|
|
276
|
+
}
|
|
277
|
+
// 幂等键:同一事件的第一发用固定键(重复提交时钉钉会去重,避免连点发出两条);
|
|
278
|
+
// 之后每次重试都换一个新键(-r2/-r3…),否则钉钉会一直报
|
|
279
|
+
// 「Request is repeated with uuid ...」,导致重发永远发不出去。
|
|
280
|
+
// 连续发多条时每条再带 -p2/-p3…,否则第二条会被当成重复消息直接丢掉。
|
|
281
|
+
const baseKey = `dsh-dingtalk-${String(record.id ?? '')}`
|
|
282
|
+
const tries = Math.max(0, Number(attempt) || 0)
|
|
283
|
+
const part = Math.max(1, Number(partIndex) || 1)
|
|
284
|
+
const key = `${baseKey}${part > 1 ? `-p${part}` : ''}${tries === 0 ? '' : `-r${tries + 1}`}`
|
|
285
|
+
args.push('--idempotency-key', key)
|
|
286
|
+
// 人工确认过的回复按本人身份发送;全自动回复保留 AI 角标。
|
|
287
|
+
if (!auto) args.push('--ai-tag=false')
|
|
288
|
+
if (record.profile) args.push('--profile', String(record.profile))
|
|
289
|
+
// dws 在非交互环境要求显式确认,否则会以 confirmation_required 失败。
|
|
290
|
+
if (dryRun) {
|
|
291
|
+
args.push('--dry-run')
|
|
292
|
+
} else {
|
|
293
|
+
args.push('--yes')
|
|
294
|
+
}
|
|
295
|
+
return args
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export class DingTalkBridgeService {
|
|
299
|
+
constructor(ctx, config = {}) {
|
|
300
|
+
this.ctx = ctx
|
|
301
|
+
this.config = {
|
|
302
|
+
enabled: asBool(config.enabled, true),
|
|
303
|
+
dwsPath: asString(config.dwsPath, 'dws').trim() || 'dws',
|
|
304
|
+
profiles: asStringArray(config.profiles),
|
|
305
|
+
listenDirect: asBool(config.listenDirect, true),
|
|
306
|
+
listenGroupAt: asBool(config.listenGroupAt, true),
|
|
307
|
+
autoReply: asBool(config.autoReply, false),
|
|
308
|
+
autoSuggest: asBool(config.autoSuggest, true),
|
|
309
|
+
minConfidence: asNumber(config.minConfidence, 0.72, 0, 1),
|
|
310
|
+
contextMessages: Math.round(asNumber(config.contextMessages, 6, 1, 12)),
|
|
311
|
+
// 每个消息来源(私信按发送人、群 @ 按群)各自维护的滑动窗口长度。
|
|
312
|
+
windowMessages: Math.round(asNumber(config.windowMessages, 5, 2, 20)),
|
|
313
|
+
remoteContext: asBool(config.remoteContext, true),
|
|
314
|
+
remoteContextLimit: Math.round(asNumber(config.remoteContextLimit, 10, 0, 30)),
|
|
315
|
+
imageRecognition: asBool(config.imageRecognition, true),
|
|
316
|
+
imageMax: Math.round(asNumber(config.imageMax, 2, 1, 4)),
|
|
317
|
+
replyPrefix: asString(config.replyPrefix, ''),
|
|
318
|
+
// 群消息回复时先在正文 @ 回发送人(dws --at-open-dingtalk-ids + <@id> 占位符)。
|
|
319
|
+
groupReplyAt: asBool(config.groupReplyAt, true),
|
|
320
|
+
// 连续多条:模型可把回复拆成若干条依次发出(「给我发 10 条消息试试」这种需求)。
|
|
321
|
+
multiSend: asBool(config.multiSend, true),
|
|
322
|
+
multiSendMax: Math.round(asNumber(config.multiSendMax, 5, 1, 10)),
|
|
323
|
+
multiSendDelayMs: Math.round(asNumber(config.multiSendDelayMs, 600, 100, 5000)),
|
|
324
|
+
notifyModal: asBool(config.notifyModal, true),
|
|
325
|
+
maxInbox: Math.round(asNumber(config.maxInbox, 120, 20, 500)),
|
|
326
|
+
suggestProvider: asString(config.suggestProvider, '').trim(),
|
|
327
|
+
suggestModel: asString(config.suggestModel, '').trim(),
|
|
328
|
+
suggestReasoningEffort: asString(config.suggestReasoningEffort, '').trim(),
|
|
329
|
+
suggestTimeoutMs: Math.round(asNumber(config.suggestTimeoutMs, 30000, 5000, 180000)),
|
|
330
|
+
dryRun: asBool(config.dryRun, false),
|
|
331
|
+
// loopback = 本机浏览器授权(无需授权码);device = 设备流(授权码 + 二维码)。
|
|
332
|
+
loginMode: config.loginMode === 'device' ? 'device' : 'loopback',
|
|
333
|
+
// 重新授权前先退出已登录组织,避免越授权越多组织(默认开启)。
|
|
334
|
+
loginReset: asBool(config.loginReset, true),
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
this.statePath = join(
|
|
338
|
+
process.env.DSH_HOME && process.env.DSH_HOME.trim() !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh'),
|
|
339
|
+
'integrations',
|
|
340
|
+
'dingtalk-bridge',
|
|
341
|
+
'state.json',
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
this.state = {
|
|
345
|
+
autoReply: this.config.autoReply,
|
|
346
|
+
autoReplyTouched: false,
|
|
347
|
+
// 本次开启自动回复的时刻(毫秒)。早于它到达的消息不自动发送。
|
|
348
|
+
autoReplyAt: this.config.autoReply ? Date.now() : 0,
|
|
349
|
+
messages: [],
|
|
350
|
+
selfName: '',
|
|
351
|
+
currentProfile: '',
|
|
352
|
+
profiles: [],
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
this.tool = { ok: false, version: '', error: '', checkedAt: 0 }
|
|
356
|
+
this.login = { status: 'idle', code: '', url: '', qr: '', startedAt: 0, error: '', message: '' }
|
|
357
|
+
this.loginChild = null
|
|
358
|
+
this.listeners = new Map()
|
|
359
|
+
this.sseClients = new Set()
|
|
360
|
+
this.seen = new Map()
|
|
361
|
+
this.titleCache = new Map()
|
|
362
|
+
this.remoteCache = new Map()
|
|
363
|
+
// 每个来源(sourceKey)一条独立的滑动窗口,AI 回复只看自己窗口里的最近若干条。
|
|
364
|
+
this.windows = new Map()
|
|
365
|
+
// null = 未知,true/false = 当前模型是否支持图片输入(仅用于界面提示)。
|
|
366
|
+
this.vision = null
|
|
367
|
+
this.timers = new Set()
|
|
368
|
+
this.restartTimers = new Map()
|
|
369
|
+
this.suggestQueue = []
|
|
370
|
+
this.suggestBusy = 0
|
|
371
|
+
this.saveChain = Promise.resolve()
|
|
372
|
+
this.started = false
|
|
373
|
+
this.stopped = false
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ---------------------------------------------------------------- lifecycle
|
|
377
|
+
|
|
378
|
+
start() {
|
|
379
|
+
this.started = true
|
|
380
|
+
this.stopped = false
|
|
381
|
+
|
|
382
|
+
if (this.config.enabled) {
|
|
383
|
+
this.bootstrap().catch(() => {
|
|
384
|
+
// bootstrap 内部已广播错误状态,这里只兜住未捕获异常。
|
|
385
|
+
})
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
this.setInterval(() => this.healthCheck(), HEALTH_INTERVAL)
|
|
389
|
+
this.setInterval(() => this.pruneSeen(), 60 * 1000)
|
|
390
|
+
|
|
391
|
+
return async () => {
|
|
392
|
+
this.stopped = true
|
|
393
|
+
this.started = false
|
|
394
|
+
for (const timer of this.timers) clearInterval(timer)
|
|
395
|
+
this.timers.clear()
|
|
396
|
+
for (const timer of this.restartTimers.values()) clearTimeout(timer)
|
|
397
|
+
this.restartTimers.clear()
|
|
398
|
+
await this.stopAllListeners()
|
|
399
|
+
if (this.loginChild) {
|
|
400
|
+
killTree(this.loginChild)
|
|
401
|
+
this.loginChild = null
|
|
402
|
+
}
|
|
403
|
+
for (const res of this.sseClients) {
|
|
404
|
+
try {
|
|
405
|
+
res.end()
|
|
406
|
+
} catch {
|
|
407
|
+
// 忽略。
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
this.sseClients.clear()
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
setInterval(fn, ms) {
|
|
415
|
+
const timer = setInterval(() => {
|
|
416
|
+
if (this.stopped) return
|
|
417
|
+
try {
|
|
418
|
+
fn()
|
|
419
|
+
} catch {
|
|
420
|
+
// 定时任务异常不打断宿主。
|
|
421
|
+
}
|
|
422
|
+
}, ms)
|
|
423
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
424
|
+
this.timers.add(timer)
|
|
425
|
+
return timer
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async bootstrap() {
|
|
429
|
+
// 调试日志别无限长:超过 ~400KB 就在启动时清空。
|
|
430
|
+
try {
|
|
431
|
+
const logPath = join(this.dataDir(), 'http-debug.log')
|
|
432
|
+
const text = await readFile(logPath, 'utf8')
|
|
433
|
+
if (text.length > 400000) await writeFile(logPath, '', 'utf8')
|
|
434
|
+
} catch {
|
|
435
|
+
// 文件还不存在,忽略。
|
|
436
|
+
}
|
|
437
|
+
this.noteRequest('BOOT', ROUTE_PREFIX, 200, `${HOST_BUILD} pid=${process.pid}`)
|
|
438
|
+
await this.loadState()
|
|
439
|
+
this.broadcast()
|
|
440
|
+
await this.checkTool()
|
|
441
|
+
await this.refreshProfiles()
|
|
442
|
+
if (this.state.profiles.length === 0 && this.login.status !== 'pending') {
|
|
443
|
+
this.login = {
|
|
444
|
+
...this.login,
|
|
445
|
+
status: 'idle',
|
|
446
|
+
message: '尚未登录钉钉,请点击右上角「钉钉授权」,在弹出的授权页扫码或登录即可',
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
this.startAllListeners()
|
|
450
|
+
this.refreshVision().catch(() => {})
|
|
451
|
+
this.broadcast()
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* 探测当前模型是否支持图片输入。
|
|
456
|
+
* 结果只用于界面提示:不支持时消息里的图片仍然会下载、展示,只是不交给模型分析。
|
|
457
|
+
*/
|
|
458
|
+
async refreshVision() {
|
|
459
|
+
const selection = this.modelInfo()
|
|
460
|
+
const llm = this.ctx?.get?.('llm')
|
|
461
|
+
if (selection.provider === '' || !llm || typeof llm.resolveModelInfo !== 'function') return
|
|
462
|
+
try {
|
|
463
|
+
const info = await llm.resolveModelInfo(selection.provider, selection.model)
|
|
464
|
+
const modalities = Array.isArray(info?.inputModalities) ? info.inputModalities : null
|
|
465
|
+
const next = modalities === null ? null : modalities.includes('image')
|
|
466
|
+
if (next !== this.vision) {
|
|
467
|
+
this.vision = next
|
|
468
|
+
this.broadcast()
|
|
469
|
+
}
|
|
470
|
+
} catch {
|
|
471
|
+
if (this.vision !== null) {
|
|
472
|
+
this.vision = null
|
|
473
|
+
this.broadcast()
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// ------------------------------------------------------------------- 外部命令
|
|
479
|
+
|
|
480
|
+
async checkTool() {
|
|
481
|
+
const result = await runDws(this.config.dwsPath, ['--version'], { timeoutMs: 15000 })
|
|
482
|
+
const output = `${result.stdout}\n${result.stderr}`.trim()
|
|
483
|
+
const version = /(\d+\.\d+\.\d+)/.exec(output)?.[1] || ''
|
|
484
|
+
this.tool = {
|
|
485
|
+
ok: result.code === 0 && version !== '',
|
|
486
|
+
version,
|
|
487
|
+
error: result.code === 0 ? '' : describeFailure(result),
|
|
488
|
+
checkedAt: Date.now(),
|
|
489
|
+
}
|
|
490
|
+
return this.tool
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
async refreshProfiles() {
|
|
494
|
+
const result = await runDws(this.config.dwsPath, ['profile', 'list', '-f', 'json'], { timeoutMs: 20000 })
|
|
495
|
+
const payload = parseLooseJson(result.stdout)
|
|
496
|
+
const raw = Array.isArray(payload?.profiles) ? payload.profiles : []
|
|
497
|
+
const profiles = raw
|
|
498
|
+
.map((item) => ({
|
|
499
|
+
profile: String(item?.profile ?? ''),
|
|
500
|
+
corpId: String(item?.corpId ?? ''),
|
|
501
|
+
corpName: String(item?.corpName ?? ''),
|
|
502
|
+
userId: String(item?.userId ?? ''),
|
|
503
|
+
userName: String(item?.userName ?? ''),
|
|
504
|
+
status: String(item?.status ?? ''),
|
|
505
|
+
}))
|
|
506
|
+
.filter((item) => item.profile !== '')
|
|
507
|
+
|
|
508
|
+
this.state.profiles = profiles
|
|
509
|
+
this.state.currentProfile = String(payload?.currentProfile ?? '')
|
|
510
|
+
const current = profiles.find((item) => item.profile === this.state.currentProfile)
|
|
511
|
+
this.state.selfName = current?.userName || this.state.selfName || ''
|
|
512
|
+
|
|
513
|
+
if (profiles.length === 0) {
|
|
514
|
+
this.tool = {
|
|
515
|
+
ok: false,
|
|
516
|
+
version: this.tool.version,
|
|
517
|
+
error: result.code === 0 ? '未找到已登录的钉钉组织,请点击右上角「钉钉授权」登录' : describeFailure(result),
|
|
518
|
+
checkedAt: Date.now(),
|
|
519
|
+
}
|
|
520
|
+
} else if (!this.tool.ok) {
|
|
521
|
+
// 重新授权成功后要把「dws 未就绪」的旧结论翻回来,否则面板一直显示错误态。
|
|
522
|
+
this.tool = { ok: true, version: this.tool.version, error: '', checkedAt: Date.now() }
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
return profiles
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** 需要监听的组织 profile 列表。登录态过期的组织不再监听(否则监听进程会反复报鉴权失败)。 */
|
|
529
|
+
targetProfiles() {
|
|
530
|
+
if (this.config.profiles.length > 0) return this.config.profiles
|
|
531
|
+
const usable = this.state.profiles.filter((item) => item && (item.status === '' || item.status === 'active'))
|
|
532
|
+
const current = this.state.currentProfile
|
|
533
|
+
if (current !== '' && (usable.length === 0 || usable.some((item) => item.profile === current))) return [current]
|
|
534
|
+
const names = usable.map((item) => item.profile).filter((name) => name !== '')
|
|
535
|
+
if (names.length > 0) return names
|
|
536
|
+
return current !== '' ? [current] : []
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** 判断记录里的 profile 是否仍然有效:失效时发送命令不再带 --profile,交给 dws 用当前账号。 */
|
|
540
|
+
knownProfile(name) {
|
|
541
|
+
const value = typeof name === 'string' ? name : ''
|
|
542
|
+
if (value === '') return ''
|
|
543
|
+
if (this.state.currentProfile === value) return value
|
|
544
|
+
if (this.state.profiles.some((item) => item && item.profile === value)) return value
|
|
545
|
+
return ''
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ------------------------------------------------------------------ 授权登录
|
|
549
|
+
|
|
550
|
+
/** 当前是否有可用登录态(组织列表里有 active 或至少一个 profile)。 */
|
|
551
|
+
hasLogin() {
|
|
552
|
+
if (this.state.currentProfile !== '') return true
|
|
553
|
+
return this.state.profiles.some((item) => item && item.profile !== '')
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** 已登录但登录态过期的组织,界面上提示「建议重新授权」。 */
|
|
557
|
+
expiredProfiles() {
|
|
558
|
+
return this.state.profiles.filter((item) => item && item.status !== '' && item.status !== 'active')
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* 退出钉钉登录:先停掉所有事件监听(避免退出后监听进程反复报鉴权失败),
|
|
563
|
+
* 再执行 `dws auth logout --yes`(默认退出全部账号),最后清空本地组织缓存。
|
|
564
|
+
*/
|
|
565
|
+
async logoutAll({ quiet = false } = {}) {
|
|
566
|
+
if (!quiet) {
|
|
567
|
+
this.login = { ...this.login, status: 'idle', message: '正在退出钉钉登录…', error: '' }
|
|
568
|
+
this.broadcast()
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
await this.stopAllListeners()
|
|
572
|
+
|
|
573
|
+
let result = { code: 0, stdout: '', stderr: '' }
|
|
574
|
+
try {
|
|
575
|
+
result = await runDws(this.config.dwsPath, ['auth', 'logout', '--yes'], { timeoutMs: 40000 })
|
|
576
|
+
} catch (error) {
|
|
577
|
+
result = { code: -1, stdout: '', stderr: String(error?.message || error) }
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const ok = result.code === 0
|
|
581
|
+
this.state.profiles = []
|
|
582
|
+
this.state.currentProfile = ''
|
|
583
|
+
this.state.selfName = ''
|
|
584
|
+
this.tool = {
|
|
585
|
+
ok: false,
|
|
586
|
+
version: this.tool.version,
|
|
587
|
+
error: ok ? '已退出钉钉登录,点击「钉钉授权」重新登录' : `退出登录未成功:${describeFailure(result)}`,
|
|
588
|
+
checkedAt: Date.now(),
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (!quiet) {
|
|
592
|
+
this.login = {
|
|
593
|
+
...this.login,
|
|
594
|
+
status: 'idle',
|
|
595
|
+
code: '',
|
|
596
|
+
url: '',
|
|
597
|
+
qr: '',
|
|
598
|
+
qrUrl: '',
|
|
599
|
+
error: ok ? '' : describeFailure(result),
|
|
600
|
+
message: ok ? '已退出钉钉登录,可重新点击「钉钉授权」登录新的组织' : '退出登录未成功,请稍后重试',
|
|
601
|
+
}
|
|
602
|
+
this.broadcast()
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
await this.saveState()
|
|
606
|
+
return { ok, output: `${result.stdout}\n${result.stderr}`.trim() }
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* 启动钉钉授权。
|
|
611
|
+
*
|
|
612
|
+
* 默认走 loopback(`dws auth login --no-browser`):dws 起一个 127.0.0.1 回调,
|
|
613
|
+
* 我们只需要把授权页链接交给界面打开,用户在页面里扫码/登录,回调写回 token 即完成,
|
|
614
|
+
* **全程不需要抄授权码**。远程/无浏览器环境可配置 loginMode=device 走设备流
|
|
615
|
+
* (--device,输出授权码 + 二维码链接)。
|
|
616
|
+
*/
|
|
617
|
+
async startLogin() {
|
|
618
|
+
if (this.loginChild) return { ok: true, login: this.login }
|
|
619
|
+
|
|
620
|
+
// 默认先退出已登录的组织:否则每授权一次就多一个组织,监听列表越滚越长。
|
|
621
|
+
if (this.config.loginReset && this.config.profiles.length === 0 && this.hasLogin()) {
|
|
622
|
+
this.login = {
|
|
623
|
+
...this.login,
|
|
624
|
+
status: 'idle',
|
|
625
|
+
code: '',
|
|
626
|
+
url: '',
|
|
627
|
+
qr: '',
|
|
628
|
+
qrUrl: '',
|
|
629
|
+
error: '',
|
|
630
|
+
message: '正在退出已登录的钉钉组织,随后申请新的授权…',
|
|
631
|
+
}
|
|
632
|
+
this.broadcast()
|
|
633
|
+
await this.logoutAll({ quiet: true })
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const mode = this.config.loginMode === 'device' ? 'device' : 'loopback'
|
|
637
|
+
const args =
|
|
638
|
+
mode === 'device'
|
|
639
|
+
? ['auth', 'login', '--device', '--no-browser']
|
|
640
|
+
: ['auth', 'login', '--no-browser', '--yes']
|
|
641
|
+
|
|
642
|
+
this.login = {
|
|
643
|
+
status: 'pending',
|
|
644
|
+
mode,
|
|
645
|
+
code: '',
|
|
646
|
+
url: '',
|
|
647
|
+
qr: '',
|
|
648
|
+
startedAt: Date.now(),
|
|
649
|
+
error: '',
|
|
650
|
+
message:
|
|
651
|
+
mode === 'device' ? '正在向钉钉申请设备授权…' : '正在向钉钉申请授权链接…',
|
|
652
|
+
}
|
|
653
|
+
this.broadcast()
|
|
654
|
+
|
|
655
|
+
let child
|
|
656
|
+
try {
|
|
657
|
+
child = spawnDws(this.config.dwsPath, args, {
|
|
658
|
+
cwd: this.workdir(),
|
|
659
|
+
})
|
|
660
|
+
} catch (error) {
|
|
661
|
+
this.login = {
|
|
662
|
+
...this.login,
|
|
663
|
+
status: 'failed',
|
|
664
|
+
error: String(error?.message || error),
|
|
665
|
+
message: '无法启动 dws 授权命令',
|
|
666
|
+
}
|
|
667
|
+
this.broadcast()
|
|
668
|
+
return { ok: false, error: this.login.error, login: this.login }
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
this.loginChild = child
|
|
672
|
+
const reader = createLineReader((line) => this.handleLoginLine(line))
|
|
673
|
+
child.stdout?.on('data', (chunk) => reader.push(toText(chunk)))
|
|
674
|
+
child.stderr?.on('data', (chunk) => reader.push(toText(chunk)))
|
|
675
|
+
child.on('error', (error) => {
|
|
676
|
+
this.loginChild = null
|
|
677
|
+
this.login = { ...this.login, status: 'failed', error: String(error?.message || error), message: '' }
|
|
678
|
+
this.broadcast()
|
|
679
|
+
})
|
|
680
|
+
child.on('close', (code) => {
|
|
681
|
+
reader.flush()
|
|
682
|
+
this.loginChild = null
|
|
683
|
+
if (this.login.status === 'pending') {
|
|
684
|
+
this.login =
|
|
685
|
+
code === 0
|
|
686
|
+
? { ...this.login, status: 'authorized', message: '授权成功,正在刷新账号与监听…' }
|
|
687
|
+
: {
|
|
688
|
+
...this.login,
|
|
689
|
+
status: 'failed',
|
|
690
|
+
error: this.login.error || `授权未完成(退出码 ${code})`,
|
|
691
|
+
message:
|
|
692
|
+
this.login.mode === 'device'
|
|
693
|
+
? '扫码/授权码流程已结束,但未获取到有效登录态,请重试'
|
|
694
|
+
: '本机浏览器授权没有完成(浏览器没打开或回调端口被拦截)。可以再点一次「钉钉授权」,或把配置项 loginMode 改成 device 用二维码授权。',
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
this.broadcast()
|
|
698
|
+
if (this.login.status === 'authorized') {
|
|
699
|
+
// 重新授权 = 换环境。清空旧组织的收件箱,避免新组织看到一个塞满旧消息的列表。
|
|
700
|
+
this.resetInbox('重新授权成功,已清空旧消息')
|
|
701
|
+
this.refreshProfiles()
|
|
702
|
+
.then(() => {
|
|
703
|
+
this.startAllListeners()
|
|
704
|
+
this.login = { ...this.login, message: '授权成功,已开始接收消息' }
|
|
705
|
+
this.broadcast()
|
|
706
|
+
})
|
|
707
|
+
.catch(() => {})
|
|
708
|
+
}
|
|
709
|
+
})
|
|
710
|
+
|
|
711
|
+
return { ok: true, login: this.login }
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
handleLoginLine(line) {
|
|
715
|
+
const text = String(line || '')
|
|
716
|
+
if (text.trim() === '') return
|
|
717
|
+
const flow = parseDeviceFlow(text)
|
|
718
|
+
if (flow) {
|
|
719
|
+
this.login = {
|
|
720
|
+
...this.login,
|
|
721
|
+
code: flow.code || this.login.code,
|
|
722
|
+
url: flow.url || this.login.url,
|
|
723
|
+
message:
|
|
724
|
+
this.login.mode === 'device'
|
|
725
|
+
? '用钉钉扫码,或点击「打开授权页面」在浏览器里确认授权'
|
|
726
|
+
: '点击「打开钉钉授权页面」,在弹出的页面里扫码或登录即可完成授权',
|
|
727
|
+
}
|
|
728
|
+
this.broadcast()
|
|
729
|
+
// 设备流才有可扫的授权码二维码;loopback 的回调指向本机 127.0.0.1,扫二维码没意义。
|
|
730
|
+
if (this.login.mode === 'device' && this.login.url !== '') this.renderLoginQr(this.login.url)
|
|
731
|
+
return
|
|
732
|
+
}
|
|
733
|
+
if (/授权成功|登录成功|login success/i.test(text)) {
|
|
734
|
+
this.login = { ...this.login, status: 'authorized', message: '授权成功' }
|
|
735
|
+
this.broadcast()
|
|
736
|
+
return
|
|
737
|
+
}
|
|
738
|
+
const failure = /授权失败|登录失败|error[::]\s*(.+)/i.exec(text)
|
|
739
|
+
if (failure) {
|
|
740
|
+
this.login = { ...this.login, error: String(failure[1] || failure[0]).trim() }
|
|
741
|
+
this.broadcast()
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* 把设备授权链接渲染成二维码(dataURL)直接放进快照,
|
|
747
|
+
* 页面就不用让用户再抄一遍授权码。
|
|
748
|
+
*/
|
|
749
|
+
renderLoginQr(url) {
|
|
750
|
+
if (typeof url !== 'string' || url === '') return
|
|
751
|
+
if (this.login.qrUrl === url && this.login.qr !== '') return
|
|
752
|
+
QRCode.toDataURL(url, { margin: 1, width: 260, errorCorrectionLevel: 'M' })
|
|
753
|
+
.then((dataUrl) => {
|
|
754
|
+
if (this.login.status !== 'pending') return
|
|
755
|
+
this.login = { ...this.login, qr: dataUrl, qrUrl: url }
|
|
756
|
+
this.broadcast()
|
|
757
|
+
})
|
|
758
|
+
.catch(() => {
|
|
759
|
+
// 二维码生成失败不影响授权码与链接两条路径。
|
|
760
|
+
})
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
cancelLogin() {
|
|
764
|
+
if (this.loginChild) {
|
|
765
|
+
killTree(this.loginChild)
|
|
766
|
+
this.loginChild = null
|
|
767
|
+
}
|
|
768
|
+
this.login = { ...this.login, status: 'idle', message: '已取消授权', error: '', qr: '', qrUrl: '' }
|
|
769
|
+
this.broadcast()
|
|
770
|
+
return { ok: true, login: this.login }
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// ------------------------------------------------------------------ listeners
|
|
774
|
+
|
|
775
|
+
startAllListeners() {
|
|
776
|
+
if (!this.config.enabled) return
|
|
777
|
+
const keys = []
|
|
778
|
+
if (this.config.listenDirect) keys.push(O2O_KEY)
|
|
779
|
+
if (this.config.listenGroupAt) keys.push(AT_KEY)
|
|
780
|
+
if (keys.length === 0) return
|
|
781
|
+
|
|
782
|
+
for (const profile of this.targetProfiles()) {
|
|
783
|
+
if (this.listeners.has(profile)) continue
|
|
784
|
+
this.startListener(profile)
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
startListener(profile, attempt = 0) {
|
|
789
|
+
if (this.stopped) return
|
|
790
|
+
if (this.listeners.has(profile)) return
|
|
791
|
+
|
|
792
|
+
const keys = []
|
|
793
|
+
if (this.config.listenDirect) keys.push(O2O_KEY)
|
|
794
|
+
if (this.config.listenGroupAt) keys.push(AT_KEY)
|
|
795
|
+
if (keys.length === 0) return
|
|
796
|
+
|
|
797
|
+
const args = ['--profile', profile, 'event', 'consume', ...keys, '--flatten', '-f', 'ndjson']
|
|
798
|
+
|
|
799
|
+
let child
|
|
800
|
+
try {
|
|
801
|
+
child = spawnDws(this.config.dwsPath, args, { cwd: this.workdir() })
|
|
802
|
+
} catch (error) {
|
|
803
|
+
this.broadcastListenerError(profile, String(error?.message || error))
|
|
804
|
+
return
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
const entry = {
|
|
808
|
+
profile,
|
|
809
|
+
userName: this.state.profiles.find((item) => item.profile === profile)?.userName || this.state.selfName || '',
|
|
810
|
+
child,
|
|
811
|
+
status: 'connecting',
|
|
812
|
+
since: Date.now(),
|
|
813
|
+
readyAt: 0,
|
|
814
|
+
lastEventAt: 0,
|
|
815
|
+
error: '',
|
|
816
|
+
attempt,
|
|
817
|
+
stderrTail: '',
|
|
818
|
+
buffer: '',
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
const reader = createLineReader((line) => this.handleLine(profile, line))
|
|
822
|
+
|
|
823
|
+
child.stdout?.on('data', (chunk) => reader.push(toText(chunk)))
|
|
824
|
+
child.stderr?.on('data', (chunk) => this.handleStderr(entry, toText(chunk)))
|
|
825
|
+
child.on('error', (error) => {
|
|
826
|
+
entry.error = String(error?.message || error)
|
|
827
|
+
entry.status = 'error'
|
|
828
|
+
this.broadcast()
|
|
829
|
+
})
|
|
830
|
+
child.on('close', (code) => {
|
|
831
|
+
reader.flush()
|
|
832
|
+
this.handleListenerClose(profile, entry, code)
|
|
833
|
+
})
|
|
834
|
+
|
|
835
|
+
this.listeners.set(profile, entry)
|
|
836
|
+
this.broadcast()
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
handleStderr(entry, text) {
|
|
840
|
+
const cleaned = String(text || '')
|
|
841
|
+
if (cleaned.trim() === '') return
|
|
842
|
+
entry.stderrTail = `${entry.stderrTail}${cleaned}`.slice(-2000)
|
|
843
|
+
|
|
844
|
+
if (/\[event\]\s*ready/i.test(cleaned)) {
|
|
845
|
+
entry.status = 'online'
|
|
846
|
+
entry.error = ''
|
|
847
|
+
entry.readyAt = Date.now()
|
|
848
|
+
this.broadcast()
|
|
849
|
+
return
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
const errorLine = cleaned
|
|
853
|
+
.split('\n')
|
|
854
|
+
.map((line) => line.trim())
|
|
855
|
+
.filter((line) => line !== '')
|
|
856
|
+
.filter((line) => /error|失败|拒绝|denied|unauthorized|expired|invalid/i.test(line))
|
|
857
|
+
.pop()
|
|
858
|
+
|
|
859
|
+
if (errorLine) {
|
|
860
|
+
entry.error = errorLine.slice(0, 500)
|
|
861
|
+
if (entry.status === 'connecting') entry.status = 'error'
|
|
862
|
+
this.broadcast()
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
handleListenerClose(profile, entry, code) {
|
|
867
|
+
this.listeners.delete(profile)
|
|
868
|
+
if (this.stopped) return
|
|
869
|
+
|
|
870
|
+
const stable = entry.readyAt > 0 && Date.now() - entry.readyAt > MIN_STABLE_MS
|
|
871
|
+
const attempt = stable ? 1 : entry.attempt + 1
|
|
872
|
+
const delay = Math.min(60000, 1000 * 2 ** Math.min(attempt - 1, 6))
|
|
873
|
+
|
|
874
|
+
this.broadcastListenerError(
|
|
875
|
+
profile,
|
|
876
|
+
entry.error || `事件监听已退出(退出码 ${code}),${Math.round(delay / 1000)} 秒后重连`,
|
|
877
|
+
{ retryIn: delay },
|
|
878
|
+
)
|
|
879
|
+
this.scheduleRestart(profile, attempt, delay)
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
broadcastListenerError(profile, message, extra = {}) {
|
|
883
|
+
const entry = {
|
|
884
|
+
profile,
|
|
885
|
+
child: null,
|
|
886
|
+
status: 'error',
|
|
887
|
+
since: Date.now(),
|
|
888
|
+
readyAt: 0,
|
|
889
|
+
lastEventAt: 0,
|
|
890
|
+
error: String(message || ''),
|
|
891
|
+
attempt: 0,
|
|
892
|
+
stderrTail: '',
|
|
893
|
+
buffer: '',
|
|
894
|
+
...extra,
|
|
895
|
+
}
|
|
896
|
+
this.listeners.set(profile, entry)
|
|
897
|
+
this.broadcast()
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
scheduleRestart(profile, attempt, delay) {
|
|
901
|
+
const existing = this.restartTimers.get(profile)
|
|
902
|
+
if (existing) clearTimeout(existing)
|
|
903
|
+
const timer = setTimeout(() => {
|
|
904
|
+
this.restartTimers.delete(profile)
|
|
905
|
+
if (this.stopped || !this.config.enabled) return
|
|
906
|
+
const current = this.listeners.get(profile)
|
|
907
|
+
if (current && current.child) return
|
|
908
|
+
this.listeners.delete(profile)
|
|
909
|
+
this.startListener(profile, attempt)
|
|
910
|
+
}, delay)
|
|
911
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
912
|
+
this.restartTimers.set(profile, timer)
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
async stopListener(profile, { graceful = true } = {}) {
|
|
916
|
+
const entry = this.listeners.get(profile)
|
|
917
|
+
if (!entry) return
|
|
918
|
+
this.listeners.delete(profile)
|
|
919
|
+
const child = entry.child
|
|
920
|
+
if (!child) return
|
|
921
|
+
|
|
922
|
+
if (graceful) {
|
|
923
|
+
try {
|
|
924
|
+
child.stdin?.end()
|
|
925
|
+
} catch {
|
|
926
|
+
// 忽略。
|
|
927
|
+
}
|
|
928
|
+
const closed = await new Promise((resolve) => {
|
|
929
|
+
const timer = setTimeout(() => resolve(false), 2500)
|
|
930
|
+
child.once('close', () => {
|
|
931
|
+
clearTimeout(timer)
|
|
932
|
+
resolve(true)
|
|
933
|
+
})
|
|
934
|
+
})
|
|
935
|
+
if (closed) return
|
|
936
|
+
}
|
|
937
|
+
killTree(child)
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
async stopAllListeners() {
|
|
941
|
+
const profiles = [...this.listeners.keys()]
|
|
942
|
+
await Promise.all(profiles.map((profile) => this.stopListener(profile)))
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
async restartAll() {
|
|
946
|
+
await this.stopAllListeners()
|
|
947
|
+
await this.refreshProfiles()
|
|
948
|
+
this.startAllListeners()
|
|
949
|
+
this.broadcast()
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
async healthCheck() {
|
|
953
|
+
this.pruneSeen()
|
|
954
|
+
if (!this.config.enabled || this.stopped) return
|
|
955
|
+
|
|
956
|
+
for (const profile of this.targetProfiles()) {
|
|
957
|
+
const entry = this.listeners.get(profile)
|
|
958
|
+
if (!entry || entry.child === null) continue
|
|
959
|
+
|
|
960
|
+
const result = await runDws(this.config.dwsPath, ['--profile', profile, 'event', 'status'], {
|
|
961
|
+
timeoutMs: 15000,
|
|
962
|
+
})
|
|
963
|
+
const output = `${result.stdout}\n${result.stderr}`
|
|
964
|
+
|
|
965
|
+
// 订阅被清空时 dws 会输出 Subscriptions: none,需要重建监听。
|
|
966
|
+
if (/Subscriptions:\s*none/i.test(output)) {
|
|
967
|
+
await this.stopListener(profile)
|
|
968
|
+
this.scheduleRestart(profile, 1, 5000)
|
|
969
|
+
this.broadcastListenerError(profile, '订阅已被清空,5 秒后重建监听')
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
pruneSeen() {
|
|
975
|
+
const now = Date.now()
|
|
976
|
+
for (const [key, at] of this.seen) {
|
|
977
|
+
if (now - at > SEEN_TTL) this.seen.delete(key)
|
|
978
|
+
}
|
|
979
|
+
while (this.seen.size > MAX_SEEN) {
|
|
980
|
+
const oldest = this.seen.keys().next()
|
|
981
|
+
if (oldest.done) break
|
|
982
|
+
this.seen.delete(oldest.value)
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
workdir() {
|
|
987
|
+
return process.cwd()
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// ------------------------------------------------------------------ 消息接入
|
|
991
|
+
|
|
992
|
+
handleLine(profile, line) {
|
|
993
|
+
const payload = parseLooseJson(line)
|
|
994
|
+
if (!payload || typeof payload !== 'object') return
|
|
995
|
+
|
|
996
|
+
const errorMessage = payload?.error?.message || payload?.error?.msg
|
|
997
|
+
if (typeof errorMessage === 'string' && errorMessage.trim() !== '') {
|
|
998
|
+
const entry = this.listeners.get(profile)
|
|
999
|
+
if (entry) {
|
|
1000
|
+
entry.error = errorMessage.trim().slice(0, 500)
|
|
1001
|
+
const retry = normalizeTimestamp(payload?.error?.retry_after_seconds || payload?.retry_after_seconds)
|
|
1002
|
+
if (retry > Date.now()) {
|
|
1003
|
+
entry.status = 'error'
|
|
1004
|
+
this.broadcast()
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
const entry = this.listeners.get(profile)
|
|
1011
|
+
if (entry) {
|
|
1012
|
+
entry.lastEventAt = Date.now()
|
|
1013
|
+
if (entry.status !== 'online') {
|
|
1014
|
+
entry.status = 'online'
|
|
1015
|
+
entry.error = ''
|
|
1016
|
+
this.broadcast()
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
this.ingest(profile, payload)
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
ingest(profile, event) {
|
|
1024
|
+
const type = String(event?.type || event?.event_type || '').toLowerCase()
|
|
1025
|
+
|
|
1026
|
+
// 只处理两个订阅来源的事件,其余(已读、撤回、表情回复等)一律忽略。
|
|
1027
|
+
const isDirect = type === O2O_KEY.toLowerCase() || type.includes('_o2o')
|
|
1028
|
+
const isGroupAt = type === AT_KEY.toLowerCase() || type.endsWith('_at')
|
|
1029
|
+
if (!isDirect && !isGroupAt) return
|
|
1030
|
+
if (/recall|revoke|reaction|read|remove/i.test(type)) return
|
|
1031
|
+
|
|
1032
|
+
const sender = String(event?.sender ?? '').trim()
|
|
1033
|
+
const senderId = String(event?.sender_open_dingtalk_id ?? event?.open_dingtalk_id ?? '').trim()
|
|
1034
|
+
const selfName = this.listeners.get(profile)?.userName || this.state.selfName
|
|
1035
|
+
|
|
1036
|
+
// 自己发送的消息会回流,忽略。
|
|
1037
|
+
if (sender !== '' && selfName !== '' && sender === selfName) return
|
|
1038
|
+
|
|
1039
|
+
const eventId = String(event?.event_id ?? event?.message_id ?? '').trim()
|
|
1040
|
+
if (eventId !== '') {
|
|
1041
|
+
if (this.seen.has(eventId)) return
|
|
1042
|
+
this.seen.set(eventId, Date.now())
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
const kind = isGroupAt ? 'group' : detectMessageKind(event)
|
|
1046
|
+
if (kind === 'group' && !this.config.listenGroupAt) return
|
|
1047
|
+
if (kind === 'dm' && !this.config.listenDirect) return
|
|
1048
|
+
|
|
1049
|
+
// 图片消息的正文只有 `[图片消息](mediaId=…)` 标记:先把 mediaId 抠出来,
|
|
1050
|
+
// 再把标记换成 [图片],避免把 markdown 原文丢给模型。
|
|
1051
|
+
const imageRefs = this.config.imageRecognition
|
|
1052
|
+
? extractImageRefs(event).slice(0, this.config.imageMax)
|
|
1053
|
+
: []
|
|
1054
|
+
const text = stripImageMarkers(extractEventText(event))
|
|
1055
|
+
if (text === '' && imageRefs.length === 0) return
|
|
1056
|
+
|
|
1057
|
+
const conversationId = String(event?.conversation_id ?? event?.open_conversation_id ?? '').trim()
|
|
1058
|
+
const at = repairStoredTime(event?.create_time ?? event?.timestamp ?? event?.event_time)
|
|
1059
|
+
|
|
1060
|
+
const record = {
|
|
1061
|
+
id: eventId !== '' ? eventId : randomUUID(),
|
|
1062
|
+
messageId: String(event?.message_id ?? '').trim(),
|
|
1063
|
+
kind,
|
|
1064
|
+
sender: sender !== '' ? sender : '未知联系人',
|
|
1065
|
+
senderId,
|
|
1066
|
+
text: text !== '' ? text : '[图片]',
|
|
1067
|
+
images: imageRefs.map((ref) => ({
|
|
1068
|
+
mediaId: ref.mediaId,
|
|
1069
|
+
file: '',
|
|
1070
|
+
mediaType: '',
|
|
1071
|
+
bytes: 0,
|
|
1072
|
+
state: 'pending',
|
|
1073
|
+
})),
|
|
1074
|
+
conversationId,
|
|
1075
|
+
conversationTitle: kind === 'group' ? this.titleCache.get(conversationId) || '' : '',
|
|
1076
|
+
at,
|
|
1077
|
+
profile,
|
|
1078
|
+
sourceKey: '',
|
|
1079
|
+
status: 'received',
|
|
1080
|
+
suggestion: null,
|
|
1081
|
+
reply: null,
|
|
1082
|
+
needsHuman: false,
|
|
1083
|
+
dismissed: false,
|
|
1084
|
+
error: '',
|
|
1085
|
+
quoted: this.extractQuoted(event),
|
|
1086
|
+
}
|
|
1087
|
+
record.sourceKey = sourceKeyOf(record)
|
|
1088
|
+
|
|
1089
|
+
// 推进本来源的滑动窗口:新消息进来,最早一条被挤出去。
|
|
1090
|
+
this.remember(record, {
|
|
1091
|
+
direction: 'in',
|
|
1092
|
+
sender: record.sender,
|
|
1093
|
+
text: record.text,
|
|
1094
|
+
at: record.at,
|
|
1095
|
+
key: record.messageId || record.id,
|
|
1096
|
+
})
|
|
1097
|
+
|
|
1098
|
+
this.state.messages.unshift(record)
|
|
1099
|
+
this.trimInbox()
|
|
1100
|
+
|
|
1101
|
+
if (kind === 'group' && conversationId !== '') this.resolveTitle(conversationId).catch(() => {})
|
|
1102
|
+
this.broadcast()
|
|
1103
|
+
if (record.images.length > 0) this.downloadImages(record).catch(() => {})
|
|
1104
|
+
this.enqueueSuggestion(record)
|
|
1105
|
+
this.saveState().catch(() => {})
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
extractQuoted(event) {
|
|
1109
|
+
const quoted = event?.quoted_message
|
|
1110
|
+
if (!quoted || typeof quoted !== 'object') return ''
|
|
1111
|
+
const text = extractEventText(quoted)
|
|
1112
|
+
if (text === '') return ''
|
|
1113
|
+
const who = String(quoted?.sender ?? '').trim()
|
|
1114
|
+
return who !== '' ? `${who}:${text.slice(0, 160)}` : text.slice(0, 160)
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
trimInbox() {
|
|
1118
|
+
const limit = this.config.maxInbox
|
|
1119
|
+
if (this.state.messages.length > limit) {
|
|
1120
|
+
this.state.messages.length = limit
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
async resolveTitle(conversationId) {
|
|
1125
|
+
if (this.titleCache.has(conversationId)) return this.titleCache.get(conversationId)
|
|
1126
|
+
this.titleCache.set(conversationId, '')
|
|
1127
|
+
|
|
1128
|
+
const result = await runDws(
|
|
1129
|
+
this.config.dwsPath,
|
|
1130
|
+
['chat', '+conversation-info', '--group', conversationId, '-f', 'json'],
|
|
1131
|
+
{ timeoutMs: 15000 },
|
|
1132
|
+
)
|
|
1133
|
+
const payload = parseLooseJson(result.stdout)
|
|
1134
|
+
const title = String(
|
|
1135
|
+
payload?.name ?? payload?.title ?? payload?.conversationName ?? payload?.conversation?.name ?? '',
|
|
1136
|
+
).trim()
|
|
1137
|
+
|
|
1138
|
+
if (title === '') {
|
|
1139
|
+
this.titleCache.delete(conversationId)
|
|
1140
|
+
return ''
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
this.titleCache.set(conversationId, title)
|
|
1144
|
+
let changed = false
|
|
1145
|
+
for (const item of this.state.messages) {
|
|
1146
|
+
if (item.conversationId === conversationId && item.conversationTitle !== title) {
|
|
1147
|
+
item.conversationTitle = title
|
|
1148
|
+
item.sourceKey = sourceKeyOf(item)
|
|
1149
|
+
changed = true
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
if (changed) this.broadcast()
|
|
1153
|
+
return title
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// -------------------------------------------------------------------- 图片
|
|
1157
|
+
|
|
1158
|
+
/** 图片落地目录(放在插件的状态目录下,与 state.json 同级)。 */
|
|
1159
|
+
/**
|
|
1160
|
+
* 插件数据目录(与状态文件同级),图片等二进制资源都落在这里。
|
|
1161
|
+
* 用它作为 dws 的工作目录:`--output` 只接受相对于工作目录的路径,
|
|
1162
|
+
* 而应用安装目录通常是只读的,不能作为下载落点。
|
|
1163
|
+
*/
|
|
1164
|
+
dataDir() {
|
|
1165
|
+
return dirname(this.statePath)
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
mediaDir() {
|
|
1169
|
+
return join(this.dataDir(), 'media')
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* 下载消息里的图片。钉钉事件只给 mediaId,必须用 `+messages-resource-download`
|
|
1174
|
+
* 才能真正拿到字节;`--output` 只接受相对工作目录的路径。
|
|
1175
|
+
*/
|
|
1176
|
+
async downloadImages(record) {
|
|
1177
|
+
const images = Array.isArray(record?.images) ? record.images : []
|
|
1178
|
+
if (images.length === 0) return
|
|
1179
|
+
if (record.messageId === '') {
|
|
1180
|
+
for (const image of images) {
|
|
1181
|
+
image.state = 'failed'
|
|
1182
|
+
image.error = '缺少 message_id,无法下载图片'
|
|
1183
|
+
}
|
|
1184
|
+
this.broadcast()
|
|
1185
|
+
return
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
let dirReady = false
|
|
1189
|
+
for (let index = 0; index < images.length; index += 1) {
|
|
1190
|
+
const image = images[index]
|
|
1191
|
+
if (image.file !== '' && image.state === 'ready') continue
|
|
1192
|
+
image.state = 'downloading'
|
|
1193
|
+
|
|
1194
|
+
if (!dirReady) {
|
|
1195
|
+
try {
|
|
1196
|
+
await mkdir(this.mediaDir(), { recursive: true })
|
|
1197
|
+
dirReady = true
|
|
1198
|
+
} catch {
|
|
1199
|
+
// 目录创建失败时让下面的下载命令自己报错。
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
const stamp = String(record.id || randomUUID()).replace(/[^\w-]/g, '').slice(0, 24)
|
|
1204
|
+
const relative = `media/${stamp}-${index}.png`
|
|
1205
|
+
const args = [
|
|
1206
|
+
'chat',
|
|
1207
|
+
'+messages-resource-download',
|
|
1208
|
+
'--type',
|
|
1209
|
+
'mediaId',
|
|
1210
|
+
'--resource-id',
|
|
1211
|
+
image.mediaId,
|
|
1212
|
+
'--message-id',
|
|
1213
|
+
record.messageId,
|
|
1214
|
+
'--output',
|
|
1215
|
+
relative,
|
|
1216
|
+
'-f',
|
|
1217
|
+
'json',
|
|
1218
|
+
]
|
|
1219
|
+
if (record.conversationId !== '') args.push('--open-conversation-id', record.conversationId)
|
|
1220
|
+
if (record.profile !== '') args.push('--profile', record.profile)
|
|
1221
|
+
|
|
1222
|
+
const result = await runDws(this.config.dwsPath, args, { cwd: this.dataDir(), timeoutMs: 45000 })
|
|
1223
|
+
const payload = parseLooseJson(result.stdout) || parseLooseJson(result.stderr)
|
|
1224
|
+
const localPath = String(payload?.localPath ?? payload?.local_path ?? '').trim()
|
|
1225
|
+
if (result.code !== 0 || localPath === '') {
|
|
1226
|
+
image.state = 'failed'
|
|
1227
|
+
image.error = describeFailure(result).slice(0, 200)
|
|
1228
|
+
continue
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
const file = localPath.replace(/\\/g, '/')
|
|
1232
|
+
try {
|
|
1233
|
+
const bytes = await readFile(join(this.dataDir(), file))
|
|
1234
|
+
const mediaType = sniffImageMediaType(bytes)
|
|
1235
|
+
if (mediaType === '') {
|
|
1236
|
+
image.state = 'failed'
|
|
1237
|
+
image.error = '下载到的文件不是可识别的图片'
|
|
1238
|
+
continue
|
|
1239
|
+
}
|
|
1240
|
+
image.file = file
|
|
1241
|
+
image.mediaType = mediaType
|
|
1242
|
+
image.bytes = bytes.length
|
|
1243
|
+
image.state = 'ready'
|
|
1244
|
+
} catch (error) {
|
|
1245
|
+
image.state = 'failed'
|
|
1246
|
+
image.error = String(error?.message || error)
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
this.broadcast()
|
|
1251
|
+
this.saveState().catch(() => {})
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/** 读插件自带的彩色图标(icon.png),供 GET /icon 与界面复用。 */
|
|
1255
|
+
async readIcon() {
|
|
1256
|
+
if (this.iconCache && this.iconCache.length > 0) return this.iconCache
|
|
1257
|
+
const bytes = await readFile(new URL('../../icon.png', import.meta.url))
|
|
1258
|
+
this.iconCache = bytes
|
|
1259
|
+
return bytes
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
/** 读一张已下载的图片字节,供 HTTP 路由与模型输入复用。 */
|
|
1263
|
+
async readMedia(record, index) {
|
|
1264
|
+
const image = Array.isArray(record?.images) ? record.images[index] : null
|
|
1265
|
+
if (!image || image.state !== 'ready' || image.file === '') return null
|
|
1266
|
+
const bytes = await readFile(join(this.dataDir(), image.file))
|
|
1267
|
+
return { image, bytes, mediaType: image.mediaType || sniffImageMediaType(bytes) || 'image/png' }
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
/**
|
|
1271
|
+
* 把消息图片交给模型。
|
|
1272
|
+
* 只有在模型确实声明支持图片输入、且附件服务可用时才附带图片;
|
|
1273
|
+
* 否则返回空数组,由 prompt 里的文字说明降级处理。
|
|
1274
|
+
*/
|
|
1275
|
+
async buildImageBlocks(record, selection, llm) {
|
|
1276
|
+
const images = Array.isArray(record?.images) ? record.images.filter((item) => item.state === 'ready') : []
|
|
1277
|
+
if (images.length === 0 || !selection) return { blocks: [], note: '' }
|
|
1278
|
+
|
|
1279
|
+
const attachments = this.ctx?.get?.('attachments')
|
|
1280
|
+
if (!attachments || typeof attachments.saveImage !== 'function') {
|
|
1281
|
+
return { blocks: [], note: '(消息含图片,但当前环境无法读取图片内容)' }
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
try {
|
|
1285
|
+
if (llm && typeof llm.resolveModelInfo === 'function') {
|
|
1286
|
+
const info = await llm.resolveModelInfo(selection.provider, selection.model)
|
|
1287
|
+
const modalities = Array.isArray(info?.inputModalities) ? info.inputModalities : null
|
|
1288
|
+
if (modalities !== null && !modalities.includes('image')) {
|
|
1289
|
+
return { blocks: [], note: '(消息含图片,但当前模型不支持图片输入,已忽略图片内容)' }
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
} catch {
|
|
1293
|
+
// 模型元数据不可用时按不支持处理,避免整次建议失败。
|
|
1294
|
+
return { blocks: [], note: '(消息含图片,但无法确认模型是否支持图片输入,已忽略图片内容)' }
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
const blocks = []
|
|
1298
|
+
for (let index = 0; index < images.length; index += 1) {
|
|
1299
|
+
try {
|
|
1300
|
+
const media = await this.readMedia(record, index)
|
|
1301
|
+
if (!media) continue
|
|
1302
|
+
const ref = await attachments.saveImage({
|
|
1303
|
+
data: media.bytes,
|
|
1304
|
+
mediaType: media.mediaType,
|
|
1305
|
+
name: `dingtalk-${record.id.slice(0, 12)}-${index}`,
|
|
1306
|
+
})
|
|
1307
|
+
blocks.push({ type: 'image', attachment: ref })
|
|
1308
|
+
} catch {
|
|
1309
|
+
// 单张失败不影响其余图片与文字建议。
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
return { blocks, note: blocks.length > 0 ? '' : '(消息含图片,但图片读取失败)' }
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
// ------------------------------------------------------- 钉钉侧历史上下文
|
|
1316
|
+
|
|
1317
|
+
/**
|
|
1318
|
+
* 从钉钉拉取该会话最新消息作为上下文。
|
|
1319
|
+
* 拉到的是会话真实历史,比插件本地内存里的更完整;失败时静默回退本地记录。
|
|
1320
|
+
*/
|
|
1321
|
+
async remoteHistory(record) {
|
|
1322
|
+
if (!this.config.remoteContext || this.config.remoteContextLimit <= 0) return []
|
|
1323
|
+
const conversationId = String(record?.conversationId ?? '')
|
|
1324
|
+
if (conversationId === '') return []
|
|
1325
|
+
|
|
1326
|
+
const cached = this.remoteCache.get(conversationId)
|
|
1327
|
+
if (cached && Date.now() - cached.at < 60 * 1000) return cached.entries
|
|
1328
|
+
|
|
1329
|
+
const args = [
|
|
1330
|
+
'chat',
|
|
1331
|
+
'+chat-messages',
|
|
1332
|
+
'--chat-id',
|
|
1333
|
+
conversationId,
|
|
1334
|
+
'--limit',
|
|
1335
|
+
String(this.config.remoteContextLimit),
|
|
1336
|
+
'-f',
|
|
1337
|
+
'json',
|
|
1338
|
+
]
|
|
1339
|
+
const result = await runDws(this.config.dwsPath, args, { timeoutMs: 20000 })
|
|
1340
|
+
if (result.code !== 0) return []
|
|
1341
|
+
const payload = parseLooseJson(result.stdout)
|
|
1342
|
+
const raw = payload?.data?.messages ?? payload?.messages ?? payload?.data?.items ?? payload?.items
|
|
1343
|
+
if (!Array.isArray(raw)) return []
|
|
1344
|
+
|
|
1345
|
+
const selfName = this.state.selfName
|
|
1346
|
+
const entries = []
|
|
1347
|
+
for (const item of raw) {
|
|
1348
|
+
if (!item || typeof item !== 'object') continue
|
|
1349
|
+
const text = stripImageMarkers(String(item.text ?? item.content ?? '')).slice(0, 400)
|
|
1350
|
+
if (text === '') continue
|
|
1351
|
+
const sender = String(item.sender ?? '').trim()
|
|
1352
|
+
entries.push({
|
|
1353
|
+
direction: selfName !== '' && sender === selfName ? 'out' : 'in',
|
|
1354
|
+
sender: sender !== '' ? sender : '对方',
|
|
1355
|
+
text,
|
|
1356
|
+
at: normalizeTimestamp(item.createTime ?? item.create_time ?? item.timestamp),
|
|
1357
|
+
messageId: String(item.messageId ?? item.message_id ?? ''),
|
|
1358
|
+
})
|
|
1359
|
+
}
|
|
1360
|
+
entries.sort((a, b) => a.at - b.at)
|
|
1361
|
+
if (entries.length > 0) this.remoteCache.set(conversationId, { at: Date.now(), entries })
|
|
1362
|
+
return entries
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
// ------------------------------------------------------- 每个来源的滑动窗口
|
|
1366
|
+
|
|
1367
|
+
/**
|
|
1368
|
+
* 消息按来源(私信=发送人,群 @=群会话)分桶,每个桶只保留最近 `windowMessages` 条。
|
|
1369
|
+
* 新消息进来就推进窗口、挤掉最早一条,AI 回复永远只看「本来源最近 N 条」。
|
|
1370
|
+
*/
|
|
1371
|
+
windowKeyOf(record) {
|
|
1372
|
+
return sourceKeyOf(record)
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
remember(record, entry) {
|
|
1376
|
+
const key = this.windowKeyOf(record)
|
|
1377
|
+
if (key === '' || !entry) return
|
|
1378
|
+
const list = this.windows.get(key) || []
|
|
1379
|
+
const id = String(entry.key ?? '')
|
|
1380
|
+
if (id !== '' && list.some((item) => item.key === id)) return
|
|
1381
|
+
const text = String(entry.text ?? '').trim()
|
|
1382
|
+
if (text === '') return
|
|
1383
|
+
list.push({
|
|
1384
|
+
direction: entry.direction === 'out' ? 'out' : 'in',
|
|
1385
|
+
sender: String(entry.sender ?? ''),
|
|
1386
|
+
text: text.slice(0, 400),
|
|
1387
|
+
at: Number(entry.at) || Date.now(),
|
|
1388
|
+
key: id,
|
|
1389
|
+
})
|
|
1390
|
+
list.sort((a, b) => a.at - b.at)
|
|
1391
|
+
const size = this.config.windowMessages
|
|
1392
|
+
this.windows.set(key, list.length > size ? list.slice(-size) : list)
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
windowEntries(record) {
|
|
1396
|
+
const list = this.windows.get(this.windowKeyOf(record)) || []
|
|
1397
|
+
const currentId = String(record?.messageId ?? '') || String(record?.id ?? '')
|
|
1398
|
+
return list.filter((item) => item.at <= Number(record?.at) && item.key !== currentId && item.key !== String(record?.id ?? ''))
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
/** 状态文件里存下所有窗口,重启后上下文不丢。 */
|
|
1402
|
+
windowSnapshot() {
|
|
1403
|
+
const out = {}
|
|
1404
|
+
for (const [key, list] of this.windows) out[key] = list
|
|
1405
|
+
return out
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
restoreWindows(raw) {
|
|
1409
|
+
this.windows.clear()
|
|
1410
|
+
if (!raw || typeof raw !== 'object') return
|
|
1411
|
+
const size = this.config.windowMessages
|
|
1412
|
+
for (const [key, list] of Object.entries(raw)) {
|
|
1413
|
+
if (typeof key !== 'string' || key === '' || !Array.isArray(list)) continue
|
|
1414
|
+
const entries = list
|
|
1415
|
+
.filter((item) => item && typeof item.text === 'string' && item.text.trim() !== '')
|
|
1416
|
+
.map((item) => ({
|
|
1417
|
+
direction: item.direction === 'out' ? 'out' : 'in',
|
|
1418
|
+
sender: String(item.sender ?? ''),
|
|
1419
|
+
text: String(item.text).slice(0, 400),
|
|
1420
|
+
at: Number(item.at) || Date.now(),
|
|
1421
|
+
key: String(item.key ?? ''),
|
|
1422
|
+
}))
|
|
1423
|
+
.sort((a, b) => a.at - b.at)
|
|
1424
|
+
if (entries.length === 0) continue
|
|
1425
|
+
this.windows.set(key, entries.slice(-size))
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
// -------------------------------------------------------------- 建议与自动回复
|
|
1430
|
+
|
|
1431
|
+
/**
|
|
1432
|
+
* 当前建议回复使用的模型。默认实时跟随 DSH 正在使用的大模型,
|
|
1433
|
+
* 只有插件配置显式指定 provider/model 时才覆盖。
|
|
1434
|
+
*/
|
|
1435
|
+
modelInfo() {
|
|
1436
|
+
const provider = this.config.suggestProvider
|
|
1437
|
+
const model = this.config.suggestModel
|
|
1438
|
+
let fallback = null
|
|
1439
|
+
try {
|
|
1440
|
+
const service = this.ctx?.get?.('agentDefaultModel')
|
|
1441
|
+
const selection = service?.currentSelection?.()
|
|
1442
|
+
if (selection && selection.provider && selection.model) fallback = selection
|
|
1443
|
+
} catch {
|
|
1444
|
+
fallback = null
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
if (provider !== '' && model !== '') {
|
|
1448
|
+
return {
|
|
1449
|
+
provider,
|
|
1450
|
+
model,
|
|
1451
|
+
reasoningEffort: this.config.suggestReasoningEffort || undefined,
|
|
1452
|
+
source: 'config',
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
if (provider !== '' && fallback) {
|
|
1456
|
+
return {
|
|
1457
|
+
provider,
|
|
1458
|
+
model: fallback.model,
|
|
1459
|
+
reasoningEffort: this.config.suggestReasoningEffort || fallback.reasoningEffort,
|
|
1460
|
+
source: 'hybrid',
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
if (fallback) {
|
|
1464
|
+
const info = {
|
|
1465
|
+
provider: fallback.provider,
|
|
1466
|
+
model: fallback.model,
|
|
1467
|
+
reasoningEffort: this.config.suggestReasoningEffort || fallback.reasoningEffort || undefined,
|
|
1468
|
+
source: 'dsh',
|
|
1469
|
+
}
|
|
1470
|
+
return info
|
|
1471
|
+
}
|
|
1472
|
+
return { provider: '', model: '', reasoningEffort: undefined, source: 'none' }
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
resolveSelection() {
|
|
1476
|
+
const info = this.modelInfo()
|
|
1477
|
+
if (info.provider === '' || info.model === '') return null
|
|
1478
|
+
return { provider: info.provider, model: info.model, reasoningEffort: info.reasoningEffort }
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
findMessage(id) {
|
|
1482
|
+
return this.state.messages.find((item) => item.id === id) || null
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
async buildHistory(record) {
|
|
1486
|
+
// 窗口负责「存多少」,contextMessages 负责「喂多少」,两者取小。
|
|
1487
|
+
const limit = Math.max(1, Math.min(this.config.windowMessages, this.config.contextMessages))
|
|
1488
|
+
|
|
1489
|
+
// 主来源:本来源自己的滑动窗口(含对方消息与我的回复,已按时间排序)。
|
|
1490
|
+
let entries = this.windowEntries(record).map((item) => ({ ...item }))
|
|
1491
|
+
|
|
1492
|
+
// 窗口还没攒满时,用钉钉侧最新消息补齐(首次接触某个来源、或刚清空收件箱时尤其有用)。
|
|
1493
|
+
if (entries.length < limit) {
|
|
1494
|
+
const remote = await this.remoteHistory(record).catch(() => [])
|
|
1495
|
+
for (const item of remote) {
|
|
1496
|
+
if (item.at > record.at) continue
|
|
1497
|
+
const key = item.messageId || `remote:${item.at}`
|
|
1498
|
+
if (entries.some((entry) => entry.key === key)) continue
|
|
1499
|
+
entries.push({ direction: item.direction, sender: item.sender, text: item.text, at: item.at, key })
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
const seen = new Set()
|
|
1504
|
+
entries = entries.filter((item) => {
|
|
1505
|
+
const key = item.key || `${item.direction}:${item.at}:${item.text.slice(0, 24)}`
|
|
1506
|
+
if (seen.has(key)) return false
|
|
1507
|
+
seen.add(key)
|
|
1508
|
+
return true
|
|
1509
|
+
})
|
|
1510
|
+
|
|
1511
|
+
entries.sort((a, b) => a.at - b.at)
|
|
1512
|
+
return entries.slice(-limit).map(({ direction, sender, text, at }) => ({
|
|
1513
|
+
direction,
|
|
1514
|
+
sender,
|
|
1515
|
+
text,
|
|
1516
|
+
at,
|
|
1517
|
+
}))
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/**
|
|
1521
|
+
* 这条消息现在还能不能由 AI 自动回复?
|
|
1522
|
+
* 必须同时满足:当前开着自动回复,且消息是在「本次开启」之后收到的。
|
|
1523
|
+
* 关闭期间积压、或关闭时正在生成建议的消息,一律不自动发送。
|
|
1524
|
+
*/
|
|
1525
|
+
canAutoReply(record) {
|
|
1526
|
+
if (!this.state.autoReply) return false
|
|
1527
|
+
const enabledAt = Number(this.state.autoReplyAt) || 0
|
|
1528
|
+
// 老状态文件没有时间戳时按「一直开着」处理,避免升级后全部拒绝自动回复。
|
|
1529
|
+
if (enabledAt <= 0) return true
|
|
1530
|
+
return Number(record?.at) >= enabledAt
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* 群消息回复要不要先 @ 发送人:谁 @ 我,我就 @ 谁。
|
|
1535
|
+
* 私信没有 @ 的概念;群聊需要 conversationId + 对方的 openDingTalkId。
|
|
1536
|
+
*/
|
|
1537
|
+
shouldAtSender(record) {
|
|
1538
|
+
if (!this.config.groupReplyAt) return false
|
|
1539
|
+
if (!record || record.kind !== 'group') return false
|
|
1540
|
+
return String(record.senderId ?? '') !== '' && String(record.conversationId ?? '') !== ''
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/** 关闭自动回复时,把还在排队/生成中的消息标记为「自动回复已取消」,稍后不会补发。 */ cancelPendingAutoReplies() {
|
|
1544
|
+
let touched = 0
|
|
1545
|
+
for (const record of this.state.messages) {
|
|
1546
|
+
if (record.reply && record.reply.ok) continue
|
|
1547
|
+
if (record.status === 'suggesting' || record.status === 'received' || record.status === 'sending') {
|
|
1548
|
+
record.autoCancelled = true
|
|
1549
|
+
record.needsHuman = false
|
|
1550
|
+
if (record.status === 'sending') record.status = 'suggested'
|
|
1551
|
+
touched += 1
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
return touched
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/** 清空收件箱(重新授权、手动清空都走这里),reason 用于界面提示。 */
|
|
1558
|
+
resetInbox(reason = '') {
|
|
1559
|
+
this.state.messages = []
|
|
1560
|
+
this.seen.clear()
|
|
1561
|
+
this.remoteCache.clear()
|
|
1562
|
+
this.windows.clear()
|
|
1563
|
+
this.state.inboxNotice = reason
|
|
1564
|
+
this.broadcast()
|
|
1565
|
+
this.saveState().catch(() => {})
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
enqueueSuggestion(record) {
|
|
1569
|
+
if (!this.config.autoSuggest) {
|
|
1570
|
+
record.status = 'received'
|
|
1571
|
+
return
|
|
1572
|
+
}
|
|
1573
|
+
if (!this.suggestQueue.includes(record.id)) this.suggestQueue.push(record.id)
|
|
1574
|
+
this.pumpSuggestQueue()
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
pumpSuggestQueue() {
|
|
1578
|
+
while (this.suggestBusy < SUGGEST_CONCURRENCY && this.suggestQueue.length > 0) {
|
|
1579
|
+
const id = this.suggestQueue.shift()
|
|
1580
|
+
const record = this.findMessage(id)
|
|
1581
|
+
if (!record || record.suggestion !== null) continue
|
|
1582
|
+
this.suggestBusy += 1
|
|
1583
|
+
this.refreshSuggestion(id)
|
|
1584
|
+
.catch(() => {})
|
|
1585
|
+
.finally(() => {
|
|
1586
|
+
this.suggestBusy -= 1
|
|
1587
|
+
this.pumpSuggestQueue()
|
|
1588
|
+
})
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
async refreshSuggestion(id, { manual = false } = {}) {
|
|
1593
|
+
const record = this.findMessage(id)
|
|
1594
|
+
if (!record) return
|
|
1595
|
+
|
|
1596
|
+
record.status = 'suggesting'
|
|
1597
|
+
record.error = ''
|
|
1598
|
+
this.broadcast()
|
|
1599
|
+
|
|
1600
|
+
const llm = this.ctx?.get?.('llm')
|
|
1601
|
+
const selection = this.resolveSelection()
|
|
1602
|
+
|
|
1603
|
+
// 图片要先落盘下载完再喂给模型;下载失败/模型不支持图片时降级为纯文本。
|
|
1604
|
+
const history = await this.buildHistory(record)
|
|
1605
|
+
const { blocks: imageBlocks, note: imageNote } = await this.buildImageBlocks(record, selection, llm)
|
|
1606
|
+
const prompt = buildSuggestPrompt({
|
|
1607
|
+
record,
|
|
1608
|
+
history,
|
|
1609
|
+
selfName: this.state.selfName || '我',
|
|
1610
|
+
imageNote,
|
|
1611
|
+
imageCount: imageBlocks.length,
|
|
1612
|
+
maxReplies: this.config.multiSendMax,
|
|
1613
|
+
})
|
|
1614
|
+
|
|
1615
|
+
const result = await generateSuggestion({
|
|
1616
|
+
llm,
|
|
1617
|
+
selection,
|
|
1618
|
+
prompt,
|
|
1619
|
+
images: imageBlocks,
|
|
1620
|
+
timeoutMs: this.config.suggestTimeoutMs,
|
|
1621
|
+
})
|
|
1622
|
+
|
|
1623
|
+
const current = this.findMessage(id)
|
|
1624
|
+
if (!current) return
|
|
1625
|
+
|
|
1626
|
+
current.suggestion = {
|
|
1627
|
+
text: result.reply,
|
|
1628
|
+
// 模型给出的「多条消息」:界面上会提示将分几条发送,自动回复时按顺序依次发出。
|
|
1629
|
+
replies: Array.isArray(result.replies) && result.replies.length > 0 ? result.replies : [result.reply].filter(Boolean),
|
|
1630
|
+
confidence: result.confidence,
|
|
1631
|
+
needsHuman: result.needsHuman,
|
|
1632
|
+
reason: result.reason,
|
|
1633
|
+
model: result.model,
|
|
1634
|
+
provider: result.provider,
|
|
1635
|
+
ok: result.ok,
|
|
1636
|
+
imageCount: imageBlocks.length,
|
|
1637
|
+
contextCount: history.length,
|
|
1638
|
+
at: Date.now(),
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
const unclear =
|
|
1642
|
+
!result.ok ||
|
|
1643
|
+
result.reply.trim() === '' ||
|
|
1644
|
+
result.needsHuman ||
|
|
1645
|
+
result.confidence < this.config.minConfidence
|
|
1646
|
+
|
|
1647
|
+
// 手动触发的「换一条建议 / 生成建议」只更新建议本身,绝不代替用户发送。
|
|
1648
|
+
if (manual) {
|
|
1649
|
+
current.status = result.ok ? 'suggested' : 'failed'
|
|
1650
|
+
current.needsHuman = false
|
|
1651
|
+
current.dismissed = false
|
|
1652
|
+
current.error = result.ok ? '' : result.reason
|
|
1653
|
+
this.broadcast()
|
|
1654
|
+
this.saveState().catch(() => {})
|
|
1655
|
+
return current
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
if (this.state.autoReply && this.canAutoReply(current)) {
|
|
1659
|
+
if (unclear) {
|
|
1660
|
+
current.status = 'needs-human'
|
|
1661
|
+
current.needsHuman = this.config.notifyModal
|
|
1662
|
+
current.dismissed = false
|
|
1663
|
+
current.error = result.ok ? '' : result.reason
|
|
1664
|
+
} else {
|
|
1665
|
+
await this.deliver(current, result.reply, {
|
|
1666
|
+
auto: true,
|
|
1667
|
+
imageCount: imageBlocks.length,
|
|
1668
|
+
replies: result.replies,
|
|
1669
|
+
})
|
|
1670
|
+
}
|
|
1671
|
+
} else {
|
|
1672
|
+
current.status = result.ok ? 'suggested' : 'failed'
|
|
1673
|
+
current.needsHuman = false
|
|
1674
|
+
current.error = result.ok ? '' : result.reason
|
|
1675
|
+
// 自动回复在生成过程中被关闭、或这条消息早于本次开启时间:只留建议,不自动发送。
|
|
1676
|
+
if (this.state.autoReplyTouched && result.ok && !current.autoCancelled) {
|
|
1677
|
+
current.autoCancelled = !this.state.autoReply || !this.canAutoReply(current)
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
this.broadcast()
|
|
1682
|
+
this.saveState().catch(() => {})
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
/** 真正把回复发到钉钉。 */
|
|
1686
|
+
async deliver(record, text, { auto = false, imageCount = 0, replies = [] } = {}) {
|
|
1687
|
+
// 群消息回复前先 @ 发送人(可配置 groupReplyAt 关闭),私信不需要。
|
|
1688
|
+
const atSender = this.shouldAtSender(record)
|
|
1689
|
+
const body = composeReplyBody({ record, text, replyPrefix: this.config.replyPrefix, atSender })
|
|
1690
|
+
if (body === '') return false
|
|
1691
|
+
|
|
1692
|
+
// 自动回复在「模型思考的这几秒」里可能已被用户关掉,或这条消息早于本次开启时间:
|
|
1693
|
+
// 发之前再判一次状态,避免关掉开关后仍然把回复发出去。
|
|
1694
|
+
if (auto && !this.canAutoReply(record)) {
|
|
1695
|
+
record.status = 'suggested'
|
|
1696
|
+
record.autoCancelled = true
|
|
1697
|
+
record.needsHuman = false
|
|
1698
|
+
record.reply = null
|
|
1699
|
+
this.broadcast()
|
|
1700
|
+
this.saveState().catch(() => {})
|
|
1701
|
+
return false
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
const imagesUsed = Math.max(
|
|
1705
|
+
imageCount,
|
|
1706
|
+
Array.isArray(record.images) ? record.images.filter((item) => item.state === 'ready').length : 0,
|
|
1707
|
+
)
|
|
1708
|
+
|
|
1709
|
+
if (record.kind === 'group' && record.conversationId === '') {
|
|
1710
|
+
record.reply = { text: String(text ?? ''), at: Date.now(), atSender, ok: false, error: '缺少群会话 ID,无法发送', auto }
|
|
1711
|
+
record.status = 'failed'
|
|
1712
|
+
this.broadcast()
|
|
1713
|
+
return false
|
|
1714
|
+
}
|
|
1715
|
+
if (record.kind !== 'group' && record.senderId === '') {
|
|
1716
|
+
record.reply = { text: String(text ?? ''), at: Date.now(), atSender, ok: false, error: '缺少对方 openDingTalkId,无法发送', auto }
|
|
1717
|
+
record.status = 'failed'
|
|
1718
|
+
this.broadcast()
|
|
1719
|
+
return false
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
// 上一次已经撞过幂等键(旧版本固定键留下的历史记录)时,直接从 -r2 开始,
|
|
1723
|
+
// 免得用户点一次失败、再点一次才成功。旧记录只有 error 文本,所以两种都认。
|
|
1724
|
+
const burnedKey = Boolean(
|
|
1725
|
+
(record.reply && record.reply.duplicate) ||
|
|
1726
|
+
isDuplicateSendFailure(record.error) ||
|
|
1727
|
+
isDuplicateSendFailure(record.reply && record.reply.error),
|
|
1728
|
+
)
|
|
1729
|
+
const attempt = Math.max(0, Number(record.sendAttempts) || 0, burnedKey ? 1 : 0)
|
|
1730
|
+
record.sendAttempts = attempt + 1
|
|
1731
|
+
const parts = planReplyParts({
|
|
1732
|
+
text,
|
|
1733
|
+
replies,
|
|
1734
|
+
multiSend: this.config.multiSend,
|
|
1735
|
+
max: this.config.multiSendMax,
|
|
1736
|
+
})
|
|
1737
|
+
if (parts.length === 0) return false
|
|
1738
|
+
|
|
1739
|
+
const sent = []
|
|
1740
|
+
let failureText = ''
|
|
1741
|
+
let duplicateAny = false
|
|
1742
|
+
for (let index = 0; index < parts.length; index += 1) {
|
|
1743
|
+
const part = parts[index]
|
|
1744
|
+
const partIndex = index + 1
|
|
1745
|
+
// 只有第一条带 @ 提及,避免群里被连 @ 多次。
|
|
1746
|
+
const partAt = atSender && partIndex === 1
|
|
1747
|
+
const partBody = composeReplyBody({ record, text: part, replyPrefix: this.config.replyPrefix, atSender: partAt })
|
|
1748
|
+
if (partBody === '') continue
|
|
1749
|
+
const args = buildSendArgs({
|
|
1750
|
+
record: { ...record, profile: this.knownProfile(record.profile) },
|
|
1751
|
+
body: partBody,
|
|
1752
|
+
auto,
|
|
1753
|
+
dryRun: this.config.dryRun,
|
|
1754
|
+
attempt,
|
|
1755
|
+
atSender: partAt,
|
|
1756
|
+
partIndex,
|
|
1757
|
+
})
|
|
1758
|
+
let result = await runDws(this.config.dwsPath, args, { timeoutMs: 45000 })
|
|
1759
|
+
let payload = parseLooseJson(result.stdout)
|
|
1760
|
+
// 记录里的 profile 已被移除(例如重新授权后 profile 标识变化)时,回退到 dws 当前登录账号重试一次。
|
|
1761
|
+
if (result.code !== 0 && /profile\b.*not found/i.test(`${result.stderr}${result.stdout}`) && args.includes('--profile')) {
|
|
1762
|
+
const retryArgs = buildSendArgs({
|
|
1763
|
+
record: { ...record, profile: '' },
|
|
1764
|
+
body: partBody,
|
|
1765
|
+
auto,
|
|
1766
|
+
dryRun: this.config.dryRun,
|
|
1767
|
+
attempt,
|
|
1768
|
+
atSender: partAt,
|
|
1769
|
+
partIndex,
|
|
1770
|
+
})
|
|
1771
|
+
result = await runDws(this.config.dwsPath, retryArgs, { timeoutMs: 45000 })
|
|
1772
|
+
payload = parseLooseJson(result.stdout)
|
|
1773
|
+
}
|
|
1774
|
+
const failed =
|
|
1775
|
+
result.code !== 0 ||
|
|
1776
|
+
(payload &&
|
|
1777
|
+
(payload.ok === false ||
|
|
1778
|
+
typeof payload?.error === 'string' ||
|
|
1779
|
+
(payload?.error && typeof payload.error === 'object')))
|
|
1780
|
+
const duplicate = failed && isDuplicateSendFailure(`${result.stderr}\n${result.stdout}\n${describeFailure(result)}`)
|
|
1781
|
+
if (duplicate) duplicateAny = true
|
|
1782
|
+
sent.push({ text: part, ok: !failed, error: failed ? (duplicate ? '幂等键重复(已提交过)' : describeFailure(result)) : '' })
|
|
1783
|
+
if (failed) {
|
|
1784
|
+
failureText = duplicate
|
|
1785
|
+
? '钉钉提示这条回复已经用同一个幂等键提交过(Request is repeated)。如果对方没收到,再点「发送」会自动换新的幂等键重发。'
|
|
1786
|
+
: describeFailure(result)
|
|
1787
|
+
break
|
|
1788
|
+
}
|
|
1789
|
+
// 连续发多条时留一点间隔,读起来更像人发的,也避免触发钉钉的频率限制。
|
|
1790
|
+
if (partIndex < parts.length) {
|
|
1791
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(100, this.config.multiSendDelayMs)))
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
const failed = failureText !== ''
|
|
1796
|
+
record.reply = {
|
|
1797
|
+
// 存纯回复正文(不含 <@id> 占位符),界面上用 atSender 标记「已 @ 对方」。
|
|
1798
|
+
text: sent.map((item) => item.text).join('\n'),
|
|
1799
|
+
parts: sent,
|
|
1800
|
+
partCount: parts.length,
|
|
1801
|
+
at: Date.now(),
|
|
1802
|
+
atSender,
|
|
1803
|
+
ok: !failed,
|
|
1804
|
+
error: failureText,
|
|
1805
|
+
auto,
|
|
1806
|
+
dryRun: this.config.dryRun === true,
|
|
1807
|
+
duplicate: duplicateAny,
|
|
1808
|
+
attempt: record.sendAttempts,
|
|
1809
|
+
matchBy: imagesUsed > 0 ? 'images' : 'text',
|
|
1810
|
+
imageCount: imagesUsed,
|
|
1811
|
+
}
|
|
1812
|
+
record.status = failed ? 'failed' : auto ? 'auto-replied' : 'replied'
|
|
1813
|
+
if (failed) record.error = record.reply.error
|
|
1814
|
+
else {
|
|
1815
|
+
record.error = ''
|
|
1816
|
+
record.needsHuman = false
|
|
1817
|
+
if (this.config.dryRun === true) record.error = '演练模式:仅预览发送内容,未真实发送'
|
|
1818
|
+
// 我发出去的回复也进窗口,下一轮 AI 才知道「我刚刚已经回过什么」。
|
|
1819
|
+
this.remember(record, {
|
|
1820
|
+
direction: 'out',
|
|
1821
|
+
sender: this.state.selfName || '我',
|
|
1822
|
+
text: record.reply.text,
|
|
1823
|
+
at: record.reply.at,
|
|
1824
|
+
key: `${record.id}:reply`,
|
|
1825
|
+
})
|
|
1826
|
+
}
|
|
1827
|
+
this.broadcast()
|
|
1828
|
+
this.saveState().catch(() => {})
|
|
1829
|
+
return !failed
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
// ---------------------------------------------------------------------- HTTP
|
|
1833
|
+
|
|
1834
|
+
handleHttp(ctx, req, res) {
|
|
1835
|
+
this.dispatchHttp(ctx, req, res).catch((error) => {
|
|
1836
|
+
try {
|
|
1837
|
+
res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
|
|
1838
|
+
res.end(JSON.stringify({ ok: false, error: String(error?.message || error) }))
|
|
1839
|
+
} catch {
|
|
1840
|
+
// 响应可能已经结束。
|
|
1841
|
+
}
|
|
1842
|
+
})
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
async dispatchHttp(ctx, req, res) {
|
|
1846
|
+
const connection = ctx?.get?.('connection')
|
|
1847
|
+
if (!connection || typeof connection.requestRejection !== 'function') {
|
|
1848
|
+
this.sendJson(res, 503, { ok: false, error: 'connection service unavailable' })
|
|
1849
|
+
return
|
|
1850
|
+
}
|
|
1851
|
+
const rejection = connection.requestRejection(req)
|
|
1852
|
+
if (rejection !== undefined) {
|
|
1853
|
+
const status = Number(rejection) || 403
|
|
1854
|
+
const detail = `rejected site=${req.headers?.['sec-fetch-site'] ?? '-'} origin=${req.headers?.origin ?? '-'} host=${req.headers?.host ?? '-'}`
|
|
1855
|
+
this.noteRequest(String(req.method ?? 'GET'), String(req.url ?? '/'), status, detail)
|
|
1856
|
+
this.sendJson(res, status, { ok: false, error: status === 401 ? 'unauthorized' : 'forbidden' })
|
|
1857
|
+
return
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
1861
|
+
const path = url.pathname
|
|
1862
|
+
const method = (req.method ?? 'GET').toUpperCase()
|
|
1863
|
+
|
|
1864
|
+
if (path === `${ROUTE_PREFIX}/state` && method === 'GET') {
|
|
1865
|
+
this.sendJson(res, 200, { ok: true, state: this.snapshot() })
|
|
1866
|
+
return
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
if (path === `${ROUTE_PREFIX}/events` && method === 'GET') {
|
|
1870
|
+
this.attachSse(res)
|
|
1871
|
+
return
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// 插件图标:GET /icon —— 客户端侧边栏与面板头部渲染彩色图标用
|
|
1875
|
+
if (path === `${ROUTE_PREFIX}/icon` && method === 'GET') {
|
|
1876
|
+
try {
|
|
1877
|
+
const bytes = await this.readIcon()
|
|
1878
|
+
res.writeHead(200, {
|
|
1879
|
+
'content-type': 'image/png',
|
|
1880
|
+
'content-length': String(bytes.length),
|
|
1881
|
+
'cache-control': 'private, max-age=86400',
|
|
1882
|
+
})
|
|
1883
|
+
res.end(bytes)
|
|
1884
|
+
} catch (error) {
|
|
1885
|
+
this.sendJson(res, 404, { ok: false, error: String(error?.message || error) })
|
|
1886
|
+
}
|
|
1887
|
+
return
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
// 消息图片:GET /media?id=<消息 id>&i=<序号>
|
|
1891
|
+
if (path === `${ROUTE_PREFIX}/media` && method === 'GET') {
|
|
1892
|
+
const id = url.searchParams.get('id') ?? ''
|
|
1893
|
+
const index = Number.parseInt(url.searchParams.get('i') ?? '0', 10)
|
|
1894
|
+
const record = this.findMessage(id)
|
|
1895
|
+
if (!record) {
|
|
1896
|
+
this.sendJson(res, 404, { ok: false, error: 'message not found' })
|
|
1897
|
+
return
|
|
1898
|
+
}
|
|
1899
|
+
try {
|
|
1900
|
+
const media = await this.readMedia(record, Number.isFinite(index) ? index : 0)
|
|
1901
|
+
if (!media) {
|
|
1902
|
+
this.sendJson(res, 404, { ok: false, error: 'image not available' })
|
|
1903
|
+
return
|
|
1904
|
+
}
|
|
1905
|
+
res.writeHead(200, {
|
|
1906
|
+
'content-type': media.mediaType,
|
|
1907
|
+
'content-length': String(media.bytes.length),
|
|
1908
|
+
'cache-control': 'private, max-age=600',
|
|
1909
|
+
})
|
|
1910
|
+
res.end(media.bytes)
|
|
1911
|
+
} catch (error) {
|
|
1912
|
+
this.sendJson(res, 500, { ok: false, error: String(error?.message || error) })
|
|
1913
|
+
}
|
|
1914
|
+
return
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
if (path === `${ROUTE_PREFIX}/action` && method === 'POST') {
|
|
1918
|
+
const body = await this.readBody(req)
|
|
1919
|
+
let payload = null
|
|
1920
|
+
try {
|
|
1921
|
+
payload = JSON.parse(body || '{}')
|
|
1922
|
+
} catch {
|
|
1923
|
+
this.noteRequest(method, path, 400, 'invalid json body')
|
|
1924
|
+
this.sendJson(res, 400, { ok: false, error: 'invalid json body' })
|
|
1925
|
+
return
|
|
1926
|
+
}
|
|
1927
|
+
const result = await this.handleAction(ctx, payload ?? {})
|
|
1928
|
+
this.noteRequest(method, path, 200, String(payload?.type ?? ''))
|
|
1929
|
+
this.sendJson(res, 200, { ok: result.ok !== false, ...result, state: this.snapshot() })
|
|
1930
|
+
return
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// 某些宿主/浏览器组合里 POST 会被安全护栏拦下(GET 正常),客户端会自动改用
|
|
1934
|
+
// 带查询参数的 GET /action... 作为兜底通道,两边执行同一套 handleAction。
|
|
1935
|
+
if (path === `${ROUTE_PREFIX}/action` && method === 'GET') {
|
|
1936
|
+
const payload = {}
|
|
1937
|
+
for (const [key, raw] of url.searchParams.entries()) {
|
|
1938
|
+
if (key === 'value') payload[key] = Number(raw)
|
|
1939
|
+
else if (raw === 'true') payload[key] = true
|
|
1940
|
+
else if (raw === 'false') payload[key] = false
|
|
1941
|
+
else payload[key] = raw
|
|
1942
|
+
}
|
|
1943
|
+
const result = await this.handleAction(ctx, payload)
|
|
1944
|
+
this.noteRequest(method, path, 200, String(payload.type ?? ''))
|
|
1945
|
+
this.sendJson(res, 200, { ok: result.ok !== false, ...result, state: this.snapshot() })
|
|
1946
|
+
return
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
this.sendJson(res, 404, { ok: false, error: 'not found' })
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/** 记录最近若干次 API 请求,便于排查「按钮点了没反应」这类环境问题。 */
|
|
1953
|
+
noteRequest(method, path, status, detail = '') {
|
|
1954
|
+
const entry = { at: Date.now(), method, path, status, detail: String(detail).slice(0, 120) }
|
|
1955
|
+
if (!Array.isArray(this.requestLog)) this.requestLog = []
|
|
1956
|
+
this.requestLog.push(entry)
|
|
1957
|
+
if (this.requestLog.length > 20) this.requestLog.splice(0, this.requestLog.length - 20)
|
|
1958
|
+
if (status >= 400) this.lastError = `${method} ${path} → ${status}`
|
|
1959
|
+
const line = `${new Date(entry.at).toISOString()} ${method} ${path} ${status} ${entry.detail}\n`
|
|
1960
|
+
appendFile(join(this.dataDir(), 'http-debug.log'), line).catch(() => {})
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
async readBody(req) {
|
|
1964
|
+
const chunks = []
|
|
1965
|
+
let size = 0
|
|
1966
|
+
for await (const chunk of req) {
|
|
1967
|
+
size += chunk.length
|
|
1968
|
+
if (size > BODY_LIMIT) throw new Error('request body too large')
|
|
1969
|
+
chunks.push(chunk)
|
|
1970
|
+
}
|
|
1971
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
sendJson(res, status, payload) {
|
|
1975
|
+
try {
|
|
1976
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
1977
|
+
res.end(JSON.stringify(payload))
|
|
1978
|
+
} catch {
|
|
1979
|
+
// 连接已断开。
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
attachSse(res) {
|
|
1984
|
+
try {
|
|
1985
|
+
res.writeHead(200, {
|
|
1986
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
1987
|
+
'cache-control': 'no-store',
|
|
1988
|
+
connection: 'keep-alive',
|
|
1989
|
+
'x-accel-buffering': 'no',
|
|
1990
|
+
})
|
|
1991
|
+
res.write(`data: ${JSON.stringify(this.snapshot())}\n\n`)
|
|
1992
|
+
} catch {
|
|
1993
|
+
return
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
this.sseClients.add(res)
|
|
1997
|
+
const ping = setInterval(() => {
|
|
1998
|
+
if (this.stopped) return
|
|
1999
|
+
try {
|
|
2000
|
+
res.write(': ping\n\n')
|
|
2001
|
+
} catch {
|
|
2002
|
+
// 忽略。
|
|
2003
|
+
}
|
|
2004
|
+
}, 25000)
|
|
2005
|
+
if (typeof ping.unref === 'function') ping.unref()
|
|
2006
|
+
|
|
2007
|
+
res.on('close', () => {
|
|
2008
|
+
clearInterval(ping)
|
|
2009
|
+
this.sseClients.delete(res)
|
|
2010
|
+
})
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
broadcast() {
|
|
2014
|
+
if (this.sseClients.size === 0) return
|
|
2015
|
+
const frame = `data: ${JSON.stringify(this.snapshot())}\n\n`
|
|
2016
|
+
for (const res of this.sseClients) {
|
|
2017
|
+
try {
|
|
2018
|
+
res.write(frame)
|
|
2019
|
+
} catch {
|
|
2020
|
+
this.sseClients.delete(res)
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
// -------------------------------------------------------------------- action
|
|
2026
|
+
|
|
2027
|
+
async handleAction(ctx, payload) {
|
|
2028
|
+
const type = String(payload.type ?? '')
|
|
2029
|
+
|
|
2030
|
+
switch (type) {
|
|
2031
|
+
case 'set-auto-reply': {
|
|
2032
|
+
const enabled = Boolean(payload.enabled)
|
|
2033
|
+
this.state.autoReply = enabled
|
|
2034
|
+
this.state.autoReplyTouched = true
|
|
2035
|
+
// 记录「本次开启」的时刻:只有在这之后到达的消息才允许自动回复,
|
|
2036
|
+
// 这样关掉再打开不会把关闭期间积压的旧消息补发出去。
|
|
2037
|
+
if (enabled) this.state.autoReplyAt = Date.now()
|
|
2038
|
+
if (!enabled) this.cancelPendingAutoReplies()
|
|
2039
|
+
this.broadcast()
|
|
2040
|
+
await this.saveState()
|
|
2041
|
+
return { ok: true }
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
case 'set-min-confidence': {
|
|
2045
|
+
const value = Math.round(asNumber(payload.value, this.config.minConfidence, 0.3, 1) * 100) / 100
|
|
2046
|
+
this.config.minConfidence = value
|
|
2047
|
+
this.broadcast()
|
|
2048
|
+
await this.saveState()
|
|
2049
|
+
return { ok: true }
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
// 上下文窗口长度:每个来源各留最近 N 条,改动立即生效并落盘。
|
|
2053
|
+
case 'set-window-messages': {
|
|
2054
|
+
const size = Math.round(asNumber(payload.value, this.config.windowMessages, 2, 20))
|
|
2055
|
+
this.config.windowMessages = size
|
|
2056
|
+
for (const [key, entries] of this.windows.entries()) {
|
|
2057
|
+
this.windows.set(key, entries.slice(-size))
|
|
2058
|
+
}
|
|
2059
|
+
this.broadcast()
|
|
2060
|
+
await this.saveState()
|
|
2061
|
+
return { ok: true }
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
case 'login-start': {
|
|
2065
|
+
return await this.startLogin()
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
case 'login-cancel': {
|
|
2069
|
+
return this.cancelLogin()
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
case 'logout': {
|
|
2073
|
+
return await this.logoutAll()
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
case 'send-reply': {
|
|
2077
|
+
const record = this.findMessage(String(payload.id ?? ''))
|
|
2078
|
+
if (!record) return { ok: false, error: '消息不存在' }
|
|
2079
|
+
const typed = String(payload.text ?? '').trim()
|
|
2080
|
+
const text = typed || String(record.suggestion?.text ?? '').trim()
|
|
2081
|
+
if (text === '') return { ok: false, error: '回复内容为空' }
|
|
2082
|
+
// 用户没改建议就点发送时,沿用模型拆好的多条(「给我发 10 条试试」这种需求)。
|
|
2083
|
+
const replies = typed === '' && Array.isArray(record.suggestion?.replies) ? record.suggestion.replies : []
|
|
2084
|
+
const ok = await this.deliver(record, text, { auto: false, replies })
|
|
2085
|
+
return { ok }
|
|
2086
|
+
}
|
|
2087
|
+
|
|
2088
|
+
case 'regenerate': {
|
|
2089
|
+
const record = this.findMessage(String(payload.id ?? ''))
|
|
2090
|
+
if (!record) return { ok: false, error: '消息不存在' }
|
|
2091
|
+
record.suggestion = null
|
|
2092
|
+
await this.refreshSuggestion(record.id, { manual: true })
|
|
2093
|
+
return { ok: true }
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
case 'dismiss': {
|
|
2097
|
+
const record = this.findMessage(String(payload.id ?? ''))
|
|
2098
|
+
if (record) {
|
|
2099
|
+
record.dismissed = true
|
|
2100
|
+
if (record.status === 'needs-human') record.status = 'waiting'
|
|
2101
|
+
this.broadcast()
|
|
2102
|
+
await this.saveState()
|
|
2103
|
+
}
|
|
2104
|
+
return { ok: true }
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
case 'clear-inbox': {
|
|
2108
|
+
this.state.messages = []
|
|
2109
|
+
this.state.inboxNotice = '收件箱已清空'
|
|
2110
|
+
this.broadcast()
|
|
2111
|
+
await this.saveState()
|
|
2112
|
+
return { ok: true }
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
case 'remove': {
|
|
2116
|
+
const id = String(payload.id ?? '')
|
|
2117
|
+
this.state.messages = this.state.messages.filter((item) => item.id !== id)
|
|
2118
|
+
this.broadcast()
|
|
2119
|
+
await this.saveState()
|
|
2120
|
+
return { ok: true }
|
|
2121
|
+
}
|
|
2122
|
+
|
|
2123
|
+
case 'restart-listeners': {
|
|
2124
|
+
await this.checkTool()
|
|
2125
|
+
await this.restartAll()
|
|
2126
|
+
return { ok: true }
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
case 'refresh': {
|
|
2130
|
+
await this.checkTool()
|
|
2131
|
+
await this.refreshProfiles()
|
|
2132
|
+
await this.refreshVision()
|
|
2133
|
+
this.startAllListeners()
|
|
2134
|
+
this.broadcast()
|
|
2135
|
+
return { ok: true }
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
default:
|
|
2139
|
+
return { ok: false, error: `unknown action: ${type}` }
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
// ------------------------------------------------------------------ snapshot
|
|
2144
|
+
|
|
2145
|
+
snapshot() {
|
|
2146
|
+
const messages = this.state.messages
|
|
2147
|
+
const sources = new Map()
|
|
2148
|
+
for (const item of messages) {
|
|
2149
|
+
const key = item.sourceKey || sourceKeyOf(item)
|
|
2150
|
+
const existing = sources.get(key)
|
|
2151
|
+
if (existing) {
|
|
2152
|
+
existing.count += 1
|
|
2153
|
+
existing.lastAt = Math.max(existing.lastAt, item.at)
|
|
2154
|
+
} else {
|
|
2155
|
+
sources.set(key, {
|
|
2156
|
+
key,
|
|
2157
|
+
kind: item.kind,
|
|
2158
|
+
sender: item.sender,
|
|
2159
|
+
senderId: item.senderId,
|
|
2160
|
+
conversationTitle: item.conversationTitle,
|
|
2161
|
+
count: 1,
|
|
2162
|
+
lastAt: item.at,
|
|
2163
|
+
})
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
const pending = messages.filter((item) => item.needsHuman && !item.dismissed && item.status !== 'replied')
|
|
2168
|
+
|
|
2169
|
+
return {
|
|
2170
|
+
enabled: this.config.enabled,
|
|
2171
|
+
build: HOST_BUILD,
|
|
2172
|
+
started: this.started,
|
|
2173
|
+
tool: this.tool,
|
|
2174
|
+
selfName: this.state.selfName,
|
|
2175
|
+
currentProfile: this.state.currentProfile,
|
|
2176
|
+
profiles: this.state.profiles,
|
|
2177
|
+
expiredProfiles: this.expiredProfiles().map((item) => ({
|
|
2178
|
+
profile: item.profile,
|
|
2179
|
+
corpName: item.corpName,
|
|
2180
|
+
userName: item.userName,
|
|
2181
|
+
status: item.status,
|
|
2182
|
+
})),
|
|
2183
|
+
loginReset: this.config.loginReset,
|
|
2184
|
+
autoReply: this.state.autoReply,
|
|
2185
|
+
autoReplyAt: Number(this.state.autoReplyAt) || 0,
|
|
2186
|
+
autoSuggest: this.config.autoSuggest,
|
|
2187
|
+
notifyModal: this.config.notifyModal,
|
|
2188
|
+
minConfidence: this.config.minConfidence,
|
|
2189
|
+
contextMessages: this.config.contextMessages,
|
|
2190
|
+
windowMessages: this.config.windowMessages,
|
|
2191
|
+
windowCount: this.windows.size,
|
|
2192
|
+
remoteContext: this.config.remoteContext,
|
|
2193
|
+
remoteContextLimit: this.config.remoteContextLimit,
|
|
2194
|
+
imageRecognition: this.config.imageRecognition,
|
|
2195
|
+
imageMax: this.config.imageMax,
|
|
2196
|
+
vision: this.vision,
|
|
2197
|
+
replyPrefix: this.config.replyPrefix,
|
|
2198
|
+
groupReplyAt: this.config.groupReplyAt,
|
|
2199
|
+
multiSend: this.config.multiSend,
|
|
2200
|
+
multiSendMax: this.config.multiSendMax,
|
|
2201
|
+
multiSendDelayMs: this.config.multiSendDelayMs,
|
|
2202
|
+
dryRun: this.config.dryRun,
|
|
2203
|
+
model: this.modelInfo(),
|
|
2204
|
+
login: this.login,
|
|
2205
|
+
listeners: [...this.listeners.values()].map((entry) => ({
|
|
2206
|
+
profile: entry.profile,
|
|
2207
|
+
status: entry.status,
|
|
2208
|
+
since: entry.since,
|
|
2209
|
+
readyAt: entry.readyAt,
|
|
2210
|
+
lastEventAt: entry.lastEventAt,
|
|
2211
|
+
error: entry.error,
|
|
2212
|
+
})),
|
|
2213
|
+
messages: messages.map((item) => ({
|
|
2214
|
+
id: item.id,
|
|
2215
|
+
messageId: item.messageId,
|
|
2216
|
+
kind: item.kind,
|
|
2217
|
+
sender: item.sender,
|
|
2218
|
+
senderId: item.senderId,
|
|
2219
|
+
text: item.text,
|
|
2220
|
+
conversationId: item.conversationId,
|
|
2221
|
+
conversationTitle: item.conversationTitle,
|
|
2222
|
+
sourceKey: item.sourceKey,
|
|
2223
|
+
at: item.at,
|
|
2224
|
+
atText: formatClock(item.at),
|
|
2225
|
+
status: item.status,
|
|
2226
|
+
suggestion: item.suggestion,
|
|
2227
|
+
reply: item.reply,
|
|
2228
|
+
needsHuman: item.needsHuman,
|
|
2229
|
+
dismissed: item.dismissed,
|
|
2230
|
+
error: item.error,
|
|
2231
|
+
quoted: item.quoted,
|
|
2232
|
+
autoCancelled: Boolean(item.autoCancelled),
|
|
2233
|
+
sendAttempts: Number(item.sendAttempts) || 0,
|
|
2234
|
+
images: (Array.isArray(item.images) ? item.images : []).map((image, index) => ({
|
|
2235
|
+
index,
|
|
2236
|
+
state: image.state,
|
|
2237
|
+
mediaType: image.mediaType,
|
|
2238
|
+
bytes: image.bytes,
|
|
2239
|
+
error: image.error ?? '',
|
|
2240
|
+
})),
|
|
2241
|
+
})),
|
|
2242
|
+
sources: [...sources.values()].sort((a, b) => b.lastAt - a.lastAt),
|
|
2243
|
+
pendingCount: pending.length,
|
|
2244
|
+
requests: Array.isArray(this.requestLog) ? this.requestLog.slice(-8).map((entry) => ({
|
|
2245
|
+
at: entry.at,
|
|
2246
|
+
method: entry.method,
|
|
2247
|
+
status: entry.status,
|
|
2248
|
+
detail: entry.detail,
|
|
2249
|
+
})) : [],
|
|
2250
|
+
lastError: this.lastError ?? '',
|
|
2251
|
+
inboxNotice: String(this.state.inboxNotice ?? ''),
|
|
2252
|
+
serverTime: Date.now(),
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
// ----------------------------------------------------------------- persistence
|
|
2257
|
+
|
|
2258
|
+
async loadState() {
|
|
2259
|
+
try {
|
|
2260
|
+
const raw = await readFile(this.statePath, 'utf8')
|
|
2261
|
+
const payload = JSON.parse(raw)
|
|
2262
|
+
if (payload && typeof payload === 'object') {
|
|
2263
|
+
if (typeof payload.autoReply === 'boolean' && payload.autoReplyTouched === true) {
|
|
2264
|
+
this.state.autoReply = payload.autoReply
|
|
2265
|
+
}
|
|
2266
|
+
this.state.autoReplyTouched = payload.autoReplyTouched === true
|
|
2267
|
+
if (Number.isFinite(payload.autoReplyAt) && payload.autoReplyAt > 0) {
|
|
2268
|
+
this.state.autoReplyAt = payload.autoReplyAt
|
|
2269
|
+
} else if (this.state.autoReply) {
|
|
2270
|
+
// 老状态文件没有开启时间:按「一直开着」处理,不误伤升级后的自动回复。
|
|
2271
|
+
this.state.autoReplyAt = 0
|
|
2272
|
+
}
|
|
2273
|
+
if (Array.isArray(payload.messages)) {
|
|
2274
|
+
this.state.messages = payload.messages
|
|
2275
|
+
.filter((item) => item && typeof item.id === 'string' && typeof item.text === 'string')
|
|
2276
|
+
.slice(0, this.config.maxInbox)
|
|
2277
|
+
.map((item) =>
|
|
2278
|
+
healLegacyFailure({
|
|
2279
|
+
...item,
|
|
2280
|
+
// 旧存档里的图片消息正文带着钉钉的下载提示,读档时顺手清理一遍。
|
|
2281
|
+
text: stripImageMarkers(String(item.text ?? '')),
|
|
2282
|
+
at: repairStoredTime(item.at),
|
|
2283
|
+
sender: String(item.sender ?? '未知联系人'),
|
|
2284
|
+
sourceKey: item.sourceKey || sourceKeyOf(item),
|
|
2285
|
+
suggestion: item.suggestion ?? null,
|
|
2286
|
+
reply: item.reply ?? null,
|
|
2287
|
+
needsHuman: Boolean(item.needsHuman),
|
|
2288
|
+
dismissed: Boolean(item.dismissed),
|
|
2289
|
+
error: String(item.error ?? ''),
|
|
2290
|
+
quoted: String(item.quoted ?? ''),
|
|
2291
|
+
images: Array.isArray(item.images) ? item.images : [],
|
|
2292
|
+
sendAttempts: Number(item.sendAttempts) || 0,
|
|
2293
|
+
}),
|
|
2294
|
+
)
|
|
2295
|
+
}
|
|
2296
|
+
if (payload.titles && typeof payload.titles === 'object') {
|
|
2297
|
+
for (const [key, value] of Object.entries(payload.titles)) {
|
|
2298
|
+
if (typeof value === 'string' && value !== '') this.titleCache.set(key, value)
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
if (typeof payload.selfName === 'string' && payload.selfName !== '') {
|
|
2302
|
+
this.state.selfName = payload.selfName
|
|
2303
|
+
}
|
|
2304
|
+
if (typeof payload.minConfidence === 'number' && payload.minConfidence > 0 && payload.minConfidence <= 1) {
|
|
2305
|
+
this.config.minConfidence = payload.minConfidence
|
|
2306
|
+
}
|
|
2307
|
+
if (typeof payload.windowMessages === 'number' && payload.windowMessages >= 2 && payload.windowMessages <= 20) {
|
|
2308
|
+
this.config.windowMessages = Math.round(payload.windowMessages)
|
|
2309
|
+
}
|
|
2310
|
+
// 恢复每个来源的滑动窗口;老存档没有这一段,就等新消息进来再重建。
|
|
2311
|
+
this.restoreWindows(payload.windows)
|
|
2312
|
+
}
|
|
2313
|
+
} catch {
|
|
2314
|
+
// 首次运行或文件损坏:使用默认状态。
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
saveState() {
|
|
2319
|
+
const payload = {
|
|
2320
|
+
version: 1,
|
|
2321
|
+
autoReply: this.state.autoReply,
|
|
2322
|
+
autoReplyTouched: this.state.autoReplyTouched,
|
|
2323
|
+
autoReplyAt: Number(this.state.autoReplyAt) || 0,
|
|
2324
|
+
minConfidence: this.config.minConfidence,
|
|
2325
|
+
windowMessages: this.config.windowMessages,
|
|
2326
|
+
selfName: this.state.selfName,
|
|
2327
|
+
titles: Object.fromEntries([...this.titleCache.entries()].filter(([, value]) => value !== '')),
|
|
2328
|
+
messages: this.state.messages.slice(0, this.config.maxInbox),
|
|
2329
|
+
windows: this.windowSnapshot(),
|
|
2330
|
+
savedAt: Date.now(),
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
this.saveChain = this.saveChain
|
|
2334
|
+
.catch(() => {})
|
|
2335
|
+
.then(async () => {
|
|
2336
|
+
const dir = dirname(this.statePath)
|
|
2337
|
+
await mkdir(dir, { recursive: true })
|
|
2338
|
+
const tmp = `${this.statePath}.${process.pid}.tmp`
|
|
2339
|
+
await writeFile(tmp, JSON.stringify(payload), { encoding: 'utf8', mode: 0o600 })
|
|
2340
|
+
await rename(tmp, this.statePath)
|
|
2341
|
+
})
|
|
2342
|
+
.catch(async () => {
|
|
2343
|
+
try {
|
|
2344
|
+
await unlink(`${this.statePath}.${process.pid}.tmp`)
|
|
2345
|
+
} catch {
|
|
2346
|
+
// 忽略。
|
|
2347
|
+
}
|
|
2348
|
+
})
|
|
2349
|
+
|
|
2350
|
+
return this.saveChain
|
|
2351
|
+
}
|
|
2352
|
+
}
|