@michengai/dsh-im-connect 0.1.37 → 0.1.39

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 (74) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/CHANGELOG.zh-CN.md +17 -1
  3. package/README.en.md +60 -65
  4. package/README.md +60 -65
  5. package/SECURITY.md +7 -2
  6. package/client.js +31 -298
  7. package/lib/channels/channel-image-download.d.ts +22 -0
  8. package/lib/channels/channel-image-download.d.ts.map +1 -0
  9. package/lib/channels/channel-image-download.js +179 -0
  10. package/lib/channels/channel-image-download.js.map +1 -0
  11. package/lib/channels/dingtalk-token-cache.d.ts +18 -0
  12. package/lib/channels/dingtalk-token-cache.d.ts.map +1 -0
  13. package/lib/channels/dingtalk-token-cache.js +48 -0
  14. package/lib/channels/dingtalk-token-cache.js.map +1 -0
  15. package/lib/channels/dingtalk.d.ts +17 -4
  16. package/lib/channels/dingtalk.d.ts.map +1 -1
  17. package/lib/channels/dingtalk.js +111 -18
  18. package/lib/channels/dingtalk.js.map +1 -1
  19. package/lib/channels/factory.d.ts.map +1 -1
  20. package/lib/channels/factory.js +6 -3
  21. package/lib/channels/factory.js.map +1 -1
  22. package/lib/channels/feishu.d.ts +30 -2
  23. package/lib/channels/feishu.d.ts.map +1 -1
  24. package/lib/channels/feishu.js +141 -26
  25. package/lib/channels/feishu.js.map +1 -1
  26. package/lib/channels/image-host-policy.d.ts +4 -0
  27. package/lib/channels/image-host-policy.d.ts.map +1 -0
  28. package/lib/channels/image-host-policy.js +24 -0
  29. package/lib/channels/image-host-policy.js.map +1 -0
  30. package/lib/channels/qq.d.ts +1 -0
  31. package/lib/channels/qq.d.ts.map +1 -1
  32. package/lib/channels/qq.js +89 -18
  33. package/lib/channels/qq.js.map +1 -1
  34. package/lib/channels/telegram.d.ts.map +1 -1
  35. package/lib/channels/telegram.js +121 -16
  36. package/lib/channels/telegram.js.map +1 -1
  37. package/lib/channels/wecom.d.ts +8 -2
  38. package/lib/channels/wecom.d.ts.map +1 -1
  39. package/lib/channels/wecom.js +60 -11
  40. package/lib/channels/wecom.js.map +1 -1
  41. package/lib/channels/weixin.d.ts.map +1 -1
  42. package/lib/channels/weixin.js +169 -17
  43. package/lib/channels/weixin.js.map +1 -1
  44. package/lib/client.js +31 -298
  45. package/lib/engine/gateway.d.ts +2 -0
  46. package/lib/engine/gateway.d.ts.map +1 -1
  47. package/lib/engine/gateway.js +48 -11
  48. package/lib/engine/gateway.js.map +1 -1
  49. package/lib/engine/image-input.d.ts +8 -0
  50. package/lib/engine/image-input.d.ts.map +1 -0
  51. package/lib/engine/image-input.js +31 -0
  52. package/lib/engine/image-input.js.map +1 -0
  53. package/lib/engine/router.d.ts.map +1 -1
  54. package/lib/engine/router.js +29 -19
  55. package/lib/engine/router.js.map +1 -1
  56. package/lib/manager.d.ts +0 -10
  57. package/lib/manager.d.ts.map +1 -1
  58. package/lib/manager.js +231 -203
  59. package/lib/manager.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/channels/channel-image-download.ts +154 -0
  62. package/src/channels/dingtalk-token-cache.ts +39 -0
  63. package/src/channels/dingtalk.ts +106 -27
  64. package/src/channels/factory.ts +6 -3
  65. package/src/channels/feishu.ts +126 -24
  66. package/src/channels/image-host-policy.ts +21 -0
  67. package/src/channels/qq.ts +80 -26
  68. package/src/channels/telegram.ts +105 -16
  69. package/src/channels/wecom.ts +57 -12
  70. package/src/channels/weixin.ts +124 -14
  71. package/src/engine/gateway.ts +35 -6
  72. package/src/engine/image-input.ts +26 -0
  73. package/src/engine/router.ts +28 -18
  74. package/src/manager.ts +116 -84
@@ -1,6 +1,7 @@
1
- import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
1
+ import type { ChannelAdapter, ImMedia, ImMessage, ReplyStream } from '../engine/types.js'
2
2
  import { JsonStateFile } from '../engine/json-state.js'
3
3
  import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
4
+ import { imageMedia, MAX_CHANNEL_IMAGE_BYTES } from './channel-image-download.js'
4
5
 
5
6
  export interface TelegramConfig {
6
7
  token?: string
@@ -15,7 +16,11 @@ interface TgUpdate {
15
16
  from?: { id: number; username?: string; first_name?: string; is_bot?: boolean }
16
17
  text?: string
17
18
  caption?: string
19
+ media_group_id?: string
20
+ photo?: Array<{ file_id: string; width: number; height: number; file_size?: number }>
21
+ document?: { file_id: string; mime_type?: string; file_name?: string; file_size?: number }
18
22
  entities?: Array<{ type: string; offset: number; length: number }>
23
+ caption_entities?: Array<{ type: string; offset: number; length: number }>
19
24
  reply_to_message?: { from?: { id: number } }
20
25
  }
21
26
  }
@@ -36,6 +41,9 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
36
41
  let username = ''
37
42
  let lifecycle: AbortController | undefined
38
43
  let pollTask: Promise<void> | undefined
44
+ // Only metadata is buffered until an album member mentions this bot. Scope
45
+ // admission to chat + sender + album, and bound both lifetime and entry count.
46
+ const albumAccess = new Map<string, { expires: number; addressed: boolean; pending: TgUpdate[]; count: number }>()
39
47
 
40
48
  async function api<T>(method: string, body: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
41
49
  const res = await fetch(`${API}/bot${token}/${method}`, {
@@ -54,13 +62,51 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
54
62
  }
55
63
 
56
64
  function mentioned(message: NonNullable<TgUpdate['message']>): boolean {
57
- if (!username || !message.text || !Array.isArray(message.entities)) return false
58
- return message.entities.some((entity) => {
65
+ const text = message.text ?? message.caption
66
+ const entities = message.text !== undefined ? message.entities : message.caption_entities
67
+ if (!username || !text || !Array.isArray(entities)) return false
68
+ return entities.some((entity) => {
59
69
  if (entity.type !== 'mention') return false
60
- return message.text!.slice(entity.offset, entity.offset + entity.length).toLowerCase() === `@${username.toLowerCase()}`
70
+ return text.slice(entity.offset, entity.offset + entity.length).toLowerCase() === `@${username.toLowerCase()}`
61
71
  })
62
72
  }
63
73
 
74
+ async function downloadImages(message: NonNullable<TgUpdate['message']>): Promise<ImMedia[]> {
75
+ const photo = message.photo?.length ? message.photo.reduce((best, candidate) => candidate.width * candidate.height > best.width * best.height ? candidate : best) : undefined
76
+ const document = message.document?.mime_type?.startsWith('image/') ? message.document : undefined
77
+ const image = photo ?? document
78
+ if (!image) return []
79
+ if ((image.file_size ?? 0) > MAX_CHANNEL_IMAGE_BYTES) throw new Error('图片超过大小限制')
80
+ const file = await api<{ file_path?: string; file_size?: number }>('getFile', { file_id: image.file_id })
81
+ if (!file.file_path || !/^[a-zA-Z0-9_/-]+\.[a-zA-Z0-9]+$/.test(file.file_path)
82
+ || file.file_path.split('/').some(part => !part || part === '.' || part === '..')
83
+ || (file.file_size ?? 0) > MAX_CHANNEL_IMAGE_BYTES) throw new Error('图片文件无效或超过大小限制')
84
+ // The bot token must never follow a redirect or a caller-provided download URL.
85
+ const response = await fetch(`${API}/file/bot${token}/${file.file_path}`, {
86
+ redirect: 'error', signal: timeoutSignal(30_000, lifecycle?.signal),
87
+ })
88
+ if (!response.ok || !response.body) throw new Error('图片下载失败')
89
+ const reader = response.body.getReader()
90
+ const chunks: Uint8Array[] = []
91
+ let size = 0
92
+ try {
93
+ if (Number(response.headers.get('content-length')) > MAX_CHANNEL_IMAGE_BYTES) throw new Error('图片超过大小限制')
94
+ while (true) {
95
+ const { done, value } = await reader.read()
96
+ if (done) break
97
+ size += value.length
98
+ if (size > MAX_CHANNEL_IMAGE_BYTES) throw new Error('图片超过大小限制')
99
+ chunks.push(value)
100
+ }
101
+ const media = imageMedia(Buffer.concat(chunks))
102
+ const name = document?.file_name?.replace(/\\/g, '/').split('/').pop()
103
+ return [{ ...media, ...(name ? { name } : {}) }]
104
+ } finally {
105
+ await reader.cancel().catch(() => undefined)
106
+ reader.releaseLock()
107
+ }
108
+ }
109
+
64
110
  async function pollLoop(): Promise<void> {
65
111
  while (!stopped) {
66
112
  try {
@@ -71,6 +117,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
71
117
  }, 35_000)
72
118
  lastError = ''
73
119
  for (const update of updates) {
120
+ if (stopped) break
74
121
  // Telegram offset 是 at-most-once 取舍:先确认游标可避免崩溃重启后重复驱动 agent,代价是极端情况下丢一条未完成消息。
75
122
  offset = update.update_id + 1
76
123
  if (persist) cursorFile.write({ offset })
@@ -78,20 +125,60 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
78
125
  if (!message || message.from?.is_bot) continue
79
126
  if (!['private', 'group', 'supergroup'].includes(message.chat.type)) continue
80
127
  const direct = message.chat.type === 'private'
81
- const addressed = direct
128
+ let addressed = direct
82
129
  || String(message.reply_to_message?.from?.id ?? '') === botId
83
130
  || mentioned(message)
84
- let text = message.text ?? message.caption ?? ''
85
- if (username) text = text.replace(new RegExp(`@${username}\\b`, 'ig'), '').trim()
86
- void handler?.({
87
- chatId: String(message.chat.id),
88
- userId: message.from ? String(message.from.id) : undefined,
89
- username: message.from?.username ?? message.from?.first_name,
90
- text,
91
- kind: direct ? 'dm' : 'group',
92
- addressed,
93
- messageId: String(update.update_id),
94
- })
131
+ let deliveries = [update]
132
+ if (!direct && message.media_group_id && message.from?.id) {
133
+ const now = Date.now()
134
+ for (const [key, album] of albumAccess) if (album.expires <= now) albumAccess.delete(key)
135
+ const key = `${message.chat.id}:${message.from.id}:${message.media_group_id}`
136
+ let album = albumAccess.get(key)
137
+ if (!album) {
138
+ if (albumAccess.size >= 64) albumAccess.delete(albumAccess.keys().next().value!)
139
+ album = { expires: now + 30_000, addressed: false, pending: [], count: 0 }
140
+ albumAccess.set(key, album)
141
+ }
142
+ album.addressed ||= addressed
143
+ addressed = album.addressed
144
+ if (++album.count > 20) {
145
+ album.pending = []
146
+ if (addressed) await api('sendMessage', { chat_id: message.chat.id, text: '相册图片过多,请分批发送。' }).catch(() => undefined)
147
+ continue
148
+ }
149
+ if (!addressed) { album.pending.push(update); continue }
150
+ deliveries = [...album.pending, update]
151
+ album.pending = []
152
+ }
153
+ for (const delivery of deliveries) {
154
+ if (stopped) break
155
+ const message = delivery.message!
156
+ let text = message.text ?? message.caption ?? ''
157
+ if (username) text = text.replace(new RegExp(`@${username}\\b`, 'ig'), '').trim()
158
+ let media: ImMedia[] = []
159
+ if (addressed) {
160
+ try { media = await downloadImages(message) }
161
+ catch {
162
+ if (stopped) break
163
+ // Do not expose a token-bearing download URL through error messages.
164
+ log('[telegram] 图片接收失败')
165
+ await api('sendMessage', { chat_id: message.chat.id, text: '图片接收失败,请检查图片格式和大小后重新发送完整消息。' }).catch(() => log('[telegram] 图片失败提示发送失败'))
166
+ // A failed image caption must never turn into a text command.
167
+ continue
168
+ }
169
+ }
170
+ if (stopped) break
171
+ void handler?.({
172
+ chatId: String(message.chat.id),
173
+ userId: message.from ? String(message.from.id) : undefined,
174
+ username: message.from?.username ?? message.from?.first_name,
175
+ text,
176
+ ...(media.length ? { media } : {}),
177
+ kind: direct ? 'dm' : 'group',
178
+ addressed,
179
+ messageId: String(delivery.update_id),
180
+ })
181
+ }
95
182
  }
96
183
  } catch (error) {
97
184
  lastError = error instanceof Error ? error.message : String(error)
@@ -107,6 +194,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
107
194
  label: 'Telegram',
108
195
  maxMessageLength: 4000,
109
196
  async start() {
197
+ albumAccess.clear()
110
198
  lifecycle?.abort()
111
199
  lifecycle = new AbortController()
112
200
  stopped = false
@@ -122,6 +210,7 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
122
210
  },
123
211
  async stop() {
124
212
  stopped = true
213
+ albumAccess.clear()
125
214
  lifecycle?.abort()
126
215
  await pollTask?.catch(() => undefined)
127
216
  pollTask = undefined
@@ -1,9 +1,20 @@
1
- import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
1
+ import type { ChannelAdapter, ImMessage, ImMedia, ReplyStream } from '../engine/types.js'
2
2
  import { quietSdkLogger } from '../engine/quiet-logger.js'
3
+ import { requestChannelBytes, imageMedia, MAX_CHANNEL_IMAGES, channelImageFailureReason, channelImageDownloadHost } from './channel-image-download.js'
4
+ import { validateAdditionalImageHosts } from './image-host-policy.js'
5
+
6
+ async function downloadWecomImage(image: { url?: string; aeskey?: string }, additionalImageHosts: readonly string[]): Promise<ImMedia> {
7
+ if (!image.url || !image.aeskey) throw new Error('图片缺少下载地址或解密密钥')
8
+ // SDK downloadFile has no response-size or redirect/SSRF controls. Reuse its
9
+ // public decryptFile primitive after our bounded, DNS-pinned HTTPS transfer.
10
+ const { decryptFile } = await import('@wecom/aibot-node-sdk')
11
+ return imageMedia(decryptFile(await requestChannelBytes(image.url, { additionalTrustedHosts: additionalImageHosts }), image.aeskey))
12
+ }
3
13
 
4
14
  export interface WecomConfig {
5
15
  botId?: string
6
16
  secret?: string
17
+ additionalImageHosts?: readonly string[]
7
18
  }
8
19
 
9
20
  export interface WecomSdkClient {
@@ -139,15 +150,20 @@ export class WecomReplyBroker {
139
150
  }
140
151
  }
141
152
 
142
- export function createWecomChannel(config: WecomConfig, log: (line: string) => void): ChannelAdapter | undefined {
153
+ export function createWecomChannel(config: WecomConfig, log: (line: string) => void, dependencies: {
154
+ downloadImage?: (image: { url?: string; aeskey?: string }) => Promise<ImMedia>
155
+ } = {}): ChannelAdapter | undefined {
143
156
  const botId = config.botId?.trim()
144
157
  const secret = config.secret?.trim()
145
158
  if (!botId || !secret) return undefined
159
+ const additionalImageHosts = validateAdditionalImageHosts(config.additionalImageHosts)
146
160
 
147
161
  let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
148
162
  let client: WecomSdkClient | undefined
149
163
  let broker: WecomReplyBroker | undefined
150
164
  let statusText = '未连接'
165
+ let generation = 0
166
+ const receiving = new Map<string, Promise<void>>()
151
167
 
152
168
  return {
153
169
  id: 'wecom',
@@ -155,6 +171,7 @@ export function createWecomChannel(config: WecomConfig, log: (line: string) => v
155
171
  maxMessageLength: 4000,
156
172
  skipMerge: true,
157
173
  async start() {
174
+ const startedGeneration = ++generation
158
175
  let sdk: {
159
176
  WSClient: new (opts: { botId: string; secret: string; maxAuthFailureAttempts?: number; logger?: { debug: Function; info: Function; warn: Function; error: Function } }) => WecomSdkClient
160
177
  generateReqId?: (prefix: string) => string
@@ -176,22 +193,48 @@ export function createWecomChannel(config: WecomConfig, log: (line: string) => v
176
193
  const senderId = from?.userid ?? ''
177
194
  const chatId = chattype === 'group' ? String(body.chatid ?? '') : senderId
178
195
  const text = messageText(body)
179
- if (!chatId || !text || !['single', 'group'].includes(chattype)) {
196
+ const mixed = body.mixed as { msg_item?: Array<{ msgtype?: string; image?: { url?: string; aeskey?: string } }> } | undefined
197
+ const images = body.msgtype === 'image' ? [(body.image as { url?: string; aeskey?: string }) ?? {}]
198
+ : body.msgtype === 'mixed' && Array.isArray(mixed?.msg_item)
199
+ ? mixed.msg_item.filter(item => item?.msgtype === 'image').map(item => item.image ?? {}) : []
200
+ if (!chatId || (!text && !images.length) || !['single', 'group'].includes(chattype)) {
180
201
  log(`[wecom] 忽略一帧 chattype=${chattype || '-'} msgtype=${String(body.msgtype ?? '-')}`)
181
202
  return
182
203
  }
183
204
  // 企微长连接模式只会在群聊中 @ 当前机器人时推送回调,这里无需也无法校验 mention;
184
205
  // 不做 text.includes('@') 兜底,避免正文不含 ASCII @ 时误丢合法消息。
185
206
  log(`[wecom] 收到 ${chattype} ${senderId}: ${text.slice(0, 80)}`)
186
- broker?.remember(chatId, frame)
187
- void handler?.({
188
- chatId,
189
- userId: senderId,
190
- text,
191
- kind: chattype === 'group' ? 'group' : 'dm',
192
- addressed: true,
193
- messageId: typeof body.msgid === 'string' ? body.msgid : undefined,
194
- })
207
+ const work = (receiving.get(chatId) ?? Promise.resolve()).then(async () => {
208
+ if (generation !== startedGeneration) return
209
+ const media: ImMedia[] = []
210
+ try {
211
+ if (images.length > MAX_CHANNEL_IMAGES) throw new Error('图片数量超过限制')
212
+ for (const image of images) {
213
+ if (generation !== startedGeneration) return
214
+ media.push(await (dependencies.downloadImage ? dependencies.downloadImage(image) : downloadWecomImage(image, additionalImageHosts)))
215
+ }
216
+ } catch (error) {
217
+ if (generation !== startedGeneration) return
218
+ const reason = channelImageFailureReason(error)
219
+ log(`[wecom] 图片读取失败: ${reason} host=${images.slice(0, MAX_CHANNEL_IMAGES).map(image => channelImageDownloadHost(image.url)).join(',')}`)
220
+ // Reply directly: consuming the broker FIFO here could steal an earlier frame.
221
+ await client?.replyStream(frame, newStreamId(), `图片读取失败:${reason}。请重新发送;若仍失败请管理员检查网络和机器人配置。`, true)
222
+ return
223
+ }
224
+ if (generation !== startedGeneration) return
225
+ broker?.remember(chatId, frame)
226
+ await handler?.({
227
+ chatId,
228
+ media,
229
+ userId: senderId,
230
+ text,
231
+ kind: chattype === 'group' ? 'group' : 'dm',
232
+ addressed: true,
233
+ messageId: typeof body.msgid === 'string' ? body.msgid : undefined,
234
+ })
235
+ }).catch(() => { log('[wecom] 消息处理或回调回复失败') })
236
+ receiving.set(chatId, work)
237
+ void work.finally(() => { if (receiving.get(chatId) === work) receiving.delete(chatId) })
195
238
  })
196
239
  const ready = new Promise<void>((resolve, reject) => {
197
240
  const timer = setTimeout(() => reject(new Error('企业微信连接超时')), 20_000)
@@ -214,6 +257,8 @@ export function createWecomChannel(config: WecomConfig, log: (line: string) => v
214
257
  statusText = '长连接已建立'
215
258
  },
216
259
  async stop() {
260
+ generation++
261
+ receiving.clear()
217
262
  client?.disconnect()
218
263
  client = undefined
219
264
  broker?.dispose()
@@ -14,6 +14,7 @@ import type { ChannelAdapter, ImMedia, ImMessage } from '../engine/types.js'
14
14
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
15
15
  import { readFile } from 'node:fs/promises'
16
16
  import { join, basename } from 'node:path'
17
+ import { isIP } from 'node:net'
17
18
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
18
19
  import { writePrivateFileSync } from '../engine/secure-file.js'
19
20
  import { isAbortError, sleepWithSignal, timeoutSignal } from '../engine/abort.js'
@@ -95,6 +96,32 @@ export function buildCdnDownloadUrl(encryptedQueryParam: string, cdnBaseUrl = CD
95
96
  return `${cdnBaseUrl}/download?encrypted_query_param=${encodeURIComponent(encryptedQueryParam)}`
96
97
  }
97
98
 
99
+ type WeixinImageFailureKind = 'network' | 'server' | 'http' | 'timeout' | 'size' | 'format' | 'decrypt' | 'metadata' | 'unsafe' | 'storage'
100
+
101
+ /** 只保留固定分类,不记录底层异常消息、签名 URL 或密钥。 */
102
+ class WeixinImageError extends Error {
103
+ constructor(readonly kind: WeixinImageFailureKind, readonly status?: number) {
104
+ const reasons: Record<WeixinImageFailureKind, string> = {
105
+ network: '网络连接失败', server: `下载服务器暂时不可用(HTTP ${status})`,
106
+ http: `下载服务器返回 HTTP ${status}`, timeout: '下载超时', size: '图片超过 50 MiB 接收限制',
107
+ format: '图片格式无效或不支持,请发送 PNG、JPEG、GIF 或 WebP', decrypt: '图片解密失败或解密信息无效',
108
+ metadata: '图片缺少下载地址或解密信息', unsafe: '图片下载安全校验失败', storage: '图片保存失败',
109
+ }
110
+ super(reasons[kind])
111
+ this.name = 'WeixinImageError'
112
+ }
113
+ }
114
+
115
+ function imageTransportError(error: unknown): WeixinImageError {
116
+ if (error instanceof WeixinImageError) return error
117
+ const e = error as { name?: string; message?: string; code?: string; cause?: { code?: string } }
118
+ const code = e?.code ?? e?.cause?.code ?? ''
119
+ if (e?.name === 'TimeoutError' || e?.name === 'AbortError' || ['ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT'].includes(code)) return new WeixinImageError('timeout')
120
+ if (/^媒体超过 \d+ 字节上限$/.test(e?.message ?? '')) return new WeixinImageError('size')
121
+ if (/^(ERR_TLS_|ERR_SSL_|CERT_|DEPTH_ZERO_|UNABLE_TO_VERIFY_|SELF_SIGNED_)/.test(code)) return new WeixinImageError('unsafe')
122
+ return new WeixinImageError('network')
123
+ }
124
+
98
125
  // ── 工具函数 ────────────────────────────────────────────────────
99
126
 
100
127
  function pickStr(obj: Json, ...keys: string[]): string | undefined {
@@ -349,11 +376,61 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
349
376
  const plain = aesKey ? decryptAesEcb(buf, aesKey) : buf
350
377
  return { buf: plain, contentType: res.headers.get('content-type') ?? undefined }
351
378
  } catch (err) {
352
- log(`[weixin] 媒体下载失败: ${err instanceof Error ? err.message : String(err)}`)
379
+ log('[weixin] 媒体下载失败')
353
380
  return undefined
354
381
  }
355
382
  }
356
383
 
384
+ /** 仅重试图片下载,共享截止时间,不重试 POST 或解密操作。 */
385
+ async function downloadImageCdn(mediaRef: Json | undefined, aesKey: Buffer | undefined): Promise<{ buf: Buffer; contentType?: string }> {
386
+ const url = cdnUrlOf(mediaRef)
387
+ if (!url) throw new WeixinImageError('metadata')
388
+ try {
389
+ const target = new URL(url)
390
+ const hostname = target.hostname.replace(/\.$/, '')
391
+ // 保留协议中的 full_url,不因增加重试而引入单 CDN 限制;
392
+ // 拒绝明文、IP 直连、localhost 和 URL 凭据,下载时另行禁止重定向。
393
+ if (target.protocol !== 'https:' || target.username || target.password
394
+ || isIP(hostname) || hostname.includes(':')
395
+ || hostname === 'localhost' || hostname.endsWith('.localhost')) throw new Error()
396
+ } catch { throw new WeixinImageError('unsafe') }
397
+ const parent = lifecycle?.signal
398
+ const signal = timeoutSignal(60_000, parent)
399
+ for (let attempt = 0; ; attempt++) {
400
+ if (parent?.aborted) throw parent.reason
401
+ if (signal.aborted) throw new WeixinImageError('timeout')
402
+ let res: Response
403
+ let buf: Buffer
404
+ try {
405
+ res = await fetch(url, { signal, redirect: 'manual' })
406
+ if (!res.ok) {
407
+ await res.body?.cancel().catch(() => undefined)
408
+ throw new WeixinImageError(res.status >= 500 ? 'server' : 'http', res.status)
409
+ }
410
+ try { buf = await readResponseBufferLimited(res, MAX_WEIXIN_MEDIA_BYTES) } catch (error) {
411
+ await res.body?.cancel().catch(() => undefined)
412
+ throw error
413
+ }
414
+ signal.throwIfAborted()
415
+ } catch (error) {
416
+ if (parent?.aborted) throw parent.reason
417
+ if (signal.aborted) throw new WeixinImageError('timeout')
418
+ const e = error as { status?: number; cause?: { code?: string }; code?: string }
419
+ const retryable = (e.status !== undefined && e.status >= 500 && e.status <= 599)
420
+ || ['ECONNRESET', 'ECONNREFUSED', 'EAI_AGAIN', 'ETIMEDOUT', 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT'].includes(e.code ?? e.cause?.code ?? '')
421
+ if (attempt >= 1 || !retryable) throw imageTransportError(error)
422
+ try { await sleepWithSignal(150, signal) } catch {
423
+ if (parent?.aborted) throw parent.reason
424
+ throw new WeixinImageError('timeout')
425
+ }
426
+ continue
427
+ }
428
+ try {
429
+ return { buf: aesKey ? decryptAesEcb(buf, aesKey) : buf, contentType: res.headers.get('content-type') ?? undefined }
430
+ } catch { throw new WeixinImageError('decrypt') }
431
+ }
432
+ }
433
+
357
434
  /** 保存媒体字节到媒体目录。 */
358
435
  function saveMediaBuf(buf: Buffer, ext: string, prefix: string, name?: string): string {
359
436
  mkdirSync(mediaDir, { recursive: true })
@@ -377,14 +454,24 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
377
454
  async function downloadImageItem(item: Json): Promise<ImMedia> {
378
455
  const img = item.image_item as Json | undefined
379
456
  const mediaRef = img?.media as Json | undefined
380
- const aesKey = aesKeyOf(mediaRef, img ? pickStr(img, 'aeskey') : undefined, 'wechat-image')
381
- const dl = await downloadCdn(mediaRef, aesKey)
382
- if (!dl) return { kind: 'image', name: 'image' }
383
- // 从 CDN Content-Type 推断真实图片类型(避免 saveImage 校验失败)
384
- const ct = dl.contentType?.split(';')[0]?.trim().toLowerCase() ?? ''
385
- const ext = ct === 'image/png' ? '.png' : ct === 'image/gif' ? '.gif' : ct === 'image/webp' ? '.webp' : '.jpg'
386
- const mediaType = ct.startsWith('image/') ? ct : 'image/jpeg'
387
- const saved = saveMediaBuf(dl.buf, ext, 'image', `image${ext}`)
457
+ let aesKey: Buffer | undefined
458
+ try {
459
+ const hex = img ? pickStr(img, 'aeskey') : undefined
460
+ if (hex && !/^[a-fA-F0-9]{32}$/.test(hex)) throw new Error()
461
+ aesKey = aesKeyOf(mediaRef, hex, 'wechat-image')
462
+ if (!aesKey && Number(mediaRef?.encrypt_type) === 1) throw new Error()
463
+ } catch { throw new WeixinImageError('decrypt') }
464
+ const dl = await downloadImageCdn(mediaRef, aesKey)
465
+ // 根据明文字节判断格式,避免加密 CDN 的 octet-stream 响应头误导类型。
466
+ const buf = dl.buf
467
+ const ext = buf.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) ? '.png'
468
+ : buf.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex')) ? '.jpg'
469
+ : /^GIF8[79]a$/.test(buf.subarray(0, 6).toString('ascii')) ? '.gif'
470
+ : buf.subarray(0, 4).toString() === 'RIFF' && buf.subarray(8, 12).toString() === 'WEBP' ? '.webp' : undefined
471
+ if (!ext) throw new WeixinImageError('format')
472
+ const mediaType = mimeFromExt(ext)
473
+ let saved: string
474
+ try { saved = saveMediaBuf(buf, ext, 'image', `image${ext}`) } catch { throw new WeixinImageError('storage') }
388
475
  return { kind: 'image', path: saved, mediaType, name: basename(saved) }
389
476
  }
390
477
 
@@ -471,6 +558,8 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
471
558
  }
472
559
 
473
560
  async function pollLoop(): Promise<void> {
561
+ const generation = lifecycle
562
+ const current = () => !stopped && lifecycle === generation && !generation?.signal.aborted
474
563
  // 已有保存的登录态 → 跳过扫码直接轮询(重启免扫码)
475
564
  if (botToken) {
476
565
  statusText = '已登录(自动恢复)'
@@ -480,7 +569,7 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
480
569
  }
481
570
  let cursor = state.syncBuf ?? ''
482
571
  let staleCount = 0
483
- while (!stopped) {
572
+ while (current()) {
484
573
  let data: Json
485
574
  try {
486
575
  data = await request(
@@ -489,7 +578,7 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
489
578
  (config.pollTimeoutSecs ?? 70) * 1000 + 5000,
490
579
  )
491
580
  } catch (err) {
492
- if (stopped) return
581
+ if (!current()) return
493
582
  const msg = err instanceof Error ? err.message : String(err)
494
583
  // token 失效(服务端 errcode -14,与官方插件 STALE_TOKEN_ERRCODE 一致)
495
584
  if (isStaleWeixinTokenError(err)) {
@@ -517,6 +606,7 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
517
606
  await sleepWithSignal(5000, lifecycle?.signal)
518
607
  continue
519
608
  }
609
+ if (!current()) return
520
610
  staleCount = 0
521
611
  const nextCursor = pickStr(data, 'get_updates_buf', 'cursor', 'sync_buf') ?? cursor
522
612
  if (nextCursor !== cursor) {
@@ -526,19 +616,39 @@ export function createWeixinChannel(config: WeixinChannelConfig, log: (line: str
526
616
  const rawList = data.msgs ?? data.messages ?? data.updates
527
617
  if (Array.isArray(rawList)) {
528
618
  for (const raw of rawList) {
619
+ if (!current()) return
529
620
  try {
530
621
  const parsed = parseInbound(raw)
531
622
  if (!parsed) continue
532
623
  if (parsed.contextToken) state.contextTokens[parsed.fromUserId] = parsed.contextToken
533
624
  if (state.allowedUserId && parsed.fromUserId !== state.allowedUserId) continue
534
- // 单个媒体失败只降级丢媒体,不再连累文本整条丢弃
625
+ // 下载完整后再分发;图片失败不能将图文静默降级成文字。
535
626
  const settled = await Promise.allSettled(parsed.media)
627
+ if (!current()) return
536
628
  const media = []
629
+ let mediaFailed = false
630
+ let imageFailure: WeixinImageError | undefined
537
631
  for (const item of settled) {
538
- if (item.status === 'fulfilled') media.push(item.value)
539
- else log(`[weixin] 媒体下载失败,降级为纯文本: ${item.reason instanceof Error ? item.reason.message : String(item.reason)}`)
632
+ if (item.status === 'fulfilled') {
633
+ if (item.value.kind === 'image' && !item.value.path && !item.value.data) mediaFailed = true
634
+ else media.push(item.value)
635
+ } else {
636
+ mediaFailed = true
637
+ if (item.reason instanceof WeixinImageError) {
638
+ imageFailure ??= item.reason
639
+ log(`[weixin] 图片下载失败 category=${item.reason.kind}: ${item.reason.message}`)
640
+ } else log('[weixin] 媒体下载失败')
641
+ }
642
+ }
643
+ if (mediaFailed) {
644
+ if (!current()) return
645
+ const feedback = imageFailure ? `图片下载失败:${imageFailure.message}。整条消息未提交,请重新发送。` : '图片或媒体下载失败,请重新发送。'
646
+ await sendText(parsed.fromUserId, feedback).catch(() => log('[weixin] 媒体提示发送失败'))
647
+ // Never turn an image caption (e.g. /new) into a text-only command.
648
+ continue
540
649
  }
541
650
  if (parsed.text === '' && media.length === 0) continue
651
+ if (!current()) return
542
652
  void handler?.({
543
653
  chatId: parsed.fromUserId,
544
654
  userId: parsed.fromUserId,
@@ -1,4 +1,5 @@
1
1
  import type { Context } from '@deepseek-ai/cordis'
2
+ import { ImageInputError, imageInputFailure, imagePromptPart } from './image-input.js'
2
3
  import { ApprovalBroker } from './approval.js'
3
4
  import { SessionMerger } from './merge.js'
4
5
  import { SessionRouter } from './router.js'
@@ -80,6 +81,7 @@ export class ImEngine {
80
81
  private readonly wrappedUserQuestionServices = new WeakSet<object>()
81
82
  private legacyServiceTimer?: NodeJS.Timeout
82
83
  private disposed = false
84
+ private readonly inputScopes = new Map<string, AbortController>()
83
85
 
84
86
  constructor(
85
87
  private readonly ctx: Context,
@@ -154,16 +156,19 @@ export class ImEngine {
154
156
  this.config.provider = provider
155
157
  this.config.model = model
156
158
  this.config.reasoningEffort = reasoningEffort
159
+ for (const channelId of this.inputScopes.keys()) this.cancelInputs(channelId)
157
160
  void this.router.disposeAll()
158
161
  }
159
162
 
160
163
  setCwd(cwd: string): void {
161
164
  this.config.cwd = cwd
165
+ for (const channelId of this.inputScopes.keys()) this.cancelInputs(channelId)
162
166
  void this.router.disposeAll()
163
167
  }
164
168
 
165
169
  setPermission(permission: string): void {
166
170
  this.config.permissionPreset = permission
171
+ for (const channelId of this.inputScopes.keys()) this.cancelInputs(channelId)
167
172
  void this.router.disposeAll()
168
173
  }
169
174
 
@@ -177,6 +182,7 @@ export class ImEngine {
177
182
  }
178
183
 
179
184
  unregister(channelId: string): void {
185
+ this.cancelInputs(channelId)
180
186
  this.channels.delete(channelId)
181
187
  }
182
188
 
@@ -192,6 +198,7 @@ export class ImEngine {
192
198
  }
193
199
 
194
200
  async reloadChannel(channelId: string, options: { resetSessions?: boolean } = {}): Promise<void> {
201
+ this.cancelInputs(channelId)
195
202
  for (const sessionId of this.router.sessionIdsForChannel(channelId)) {
196
203
  this.cancelSessionInteractions(sessionId, new Error('账号配置已更新'))
197
204
  }
@@ -205,6 +212,7 @@ export class ImEngine {
205
212
 
206
213
  dispose(): void {
207
214
  this.disposed = true
215
+ for (const channelId of this.inputScopes.keys()) this.cancelInputs(channelId)
208
216
  if (this.legacyServiceTimer) clearTimeout(this.legacyServiceTimer)
209
217
  for (const off of this.disposeEvents) off()
210
218
  this.broker.dispose()
@@ -272,7 +280,7 @@ export class ImEngine {
272
280
  const text = msg.text.trim()
273
281
  const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
274
282
  const binding = this.router.lookup(channelId, kind, msg.chatId)
275
- if (text.startsWith('/')) {
283
+ if (text.startsWith('/') && !msg.media?.length) {
276
284
  const command = text.split(/\s+/, 1)[0]?.toLowerCase()
277
285
  if ((command === '/new' || command === '/clear')
278
286
  && binding
@@ -321,7 +329,7 @@ export class ImEngine {
321
329
  const allowWords = ['批准', '同意', 'yes', 'y', 'allow']
322
330
  const denyWords = ['拒绝', '不同意', 'no', 'n', 'reject', 'deny']
323
331
  const verdict = allowWords.includes(text.toLowerCase()) ? true : denyWords.includes(text.toLowerCase()) ? false : undefined
324
- if (verdict !== undefined) {
332
+ if (verdict !== undefined && !msg.media?.length) {
325
333
  if (!canAnswerToolApproval({ userAllowed: this.userAllowed(channelId, msg.userId), kind: msg.kind === 'group' ? 'group' : 'dm' })) {
326
334
  if (binding && this.broker.has(binding.sessionId)) {
327
335
  const hint = msg.kind === 'group'
@@ -350,7 +358,7 @@ export class ImEngine {
350
358
  }
351
359
  } catch (error) {
352
360
  this.log(`[${channelId}] 处理失败: ${error instanceof Error ? error.message : String(error)}`)
353
- await channel.send(msg.chatId, '消息处理失败,请查看本机日志。').catch(() => undefined)
361
+ await channel.send(msg.chatId, msg.media?.some(media => media.kind === 'image') ? imageInputFailure(error) : '消息处理失败,请查看本机日志。').catch(() => undefined)
354
362
  }
355
363
  }
356
364
 
@@ -375,20 +383,36 @@ export class ImEngine {
375
383
  }
376
384
 
377
385
  private async inject(channel: ChannelAdapter, msg: ImMessage): Promise<void> {
386
+ if (this.disposed || this.channels.get(channel.id) !== channel) return
387
+ let scope = this.inputScopes.get(channel.id)
388
+ if (!scope) this.inputScopes.set(channel.id, scope = new AbortController())
389
+ const { signal } = scope
378
390
  const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
379
391
  const title = (msg.username || msg.text || msg.chatId).slice(0, 40)
380
392
  const binding = await this.router.getOrCreate(channel.id, kind, msg.chatId, title)
381
393
  const content: Array<Record<string, unknown>> = []
382
394
  if (msg.text.trim()) content.push({ type: 'text', text: msg.text.trim() })
383
395
  for (const media of msg.media ?? []) {
384
- if (media.kind === 'voice-text' && media.text) content.push({ type: 'text', text: `[语音] ${media.text}` })
396
+ if (media.kind === 'image') content.push(await imagePromptPart(media))
397
+ else if (media.kind === 'voice-text' && media.text) content.push({ type: 'text', text: `[语音] ${media.text}` })
385
398
  else if (media.path) content.push({ type: 'text', text: `[附件 ${media.name ?? media.kind}] ${media.path}` })
386
399
  }
387
- if (content.length === 0) return
400
+ if (signal.aborted || content.length === 0) return
388
401
  if (msg.userId) this.sessionActors.set(binding.sessionId, msg.userId)
389
402
  this.streams.reset(`${channel.id}:${msg.chatId}`)
390
403
  await channel.sendAction?.(msg.chatId, 'typing').catch(() => undefined)
391
- this.router.followup(binding, {
404
+ if (signal.aborted) return
405
+ if (content.some(part => part.type === 'image')) {
406
+ // Use Chat's public admission entry: session-local model selection, shared
407
+ // model-switch serialization, and durable attachment validation/storage.
408
+ // Optional lookup preserves text-only operation on older Hosts. Keep
409
+ // strict lookup so a pending or unloading provider is never invoked.
410
+ const controller = (this.ctx as unknown as { get(name: string): unknown }).get('sessionController') as {
411
+ prompt(request: { requestId: string; sessionId: string; mode: 'queue'; content: Array<Record<string, unknown>> }, signal: AbortSignal): Promise<unknown>
412
+ } | undefined
413
+ if (!controller?.prompt) throw new ImageInputError('当前 Host 不支持 Chat 图片输入,请升级 DeepSeek Harness。')
414
+ await controller.prompt({ requestId: crypto.randomUUID(), sessionId: binding.sessionId, mode: 'queue', content }, signal)
415
+ } else this.router.followup(binding, {
392
416
  id: crypto.randomUUID(),
393
417
  role: 'user',
394
418
  content,
@@ -397,6 +421,11 @@ export class ImEngine {
397
421
  this.log(`[${channel.id}] 已注入 ${binding.sessionId}`)
398
422
  }
399
423
 
424
+ private cancelInputs(channelId: string): void {
425
+ this.inputScopes.get(channelId)?.abort()
426
+ this.inputScopes.delete(channelId)
427
+ }
428
+
400
429
  private async answerApproval(channelId: string, msg: ImMessage, allow: boolean): Promise<boolean> {
401
430
  const binding = this.router.lookup(channelId, msg.kind === 'group' ? 'group' : 'dm', msg.chatId)
402
431
  if (!binding) return false