@michengai/dsh-im-connect 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +224 -0
- package/README.md +204 -19
- package/assets/branding/dsh-banner.png +0 -0
- package/assets/screenshots/dingtalk-chat.jpg +0 -0
- package/assets/screenshots/feishu-chat.jpg +0 -0
- package/assets/screenshots/qq-chat.jpg +0 -0
- package/assets/screenshots/settings-channels.png +0 -0
- package/assets/screenshots/telegram-chat.jpg +0 -0
- package/assets/screenshots/wecom-chat.jpg +0 -0
- package/assets/screenshots/wecom-qr.png +0 -0
- package/assets/screenshots/weixin-chat.jpg +0 -0
- package/assets/screenshots/workspace-channels.png +0 -0
- package/client.js +158 -82
- package/lib/channels/dingtalk-card.d.ts +2 -1
- package/lib/channels/dingtalk-card.d.ts.map +1 -1
- package/lib/channels/dingtalk-card.js +13 -5
- package/lib/channels/dingtalk-card.js.map +1 -1
- package/lib/channels/dingtalk.d.ts +19 -0
- package/lib/channels/dingtalk.d.ts.map +1 -1
- package/lib/channels/dingtalk.js +30 -16
- package/lib/channels/dingtalk.js.map +1 -1
- package/lib/channels/factory.d.ts.map +1 -1
- package/lib/channels/factory.js +3 -0
- package/lib/channels/factory.js.map +1 -1
- package/lib/channels/feishu.d.ts.map +1 -1
- package/lib/channels/feishu.js +5 -2
- package/lib/channels/feishu.js.map +1 -1
- package/lib/channels/meta.d.ts.map +1 -1
- package/lib/channels/meta.js +11 -0
- package/lib/channels/meta.js.map +1 -1
- package/lib/channels/qq.d.ts +9 -0
- package/lib/channels/qq.d.ts.map +1 -0
- package/lib/channels/qq.js +279 -0
- package/lib/channels/qq.js.map +1 -0
- package/lib/channels/qr/hub.d.ts +4 -1
- package/lib/channels/qr/hub.d.ts.map +1 -1
- package/lib/channels/qr/hub.js +27 -0
- package/lib/channels/qr/hub.js.map +1 -1
- package/lib/channels/qr/qq.d.ts +18 -0
- package/lib/channels/qr/qq.d.ts.map +1 -0
- package/lib/channels/qr/qq.js +86 -0
- package/lib/channels/qr/qq.js.map +1 -0
- package/lib/channels/qr/shared.d.ts +3 -0
- package/lib/channels/qr/shared.d.ts.map +1 -1
- package/lib/channels/qr/shared.js.map +1 -1
- package/lib/channels/telegram.d.ts.map +1 -1
- package/lib/channels/telegram.js +39 -8
- package/lib/channels/telegram.js.map +1 -1
- package/lib/channels/wecom.d.ts +1 -0
- package/lib/channels/wecom.d.ts.map +1 -1
- package/lib/channels/wecom.js +35 -15
- package/lib/channels/wecom.js.map +1 -1
- package/lib/channels/weixin.d.ts.map +1 -1
- package/lib/channels/weixin.js +9 -18
- package/lib/channels/weixin.js.map +1 -1
- package/lib/client.js +158 -82
- package/lib/engine/gateway.d.ts +3 -10
- package/lib/engine/gateway.d.ts.map +1 -1
- package/lib/engine/gateway.js +54 -65
- package/lib/engine/gateway.js.map +1 -1
- package/lib/engine/quiet-logger.d.ts +9 -0
- package/lib/engine/quiet-logger.d.ts.map +1 -0
- package/lib/engine/quiet-logger.js +26 -0
- package/lib/engine/quiet-logger.js.map +1 -0
- package/lib/engine/reply-stream.d.ts +25 -0
- package/lib/engine/reply-stream.d.ts.map +1 -0
- package/lib/engine/reply-stream.js +62 -0
- package/lib/engine/reply-stream.js.map +1 -0
- package/lib/engine/session-id.d.ts +1 -1
- package/lib/engine/session-id.d.ts.map +1 -1
- package/lib/engine/session-id.js +1 -1
- package/lib/engine/session-id.js.map +1 -1
- package/lib/engine/types.d.ts +0 -2
- package/lib/engine/types.d.ts.map +1 -1
- package/lib/index.d.ts +0 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +0 -2
- package/lib/index.js.map +1 -1
- package/lib/manager.d.ts +1 -12
- package/lib/manager.d.ts.map +1 -1
- package/lib/manager.js +165 -167
- package/lib/manager.js.map +1 -1
- package/package.json +15 -4
- package/src/channels/dingtalk-card.ts +13 -6
- package/src/channels/dingtalk.ts +43 -18
- package/src/channels/factory.ts +8 -2
- package/src/channels/feishu.ts +6 -2
- package/src/channels/meta.ts +13 -0
- package/src/channels/qq.ts +302 -0
- package/src/channels/qr/hub.ts +27 -3
- package/src/channels/qr/qq.ts +91 -0
- package/src/channels/qr/shared.ts +4 -0
- package/src/channels/telegram.ts +39 -9
- package/src/channels/wecom.ts +37 -16
- package/src/channels/weixin.ts +44 -52
- package/src/engine/gateway.ts +316 -325
- package/src/engine/quiet-logger.ts +23 -0
- package/src/engine/reply-stream.ts +67 -0
- package/src/engine/session-id.ts +3 -2
- package/src/engine/types.ts +1 -3
- package/src/index.ts +2 -5
- package/src/manager.ts +542 -569
- package/src/engine/access.ts +0 -17
package/src/engine/gateway.ts
CHANGED
|
@@ -1,330 +1,321 @@
|
|
|
1
|
-
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
-
import { ApprovalBroker } from './approval.js'
|
|
3
|
-
import { SessionMerger } from './merge.js'
|
|
4
|
-
import { SessionRouter } from './router.js'
|
|
5
|
-
import { SeenStore } from './seen-store.js'
|
|
6
|
-
import { SessionMapStore } from './session-store.js'
|
|
7
|
-
import { isImSessionId, type ChannelId, type ChatKind } from './session-id.js'
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import type { ChannelAdapter, EngineConfig, ImMessage
|
|
11
|
-
|
|
12
|
-
const HELP = [
|
|
13
|
-
'IM 助理已连接本机 DeepSeek Harness。',
|
|
14
|
-
'',
|
|
15
|
-
'直接发文字即可继续当前频道会话。',
|
|
16
|
-
'结尾 .. 表示还有后续,!! 表示立即提交。',
|
|
17
|
-
'/new 开启全新会话(只影响当前 IM 聊天,不影响网页任务)',
|
|
18
|
-
'/status 查看当前频道会话',
|
|
19
|
-
'/help 显示本帮助',
|
|
20
|
-
].join('\n')
|
|
21
|
-
|
|
22
|
-
export class ImEngine {
|
|
23
|
-
private readonly channels = new Map<string, ChannelAdapter>()
|
|
24
|
-
private readonly router: SessionRouter
|
|
25
|
-
private readonly broker = new ApprovalBroker()
|
|
26
|
-
private readonly merger: SessionMerger
|
|
27
|
-
private readonly
|
|
28
|
-
private readonly
|
|
29
|
-
private readonly
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
private readonly
|
|
36
|
-
private readonly
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
this.config.
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
this.
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
this.
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
if (
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
if (
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
}
|
|
148
|
-
if (
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
})
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
if (
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
await
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
if (
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
this.
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
private async deliver(channel: ChannelAdapter, chatId: string, text: string): Promise<void> {
|
|
317
|
-
for (const chunk of splitText(text, channel.maxMessageLength)) {
|
|
318
|
-
try {
|
|
319
|
-
await channel.send(chatId, chunk)
|
|
320
|
-
this.log(`[${channel.id}] 已投递 ${chatId},长度 ${chunk.length}`)
|
|
321
|
-
} catch (error) {
|
|
322
|
-
this.log(`[${channel.id}] 回复失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
}
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
import { ApprovalBroker } from './approval.js'
|
|
3
|
+
import { SessionMerger } from './merge.js'
|
|
4
|
+
import { SessionRouter } from './router.js'
|
|
5
|
+
import { SeenStore } from './seen-store.js'
|
|
6
|
+
import { SessionMapStore } from './session-store.js'
|
|
7
|
+
import { isImSessionId, type ChannelId, type ChatKind } from './session-id.js'
|
|
8
|
+
import { splitText } from './split.js'
|
|
9
|
+
import { ReplyStreamHub, isAssistantTextDelta } from './reply-stream.js'
|
|
10
|
+
import type { ChannelAdapter, EngineConfig, ImMessage } from './types.js'
|
|
11
|
+
|
|
12
|
+
const HELP = [
|
|
13
|
+
'IM 助理已连接本机 DeepSeek Harness。',
|
|
14
|
+
'',
|
|
15
|
+
'直接发文字即可继续当前频道会话。',
|
|
16
|
+
'结尾 .. 表示还有后续,!! 表示立即提交。',
|
|
17
|
+
'/new 开启全新会话(只影响当前 IM 聊天,不影响网页任务)',
|
|
18
|
+
'/status 查看当前频道会话',
|
|
19
|
+
'/help 显示本帮助',
|
|
20
|
+
].join('\n')
|
|
21
|
+
|
|
22
|
+
export class ImEngine {
|
|
23
|
+
private readonly channels = new Map<string, ChannelAdapter>()
|
|
24
|
+
private readonly router: SessionRouter
|
|
25
|
+
private readonly broker = new ApprovalBroker()
|
|
26
|
+
private readonly merger: SessionMerger
|
|
27
|
+
private readonly queues = new Map<string, Promise<void>>()
|
|
28
|
+
private readonly streams = new ReplyStreamHub()
|
|
29
|
+
private readonly disposeEvents: Array<() => void> = []
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
private readonly ctx: Context,
|
|
33
|
+
private readonly store: SessionMapStore,
|
|
34
|
+
private readonly seen: SeenStore,
|
|
35
|
+
private readonly config: EngineConfig,
|
|
36
|
+
private readonly log: (line: string) => void,
|
|
37
|
+
) {
|
|
38
|
+
this.router = new SessionRouter(ctx, store, config, log)
|
|
39
|
+
this.merger = new SessionMerger((config.mergeTimeoutSecs || 5) * 1000, (key, text) => {
|
|
40
|
+
const sep = key.indexOf(':')
|
|
41
|
+
const channelId = key.slice(0, sep)
|
|
42
|
+
const rest = key.slice(sep + 1)
|
|
43
|
+
const channel = this.channels.get(channelId)
|
|
44
|
+
if (!channel) return
|
|
45
|
+
const merged: ImMessage = { chatId: rest.split(':').slice(1).join(':') || rest, text, kind: rest.startsWith('group:') ? 'group' : 'dm' }
|
|
46
|
+
// 合并窗口回调不在任何请求链路里,必须自兜底,否则 rejection 无人接
|
|
47
|
+
void this.inject(channel, merged).catch((error) => {
|
|
48
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
49
|
+
this.log(`[${channelId}] 合并投递失败: ${detail}`)
|
|
50
|
+
channel.send(merged.chatId, `消息处理失败:${detail}`).catch(() => undefined)
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
const on = (this.ctx as unknown as { on: (name: string, fn: (...args: unknown[]) => unknown, opts?: unknown) => () => void }).on
|
|
54
|
+
if (typeof on === 'function') {
|
|
55
|
+
this.disposeEvents.push(on('session/event', (...args: unknown[]) => {
|
|
56
|
+
void this.onSessionEvent(args[0] as { id?: string }, args[1] as { type?: string; data?: { message?: { content?: Array<{ type?: string; text?: string }> }; chunk?: { type?: string; text?: string } } })
|
|
57
|
+
}, { global: true }))
|
|
58
|
+
this.disposeEvents.push(on('approval/request', (...args: unknown[]) => {
|
|
59
|
+
const req = args[0] as { session?: { id?: string } }
|
|
60
|
+
const next = args[1] as () => Promise<unknown>
|
|
61
|
+
return this.onApproval(req, next)
|
|
62
|
+
}, { global: true }))
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
renameSession(sessionId: string, title: string): boolean {
|
|
67
|
+
return this.router.rename(sessionId, title)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async removeSession(sessionId: string): Promise<boolean> {
|
|
71
|
+
return this.router.remove(sessionId)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async ensureSession(sessionId: string): Promise<boolean> {
|
|
75
|
+
return this.router.ensure(sessionId)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
setModel(provider: string, model: string, reasoningEffort?: string): void {
|
|
79
|
+
this.config.provider = provider
|
|
80
|
+
this.config.model = model
|
|
81
|
+
this.config.reasoningEffort = reasoningEffort
|
|
82
|
+
void this.router.disposeAll()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
setCwd(cwd: string): void {
|
|
86
|
+
this.config.cwd = cwd
|
|
87
|
+
void this.router.disposeAll()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
setPermission(permission: 'read-only' | 'workspace-write' | 'full-access'): void {
|
|
91
|
+
this.config.permissionPreset = permission
|
|
92
|
+
void this.router.disposeAll()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
attachMappedSessions(): Promise<void> {
|
|
96
|
+
return this.router.attachMappedSessions()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
register(channel: ChannelAdapter): void {
|
|
100
|
+
this.channels.set(channel.id, channel)
|
|
101
|
+
channel.setMessageHandler((msg) => this.enqueue(channel.id, msg))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
unregister(channelId: string): void {
|
|
105
|
+
this.channels.delete(channelId)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
dispose(): void {
|
|
109
|
+
for (const off of this.disposeEvents) off()
|
|
110
|
+
this.broker.dispose()
|
|
111
|
+
this.merger.dispose()
|
|
112
|
+
void this.router.disposeAll()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private enqueue(channelId: string, msg: ImMessage): void {
|
|
116
|
+
const key = `${channelId}:${msg.chatId}`
|
|
117
|
+
const prev = this.queues.get(key) ?? Promise.resolve()
|
|
118
|
+
const current = prev.catch(() => undefined).then(() => this.handleInbound(channelId, msg))
|
|
119
|
+
this.queues.set(key, current)
|
|
120
|
+
void current.finally(() => {
|
|
121
|
+
if (this.queues.get(key) === current) this.queues.delete(key)
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private async handleInbound(channelId: string, msg: ImMessage): Promise<void> {
|
|
126
|
+
const channel = this.channels.get(channelId)
|
|
127
|
+
if (!channel) return
|
|
128
|
+
try {
|
|
129
|
+
if (msg.messageId && this.seen.has(`${channelId}:${msg.messageId}`)) return
|
|
130
|
+
if (msg.messageId) this.seen.add(`${channelId}:${msg.messageId}`)
|
|
131
|
+
if (msg.kind === 'group' && msg.addressed === false) return
|
|
132
|
+
const text = msg.text.trim()
|
|
133
|
+
if (text.startsWith('/')) {
|
|
134
|
+
const reply = await this.handleCommand(channel, msg)
|
|
135
|
+
if (reply) await this.deliver(channel, msg.chatId, reply)
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
if (['批准', '同意', 'yes', 'y', 'allow'].includes(text.toLowerCase())) {
|
|
139
|
+
if (await this.answerApproval(channelId, msg, true)) return
|
|
140
|
+
}
|
|
141
|
+
if (['拒绝', 'no', 'n', 'reject', 'deny'].includes(text.toLowerCase())) {
|
|
142
|
+
if (await this.answerApproval(channelId, msg, false)) return
|
|
143
|
+
}
|
|
144
|
+
if (msg.media && msg.media.length > 0) {
|
|
145
|
+
await this.inject(channel, msg)
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
if (!text) return
|
|
149
|
+
if (channel.skipMerge) {
|
|
150
|
+
await this.inject(channel, { ...msg, text })
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
const mergeKey = `${channelId}:${msg.kind === 'group' ? 'group' : 'dm'}:${msg.chatId}`
|
|
154
|
+
const merged = this.merger.ingest(mergeKey, text)
|
|
155
|
+
if (merged.kind === 'flushed' && merged.text) {
|
|
156
|
+
await this.inject(channel, { ...msg, text: merged.text })
|
|
157
|
+
}
|
|
158
|
+
} catch (error) {
|
|
159
|
+
this.log(`[${channelId}] 处理失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
160
|
+
await channel.send(msg.chatId, `消息处理失败:${error instanceof Error ? error.message : String(error)}`).catch(() => undefined)
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private async handleCommand(channel: ChannelAdapter, msg: ImMessage): Promise<string | undefined> {
|
|
165
|
+
const [raw] = msg.text.trim().split(/\s+/)
|
|
166
|
+
const cmd = raw?.toLowerCase()
|
|
167
|
+
const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
|
|
168
|
+
if (cmd === '/help') return HELP
|
|
169
|
+
if (cmd === '/status') {
|
|
170
|
+
const entry = this.router.get(channel.id as ChannelId, kind, msg.chatId)
|
|
171
|
+
return [
|
|
172
|
+
`渠道:${channel.label}(${channel.status()})`,
|
|
173
|
+
entry ? `频道会话:${entry.sessionId}` : '频道会话:(尚未创建)',
|
|
174
|
+
'此会话独立于网页「任务」列表。',
|
|
175
|
+
].join('\n')
|
|
176
|
+
}
|
|
177
|
+
if (cmd === '/new' || cmd === '/clear') {
|
|
178
|
+
const entry = await this.router.rotate(channel.id as ChannelId, kind, msg.chatId, msg.username ?? msg.chatId)
|
|
179
|
+
return `已开启新的频道会话:${entry.sessionId}`
|
|
180
|
+
}
|
|
181
|
+
return `未知命令 ${cmd}。发送 /help 查看帮助。`
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private async inject(channel: ChannelAdapter, msg: ImMessage): Promise<void> {
|
|
185
|
+
const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
|
|
186
|
+
const title = (msg.username || msg.text || msg.chatId).slice(0, 40)
|
|
187
|
+
const binding = await this.router.getOrCreate(channel.id as ChannelId, kind, msg.chatId, title)
|
|
188
|
+
const content: Array<Record<string, unknown>> = []
|
|
189
|
+
if (msg.text.trim()) content.push({ type: 'text', text: msg.text.trim() })
|
|
190
|
+
for (const media of msg.media ?? []) {
|
|
191
|
+
if (media.kind === 'voice-text' && media.text) content.push({ type: 'text', text: `[语音] ${media.text}` })
|
|
192
|
+
else if (media.path) content.push({ type: 'text', text: `[附件 ${media.name ?? media.kind}] ${media.path}` })
|
|
193
|
+
}
|
|
194
|
+
if (content.length === 0) return
|
|
195
|
+
this.streams.reset(`${channel.id}:${msg.chatId}`)
|
|
196
|
+
await channel.sendAction?.(msg.chatId, 'typing').catch(() => undefined)
|
|
197
|
+
this.router.followup(binding, {
|
|
198
|
+
id: crypto.randomUUID(),
|
|
199
|
+
role: 'user',
|
|
200
|
+
content,
|
|
201
|
+
source: { kind: 'user' },
|
|
202
|
+
})
|
|
203
|
+
this.log(`[${channel.id}] 已注入 ${binding.sessionId}`)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private async answerApproval(channelId: string, msg: ImMessage, allow: boolean): Promise<boolean> {
|
|
207
|
+
const binding = this.router.get(channelId as ChannelId, msg.kind === 'group' ? 'group' : 'dm', msg.chatId)
|
|
208
|
+
if (!binding) return false
|
|
209
|
+
const ok = this.broker.answer(binding.sessionId, allow)
|
|
210
|
+
if (ok) await this.channels.get(channelId)?.send(msg.chatId, allow ? '已批准。' : '已拒绝。')
|
|
211
|
+
return ok
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private async onApproval(req: { session?: { id?: string } }, next: () => Promise<unknown>): Promise<unknown> {
|
|
215
|
+
const sessionId = req.session?.id ? String(req.session.id) : ''
|
|
216
|
+
if (!sessionId || !isImSessionId(sessionId)) return next()
|
|
217
|
+
const binding = this.router.bindingForSession(sessionId)
|
|
218
|
+
const channel = binding ? this.channels.get(binding.channelId) : undefined
|
|
219
|
+
if (!binding || !channel) return next()
|
|
220
|
+
await channel.send(binding.chatId, '需要批准才能继续。回复「批准」或「拒绝」。').catch(() => undefined)
|
|
221
|
+
const verdict = await this.broker.wait(sessionId, 120_000)
|
|
222
|
+
if (verdict === 'allow') return { behavior: 'allow' }
|
|
223
|
+
if (verdict === 'reject') return { behavior: 'reject' }
|
|
224
|
+
return next()
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private async onSessionEvent(
|
|
228
|
+
session: { id?: string },
|
|
229
|
+
event: { type?: string; data?: { message?: { content?: Array<{ type?: string; text?: string }> }; chunk?: { type?: string; text?: string } } },
|
|
230
|
+
): Promise<void> {
|
|
231
|
+
const sessionId = session.id ? String(session.id) : ''
|
|
232
|
+
if (!isImSessionId(sessionId)) return
|
|
233
|
+
const binding = this.router.bindingForSession(sessionId)
|
|
234
|
+
const channel = binding ? this.channels.get(binding.channelId) : undefined
|
|
235
|
+
if (!binding || !channel) return
|
|
236
|
+
const streamKey = `${binding.channelId}:${binding.chatId}`
|
|
237
|
+
const chunk = event.data?.chunk
|
|
238
|
+
if (event.type === 'assistant/chunk' && channel.beginReply && isAssistantTextDelta(chunk)) {
|
|
239
|
+
// 事件回调不在请求链路里,流式更新失败必须自兜底,避免 unhandled rejection
|
|
240
|
+
void this.streams.onTextDelta(streamKey, chunk.text, () => channel.beginReply!(binding.chatId).catch(() => undefined))
|
|
241
|
+
.catch((error) => {
|
|
242
|
+
this.log(`[${channel.id}] 流式更新失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
243
|
+
})
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
if (event.type === 'turn/end') {
|
|
247
|
+
const reason = (event.data as { reason?: { kind?: string; error?: { message?: string } } } | undefined)?.reason
|
|
248
|
+
this.log(`[${channel.id}] 回合结束 ${sessionId}: ${reason?.kind ?? 'ok'}`)
|
|
249
|
+
if (reason?.kind === 'error') {
|
|
250
|
+
const detail = reason.error?.message || '模型调用失败'
|
|
251
|
+
this.log(`[${channel.id}] 回合失败 ${sessionId}: ${detail}`)
|
|
252
|
+
const failed = `助手没有生成回复:${detail}`
|
|
253
|
+
const taken = await this.streams.take(streamKey)
|
|
254
|
+
let failureDelivered: boolean
|
|
255
|
+
if (taken.stream) {
|
|
256
|
+
failureDelivered = await taken.stream.finish(failed).then(() => true).catch(() => this.deliver(channel, binding.chatId, failed))
|
|
257
|
+
} else {
|
|
258
|
+
failureDelivered = await this.deliver(channel, binding.chatId, failed)
|
|
259
|
+
}
|
|
260
|
+
// 仅在确已送达时标记,失败后同回合残留的 assistant/message 还有机会补发
|
|
261
|
+
if (failureDelivered) this.streams.markDelivered(streamKey)
|
|
262
|
+
}
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
if (event.type === 'assistant/message') {
|
|
266
|
+
const text = (event.data?.message?.content ?? [])
|
|
267
|
+
.filter((block) => block.type === 'text' && block.text)
|
|
268
|
+
.map((block) => block.text ?? '')
|
|
269
|
+
.join('\n')
|
|
270
|
+
.trim()
|
|
271
|
+
const taken = await this.streams.take(streamKey)
|
|
272
|
+
if (taken.stream) {
|
|
273
|
+
const finalText = text || taken.text
|
|
274
|
+
if (finalText) {
|
|
275
|
+
let delivered = true
|
|
276
|
+
try {
|
|
277
|
+
await taken.stream.finish(finalText)
|
|
278
|
+
} catch (error) {
|
|
279
|
+
// 收口失败时大概率没送出去,宁可小概率重复也不能让用户收不到回复
|
|
280
|
+
this.log(`[${channel.id}] 流式收口失败,改走普通投递: ${error instanceof Error ? error.message : String(error)}`)
|
|
281
|
+
delivered = await this.deliver(channel, binding.chatId, finalText)
|
|
282
|
+
}
|
|
283
|
+
if (delivered) this.streams.markDelivered(streamKey)
|
|
284
|
+
}
|
|
285
|
+
return
|
|
286
|
+
}
|
|
287
|
+
if (this.streams.consumeDelivered(streamKey)) {
|
|
288
|
+
this.log(`[${channel.id}] 忽略重复助手消息 ${sessionId}`)
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
if (text) {
|
|
292
|
+
this.log(`[${channel.id}] 准备回复 ${sessionId},长度 ${text.length}`)
|
|
293
|
+
await this.deliver(channel, binding.chatId, text)
|
|
294
|
+
} else {
|
|
295
|
+
this.log(`[${channel.id}] 助手消息为空 ${sessionId}`)
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** 逐片发送;返回是否至少送达过一片,供调用方决定是否标记已投递。 */
|
|
301
|
+
private async deliver(channel: ChannelAdapter, chatId: string, text: string): Promise<boolean> {
|
|
302
|
+
let deliveredAny = false
|
|
303
|
+
for (const chunk of splitText(text, channel.maxMessageLength)) {
|
|
304
|
+
try {
|
|
305
|
+
await channel.send(chatId, chunk)
|
|
306
|
+
deliveredAny = true
|
|
307
|
+
this.log(`[${channel.id}] 已投递 ${chatId},长度 ${chunk.length}`)
|
|
308
|
+
} catch (error) {
|
|
309
|
+
this.log(`[${channel.id}] 回复失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return deliveredAny
|
|
313
|
+
}
|
|
326
314
|
}
|
|
327
315
|
|
|
328
316
|
|
|
329
317
|
|
|
330
318
|
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
|