@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.
Files changed (103) hide show
  1. package/README.en.md +224 -0
  2. package/README.md +204 -19
  3. package/assets/branding/dsh-banner.png +0 -0
  4. package/assets/screenshots/dingtalk-chat.jpg +0 -0
  5. package/assets/screenshots/feishu-chat.jpg +0 -0
  6. package/assets/screenshots/qq-chat.jpg +0 -0
  7. package/assets/screenshots/settings-channels.png +0 -0
  8. package/assets/screenshots/telegram-chat.jpg +0 -0
  9. package/assets/screenshots/wecom-chat.jpg +0 -0
  10. package/assets/screenshots/wecom-qr.png +0 -0
  11. package/assets/screenshots/weixin-chat.jpg +0 -0
  12. package/assets/screenshots/workspace-channels.png +0 -0
  13. package/client.js +158 -82
  14. package/lib/channels/dingtalk-card.d.ts +2 -1
  15. package/lib/channels/dingtalk-card.d.ts.map +1 -1
  16. package/lib/channels/dingtalk-card.js +13 -5
  17. package/lib/channels/dingtalk-card.js.map +1 -1
  18. package/lib/channels/dingtalk.d.ts +19 -0
  19. package/lib/channels/dingtalk.d.ts.map +1 -1
  20. package/lib/channels/dingtalk.js +30 -16
  21. package/lib/channels/dingtalk.js.map +1 -1
  22. package/lib/channels/factory.d.ts.map +1 -1
  23. package/lib/channels/factory.js +3 -0
  24. package/lib/channels/factory.js.map +1 -1
  25. package/lib/channels/feishu.d.ts.map +1 -1
  26. package/lib/channels/feishu.js +5 -2
  27. package/lib/channels/feishu.js.map +1 -1
  28. package/lib/channels/meta.d.ts.map +1 -1
  29. package/lib/channels/meta.js +11 -0
  30. package/lib/channels/meta.js.map +1 -1
  31. package/lib/channels/qq.d.ts +9 -0
  32. package/lib/channels/qq.d.ts.map +1 -0
  33. package/lib/channels/qq.js +279 -0
  34. package/lib/channels/qq.js.map +1 -0
  35. package/lib/channels/qr/hub.d.ts +4 -1
  36. package/lib/channels/qr/hub.d.ts.map +1 -1
  37. package/lib/channels/qr/hub.js +27 -0
  38. package/lib/channels/qr/hub.js.map +1 -1
  39. package/lib/channels/qr/qq.d.ts +18 -0
  40. package/lib/channels/qr/qq.d.ts.map +1 -0
  41. package/lib/channels/qr/qq.js +86 -0
  42. package/lib/channels/qr/qq.js.map +1 -0
  43. package/lib/channels/qr/shared.d.ts +3 -0
  44. package/lib/channels/qr/shared.d.ts.map +1 -1
  45. package/lib/channels/qr/shared.js.map +1 -1
  46. package/lib/channels/telegram.d.ts.map +1 -1
  47. package/lib/channels/telegram.js +39 -8
  48. package/lib/channels/telegram.js.map +1 -1
  49. package/lib/channels/wecom.d.ts +1 -0
  50. package/lib/channels/wecom.d.ts.map +1 -1
  51. package/lib/channels/wecom.js +35 -15
  52. package/lib/channels/wecom.js.map +1 -1
  53. package/lib/channels/weixin.d.ts.map +1 -1
  54. package/lib/channels/weixin.js +9 -18
  55. package/lib/channels/weixin.js.map +1 -1
  56. package/lib/client.js +158 -82
  57. package/lib/engine/gateway.d.ts +3 -10
  58. package/lib/engine/gateway.d.ts.map +1 -1
  59. package/lib/engine/gateway.js +54 -65
  60. package/lib/engine/gateway.js.map +1 -1
  61. package/lib/engine/quiet-logger.d.ts +9 -0
  62. package/lib/engine/quiet-logger.d.ts.map +1 -0
  63. package/lib/engine/quiet-logger.js +26 -0
  64. package/lib/engine/quiet-logger.js.map +1 -0
  65. package/lib/engine/reply-stream.d.ts +25 -0
  66. package/lib/engine/reply-stream.d.ts.map +1 -0
  67. package/lib/engine/reply-stream.js +62 -0
  68. package/lib/engine/reply-stream.js.map +1 -0
  69. package/lib/engine/session-id.d.ts +1 -1
  70. package/lib/engine/session-id.d.ts.map +1 -1
  71. package/lib/engine/session-id.js +1 -1
  72. package/lib/engine/session-id.js.map +1 -1
  73. package/lib/engine/types.d.ts +0 -2
  74. package/lib/engine/types.d.ts.map +1 -1
  75. package/lib/index.d.ts +0 -1
  76. package/lib/index.d.ts.map +1 -1
  77. package/lib/index.js +0 -2
  78. package/lib/index.js.map +1 -1
  79. package/lib/manager.d.ts +1 -12
  80. package/lib/manager.d.ts.map +1 -1
  81. package/lib/manager.js +165 -167
  82. package/lib/manager.js.map +1 -1
  83. package/package.json +15 -4
  84. package/src/channels/dingtalk-card.ts +13 -6
  85. package/src/channels/dingtalk.ts +43 -18
  86. package/src/channels/factory.ts +8 -2
  87. package/src/channels/feishu.ts +6 -2
  88. package/src/channels/meta.ts +13 -0
  89. package/src/channels/qq.ts +302 -0
  90. package/src/channels/qr/hub.ts +27 -3
  91. package/src/channels/qr/qq.ts +91 -0
  92. package/src/channels/qr/shared.ts +4 -0
  93. package/src/channels/telegram.ts +39 -9
  94. package/src/channels/wecom.ts +37 -16
  95. package/src/channels/weixin.ts +44 -52
  96. package/src/engine/gateway.ts +316 -325
  97. package/src/engine/quiet-logger.ts +23 -0
  98. package/src/engine/reply-stream.ts +67 -0
  99. package/src/engine/session-id.ts +3 -2
  100. package/src/engine/types.ts +1 -3
  101. package/src/index.ts +2 -5
  102. package/src/manager.ts +542 -569
  103. package/src/engine/access.ts +0 -17
@@ -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 { decideAccess } from './access.js'
9
- import { splitText } from './split.js'
10
- import type { ChannelAdapter, EngineConfig, ImMessage, ReplyStream } 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 extraAllow = new Map<string, Set<string>>()
28
- private readonly extraGroups = new Map<string, Set<string>>()
29
- private readonly openChannels = new Set<string>()
30
- private readonly queues = new Map<string, Promise<void>>()
31
- private readonly streams = new Map<string, ReplyStream>()
32
- private readonly disposeEvents: Array<() => void> = []
33
-
34
- constructor(
35
- private readonly ctx: Context,
36
- private readonly store: SessionMapStore,
37
- private readonly seen: SeenStore,
38
- private readonly config: EngineConfig,
39
- private readonly log: (line: string) => void,
40
- private readonly onUnauthorized?: (channelId: string, msg: ImMessage) => string,
41
- ) {
42
- this.router = new SessionRouter(ctx, store, config, log)
43
- this.merger = new SessionMerger((config.mergeTimeoutSecs || 5) * 1000, (key, text) => {
44
- const sep = key.indexOf(':')
45
- const channelId = key.slice(0, sep)
46
- const rest = key.slice(sep + 1)
47
- const channel = this.channels.get(channelId)
48
- if (!channel) return
49
- void this.inject(channel, { chatId: rest.split(':').slice(1).join(':') || rest, text, kind: rest.startsWith('group:') ? 'group' : 'dm' })
50
- })
51
- const on = (this.ctx as unknown as { on: (name: string, fn: (...args: unknown[]) => unknown, opts?: unknown) => () => void }).on
52
- if (typeof on === 'function') {
53
- this.disposeEvents.push(on('session/event', (...args: unknown[]) => {
54
- 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 } } })
55
- }, { global: true }))
56
- this.disposeEvents.push(on('approval/request', (...args: unknown[]) => {
57
- const req = args[0] as { session?: { id?: string } }
58
- const next = args[1] as () => Promise<unknown>
59
- return this.onApproval(req, next)
60
- }, { global: true }))
61
- }
62
- }
63
-
64
- renameSession(sessionId: string, title: string): boolean {
65
- return this.router.rename(sessionId, title)
66
- }
67
-
68
- async removeSession(sessionId: string): Promise<boolean> {
69
- return this.router.remove(sessionId)
70
- }
71
-
72
- async ensureSession(sessionId: string): Promise<boolean> {
73
- return this.router.ensure(sessionId)
74
- }
75
-
76
- setModel(provider: string, model: string, reasoningEffort?: string): void {
77
- this.config.provider = provider
78
- this.config.model = model
79
- this.config.reasoningEffort = reasoningEffort
80
- void this.router.disposeAll()
81
- }
82
-
83
- setCwd(cwd: string): void {
84
- this.config.cwd = cwd
85
- void this.router.disposeAll()
86
- }
87
-
88
- setPermission(permission: 'read-only' | 'workspace-write' | 'full-access'): void {
89
- this.config.permissionPreset = permission
90
- void this.router.disposeAll()
91
- }
92
-
93
- attachMappedSessions(): Promise<void> {
94
- return this.router.attachMappedSessions()
95
- }
96
-
97
- register(channel: ChannelAdapter): void {
98
- this.channels.set(channel.id, channel)
99
- channel.setMessageHandler((msg) => this.enqueue(channel.id, msg))
100
- }
101
-
102
- unregister(channelId: string): void {
103
- this.channels.delete(channelId)
104
- }
105
-
106
- addAllowed(channelId: string, userId: string): void {
107
- let set = this.extraAllow.get(channelId)
108
- if (!set) {
109
- set = new Set()
110
- this.extraAllow.set(channelId, set)
111
- }
112
- set.add(userId)
113
- }
114
-
115
- dispose(): void {
116
- for (const off of this.disposeEvents) off()
117
- this.broker.dispose()
118
- this.merger.dispose()
119
- void this.router.disposeAll()
120
- }
121
-
122
- private enqueue(channelId: string, msg: ImMessage): void {
123
- const key = `${channelId}:${msg.chatId}`
124
- const prev = this.queues.get(key) ?? Promise.resolve()
125
- const current = prev.catch(() => undefined).then(() => this.handleInbound(channelId, msg))
126
- this.queues.set(key, current)
127
- void current.finally(() => {
128
- if (this.queues.get(key) === current) this.queues.delete(key)
129
- })
130
- }
131
-
132
- private async handleInbound(channelId: string, msg: ImMessage): Promise<void> {
133
- const channel = this.channels.get(channelId)
134
- if (!channel) return
135
- try {
136
- if (msg.messageId && this.seen.has(`${channelId}:${msg.messageId}`)) return
137
- if (msg.messageId) this.seen.add(`${channelId}:${msg.messageId}`)
138
- if (msg.kind === 'group' && msg.addressed === false) return
139
- const text = msg.text.trim()
140
- if (text.startsWith('/')) {
141
- const reply = await this.handleCommand(channel, msg)
142
- if (reply) await this.deliver(channel, msg.chatId, reply)
143
- return
144
- }
145
- if (['批准', '同意', 'yes', 'y', 'allow'].includes(text.toLowerCase())) {
146
- if (await this.answerApproval(channelId, msg, true)) return
147
- }
148
- if (['拒绝', 'no', 'n', 'reject', 'deny'].includes(text.toLowerCase())) {
149
- if (await this.answerApproval(channelId, msg, false)) return
150
- }
151
- const local = channel.authorizes?.(msg.userId ?? '')
152
- const decision = decideAccess({
153
- allowAll: this.config.allowAllUsers,
154
- channelOpen: this.openChannels.has(channelId),
155
- userAllowed: local === true || (local !== false && this.userAllowed(channelId, msg.userId)),
156
- groupAllowed: msg.kind === 'group' && this.groupAllowed(channelId, msg.chatId),
157
- kind: msg.kind === 'group' ? 'group' : 'dm',
158
- addressed: msg.addressed,
159
- })
160
- if (decision === 'ignore') return
161
- if (decision === 'deny-group-silent') {
162
- this.onUnauthorized?.(channelId, msg)
163
- return
164
- }
165
- if (decision === 'deny-dm' || local === false) {
166
- const hint = this.onUnauthorized?.(channelId, msg) ?? '未授权:请管理员在设置 → IM助理 中批准你的访问。'
167
- await channel.send(msg.chatId, hint).catch(() => undefined)
168
- return
169
- }
170
- if (msg.media && msg.media.length > 0) {
171
- await this.inject(channel, msg)
172
- return
173
- }
174
- if (!text) return
175
- if (channel.skipMerge) {
176
- await this.inject(channel, { ...msg, text })
177
- return
178
- }
179
- const mergeKey = `${channelId}:${msg.kind === 'group' ? 'group' : 'dm'}:${msg.chatId}`
180
- const merged = this.merger.ingest(mergeKey, text)
181
- if (merged.kind === 'flushed' && merged.text) {
182
- await this.inject(channel, { ...msg, text: merged.text })
183
- }
184
- } catch (error) {
185
- this.log(`[${channelId}] 处理失败: ${error instanceof Error ? error.message : String(error)}`)
186
- await channel.send(msg.chatId, `消息处理失败:${error instanceof Error ? error.message : String(error)}`).catch(() => undefined)
187
- }
188
- }
189
-
190
- private async handleCommand(channel: ChannelAdapter, msg: ImMessage): Promise<string | undefined> {
191
- const [raw] = msg.text.trim().split(/\s+/)
192
- const cmd = raw?.toLowerCase()
193
- const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
194
- if (cmd === '/help') return HELP
195
- if (cmd === '/status') {
196
- const entry = this.router.get(channel.id as ChannelId, kind, msg.chatId)
197
- return [
198
- `渠道:${channel.label}(${channel.status()})`,
199
- entry ? `频道会话:${entry.sessionId}` : '频道会话:(尚未创建)',
200
- '此会话独立于网页「任务」列表。',
201
- ].join('\n')
202
- }
203
- if (cmd === '/new' || cmd === '/clear') {
204
- const entry = await this.router.rotate(channel.id as ChannelId, kind, msg.chatId, msg.username ?? msg.chatId)
205
- return `已开启新的频道会话:${entry.sessionId}`
206
- }
207
- return `未知命令 ${cmd}。发送 /help 查看帮助。`
208
- }
209
-
210
- private async inject(channel: ChannelAdapter, msg: ImMessage): Promise<void> {
211
- const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
212
- const title = (msg.username || msg.text || msg.chatId).slice(0, 40)
213
- const binding = await this.router.getOrCreate(channel.id as ChannelId, kind, msg.chatId, title)
214
- const content: Array<Record<string, unknown>> = []
215
- if (msg.text.trim()) content.push({ type: 'text', text: msg.text.trim() })
216
- for (const media of msg.media ?? []) {
217
- if (media.kind === 'voice-text' && media.text) content.push({ type: 'text', text: `[语音] ${media.text}` })
218
- else if (media.path) content.push({ type: 'text', text: `[附件 ${media.name ?? media.kind}] ${media.path}` })
219
- }
220
- if (content.length === 0) return
221
- await channel.sendAction?.(msg.chatId, 'typing').catch(() => undefined)
222
- this.router.followup(binding, {
223
- id: crypto.randomUUID(),
224
- role: 'user',
225
- content,
226
- source: { kind: 'user' },
227
- })
228
- this.log(`[${channel.id}] 已注入 ${binding.sessionId}`)
229
- }
230
-
231
- setAccessMode(channelId: string, mode: 'pair' | 'open'): void {
232
- if (mode === 'open') this.openChannels.add(channelId)
233
- else this.openChannels.delete(channelId)
234
- }
235
-
236
- private userAllowed(channelId: string, userId?: string): boolean {
237
- if (!userId) return false
238
- return this.extraAllow.get(channelId)?.has(userId) === true
239
- }
240
-
241
- private groupAllowed(channelId: string, chatId: string): boolean {
242
- return this.extraGroups.get(channelId)?.has(chatId) === true
243
- }
244
-
245
- private async answerApproval(channelId: string, msg: ImMessage, allow: boolean): Promise<boolean> {
246
- const binding = this.router.get(channelId as ChannelId, msg.kind === 'group' ? 'group' : 'dm', msg.chatId)
247
- if (!binding) return false
248
- const ok = this.broker.answer(binding.sessionId, allow)
249
- if (ok) await this.channels.get(channelId)?.send(msg.chatId, allow ? '已批准。' : '已拒绝。')
250
- return ok
251
- }
252
-
253
- private async onApproval(req: { session?: { id?: string } }, next: () => Promise<unknown>): Promise<unknown> {
254
- const sessionId = req.session?.id ? String(req.session.id) : ''
255
- if (!sessionId || !isImSessionId(sessionId)) return next()
256
- const binding = this.router.bindingForSession(sessionId)
257
- const channel = binding ? this.channels.get(binding.channelId) : undefined
258
- if (!binding || !channel) return next()
259
- await channel.send(binding.chatId, '需要批准才能继续。回复「批准」或「拒绝」。').catch(() => undefined)
260
- const verdict = await this.broker.wait(sessionId, 120_000)
261
- if (verdict === 'allow') return { behavior: 'allow' }
262
- if (verdict === 'reject') return { behavior: 'reject' }
263
- return next()
264
- }
265
-
266
- private async onSessionEvent(
267
- session: { id?: string },
268
- event: { type?: string; data?: { message?: { content?: Array<{ type?: string; text?: string }> }; chunk?: { type?: string; text?: string } } },
269
- ): Promise<void> {
270
- const sessionId = session.id ? String(session.id) : ''
271
- if (!isImSessionId(sessionId)) return
272
- const binding = this.router.bindingForSession(sessionId)
273
- const channel = binding ? this.channels.get(binding.channelId) : undefined
274
- if (!binding || !channel) return
275
- const streamKey = `${binding.channelId}:${binding.chatId}`
276
- if (event.type === 'assistant/chunk' && event.data?.chunk?.text && channel.beginReply) {
277
- let stream = this.streams.get(streamKey)
278
- if (!stream) {
279
- stream = await channel.beginReply(binding.chatId).catch(() => undefined)
280
- if (stream) this.streams.set(streamKey, stream)
281
- }
282
- if (stream) await stream.update(event.data.chunk.text).catch(() => undefined)
283
- return
284
- }
285
- if (event.type === 'turn/end') {
286
- const reason = (event.data as { reason?: { kind?: string; error?: { message?: string } } } | undefined)?.reason
287
- this.log(`[${channel.id}] 回合结束 ${sessionId}: ${reason?.kind ?? 'ok'}`)
288
- if (reason?.kind === 'error') {
289
- const detail = reason.error?.message || '模型调用失败'
290
- this.log(`[${channel.id}] 回合失败 ${sessionId}: ${detail}`)
291
- await this.deliver(channel, binding.chatId, `助手没有生成回复:${detail}`)
292
- }
293
- return
294
- }
295
- if (event.type === 'assistant/message') {
296
- const text = (event.data?.message?.content ?? [])
297
- .filter((block) => block.type === 'text' && block.text)
298
- .map((block) => block.text ?? '')
299
- .join('\n')
300
- .trim()
301
- const stream = this.streams.get(streamKey)
302
- this.streams.delete(streamKey)
303
- if (stream && text) {
304
- await stream.finish(text).catch(() => this.deliver(channel, binding.chatId, text))
305
- return
306
- }
307
- if (text) {
308
- this.log(`[${channel.id}] 准备回复 ${sessionId},长度 ${text.length}`)
309
- await this.deliver(channel, binding.chatId, text)
310
- } else {
311
- this.log(`[${channel.id}] 助手消息为空 ${sessionId}`)
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
+