@michengai/dsh-im-connect 0.1.68 → 0.1.71

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 (45) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/CHANGELOG.zh-CN.md +19 -1
  3. package/README.md +37 -15
  4. package/README.zh-CN.md +38 -15
  5. package/SECURITY.md +2 -2
  6. package/assets/brands/discord-symbol.svg +3 -0
  7. package/assets/brands/slack-hash.png +0 -0
  8. package/assets/brands/slack-hash.svg +6 -0
  9. package/assets/brands//346/235/245/346/272/220.txt +14 -0
  10. package/client.js +72 -23
  11. package/lib/channels/channel-image-download.d.ts +3 -1
  12. package/lib/channels/channel-image-download.d.ts.map +1 -1
  13. package/lib/channels/channel-image-download.js +37 -3
  14. package/lib/channels/channel-image-download.js.map +1 -1
  15. package/lib/channels/factory.d.ts.map +1 -1
  16. package/lib/channels/factory.js +4 -0
  17. package/lib/channels/factory.js.map +1 -1
  18. package/lib/channels/meta.d.ts.map +1 -1
  19. package/lib/channels/meta.js +11 -0
  20. package/lib/channels/meta.js.map +1 -1
  21. package/lib/channels/slack-markdown.d.ts +34 -0
  22. package/lib/channels/slack-markdown.d.ts.map +1 -0
  23. package/lib/channels/slack-markdown.js +161 -0
  24. package/lib/channels/slack-markdown.js.map +1 -0
  25. package/lib/channels/slack.d.ts +106 -0
  26. package/lib/channels/slack.d.ts.map +1 -0
  27. package/lib/channels/slack.js +804 -0
  28. package/lib/channels/slack.js.map +1 -0
  29. package/lib/client.js +72 -23
  30. package/lib/engine/session-id.d.ts +1 -1
  31. package/lib/engine/session-id.d.ts.map +1 -1
  32. package/lib/engine/session-id.js +1 -1
  33. package/lib/engine/session-id.js.map +1 -1
  34. package/lib/manager.d.ts +3 -0
  35. package/lib/manager.d.ts.map +1 -1
  36. package/lib/manager.js +35 -1
  37. package/lib/manager.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/channels/channel-image-download.ts +30 -2
  40. package/src/channels/factory.ts +3 -0
  41. package/src/channels/meta.ts +11 -0
  42. package/src/channels/slack-markdown.ts +162 -0
  43. package/src/channels/slack.ts +828 -0
  44. package/src/engine/session-id.ts +2 -2
  45. package/src/manager.ts +27 -1
@@ -0,0 +1,828 @@
1
+ /**
2
+ * Slack:Socket Mode 长连接(WebSocket)+ Web API。
3
+ *
4
+ * 私聊直接回复;频道与群聊里只有被 @ 才响应,并且在该消息的线程内回复,避免刷屏。
5
+ * 传输只用 Node 自带的 WebSocket 与 fetch,与 Discord、QQ 渠道保持一致,不引入平台 SDK。
6
+ */
7
+ import { choiceSendError } from '../engine/choice-delivery.js'
8
+ import { channelNotice } from '../engine/command-locale.js'
9
+ import type { ChannelAdapter, ImMedia, ImMessage, ReplyStream } from '../engine/types.js'
10
+ import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
11
+ import { splitText } from '../engine/split.js'
12
+ import { DiagnosticError, diagnosticJson, probe, requireDiagnostic } from './diagnostics.js'
13
+ import { fileMedia, imageMedia, MAX_CHANNEL_IMAGE_BYTES, MAX_CHANNEL_IMAGES, requestChannelBytes } from './channel-image-download.js'
14
+ import { prepareSlackText, slackInboundText, slackMentionsBot } from './slack-markdown.js'
15
+ import { fileForm } from './file-send.js'
16
+ import { JsonStateFile } from '../engine/json-state.js'
17
+ import { join } from 'node:path'
18
+
19
+ export interface SlackSocketEvent { data?: unknown; code?: number; reason?: string }
20
+ export interface SlackSocket {
21
+ addEventListener(type: string, listener: (event: SlackSocketEvent) => void): void
22
+ send(data: string): void
23
+ close(code?: number, reason?: string): void
24
+ }
25
+
26
+ export interface SlackConfig {
27
+ token?: string
28
+ appToken?: string
29
+ /** 账号状态目录,用于恢复已参与线程;不配置时只保留当前适配器内存记录。 */
30
+ stateDir?: string
31
+ host?: { get(name: string): unknown }
32
+ fetchImpl?: typeof fetch
33
+ createWebSocket?: (url: string) => SlackSocket
34
+ apiBase?: string
35
+ connectTimeoutMs?: number
36
+ }
37
+
38
+ interface SlackFile {
39
+ id?: string
40
+ name?: string
41
+ mimetype?: string
42
+ size?: number
43
+ url_private?: string
44
+ url_private_download?: string
45
+ }
46
+
47
+ interface SlackEvent {
48
+ type?: string
49
+ subtype?: string
50
+ hidden?: boolean
51
+ channel?: string
52
+ channel_type?: string
53
+ user?: string
54
+ username?: string
55
+ bot_id?: string
56
+ text?: string
57
+ ts?: string
58
+ thread_ts?: string
59
+ files?: SlackFile[]
60
+ }
61
+
62
+ interface SlackAction { action_id?: string; value?: string }
63
+
64
+ interface SlackInteraction {
65
+ type?: string
66
+ user?: { id?: string; username?: string; name?: string }
67
+ channel?: { id?: string; name?: string }
68
+ message?: { ts?: string; thread_ts?: string }
69
+ container?: { channel_id?: string; thread_ts?: string }
70
+ actions?: SlackAction[]
71
+ }
72
+
73
+ interface SlackEnvelope {
74
+ type?: string
75
+ envelope_id?: string
76
+ reason?: string
77
+ payload?: unknown
78
+ }
79
+
80
+ /** 解析后的收件目标:chatId 里用 `~` 带上线程根,回复才能落在原线程。 */
81
+ export interface SlackRoute {
82
+ chatId: string
83
+ channel: string
84
+ threadTs?: string
85
+ kind: 'dm' | 'group'
86
+ addressed: boolean
87
+ userId: string
88
+ username?: string
89
+ text: string
90
+ messageId: string
91
+ actionToken?: string
92
+ threadKey?: string
93
+ }
94
+
95
+ const API = 'https://slack.com/api/'
96
+ const MESSAGE_LIMIT = 4_000
97
+ const SECTION_LIMIT = 2_900
98
+ const FILE_LIMIT = 20 * 1024 * 1024
99
+ const MAX_BUTTONS = 25
100
+ const BUTTON_TEXT_LIMIT = 75
101
+ const FLUSH_INTERVAL_MS = 1_100
102
+ const SEEN_TTL_MS = 5 * 60_000
103
+ const RECONNECT_DELAYS = [1_000, 3_000, 5_000, 10_000, 30_000]
104
+ /** url_private 只允许 Slack 自己的文件域名,令牌不能跟着任意地址走。 */
105
+ const FILE_HOSTS = new Set(['files.slack.com'])
106
+ /** 事件里只处理这几种消息子类型,其余(编辑、撤回、入群等)不驱动 agent。 */
107
+ const MESSAGE_SUBTYPES = new Set(['file_share', 'thread_broadcast'])
108
+ const AUTH_ERRORS = new Set(['invalid_auth', 'not_authed', 'account_inactive', 'token_revoked', 'invalid_refresh_token', 'not_allowed_token_type', 'missing_scope'])
109
+
110
+ const CHANNEL_ID = /^[A-Za-z0-9]{2,32}$/
111
+ const MESSAGE_TS = /^\d{1,20}\.\d{1,10}$/
112
+ /** Bot Token 必须是 xoxb-。用户令牌 xoxp- 会绕过机器人身份,不接受。App-Level Token 固定 xapp-。 */
113
+ const BOT_TOKEN_PREFIX = /^xoxb-/
114
+ const APP_TOKEN_PREFIX = /^xapp-/
115
+ const BOT_TOKEN_HINT = 'Slack Bot Token 不对:请在 Slack 应用的 OAuth & Permissions 页面安装应用后,复制 Bot User OAuth Token(xoxb- 开头)。App ID、Client ID、Client Secret、Signing Secret、Verification Token 都不是这个字段要填的内容。'
116
+ const APP_TOKEN_HINT = 'Slack App Token 不对:请在 Slack 应用的 Socket Mode 页面点 Generate Token and Scopes 生成 App-Level Token(xapp- 开头,勾 connections:write),它只显示一次。'
117
+
118
+ function credentialError(message: string): Error {
119
+ return Object.assign(new Error(message), { rejected: true, code: 'slack-401', status: 401 })
120
+ }
121
+
122
+ function codePoints(value: string): string[] {
123
+ return [...value]
124
+ }
125
+
126
+ function clip(value: string, limit: number): string {
127
+ return codePoints(value).slice(0, limit).join('')
128
+ }
129
+
130
+ function errorMessage(error: unknown): string {
131
+ return error instanceof Error ? error.message : String(error)
132
+ }
133
+
134
+ /** chatId 是渠道不透明标识:频道号 + 线程根。 */
135
+ export function slackChatId(channel: string, threadTs?: string): string {
136
+ return threadTs ? `${channel}~${threadTs}` : channel
137
+ }
138
+
139
+ export function parseSlackChatId(chatId: string): { channel: string; threadTs?: string } {
140
+ const index = chatId.indexOf('~')
141
+ const channel = index < 0 ? chatId : chatId.slice(0, index)
142
+ const threadTs = index < 0 ? undefined : chatId.slice(index + 1)
143
+ if (!CHANNEL_ID.test(channel) || (threadTs !== undefined && !MESSAGE_TS.test(threadTs))) {
144
+ throw Object.assign(new Error('slack-invalid-chat'), { rejected: true })
145
+ }
146
+ return threadTs === undefined ? { channel } : { channel, threadTs }
147
+ }
148
+
149
+ export function slackChatKind(channelId: string, channelName?: string): 'dm' | 'group' {
150
+ return channelId.startsWith('D') || channelName === 'directmessage' ? 'dm' : 'group'
151
+ }
152
+
153
+ export function slackSocketUrl(value: unknown): string {
154
+ const url = new URL(String(value ?? ''))
155
+ const host = url.hostname.toLowerCase()
156
+ if (url.protocol !== 'wss:' || url.username || url.password || (host !== 'slack.com' && !host.endsWith('.slack.com'))) {
157
+ throw new Error('Slack Socket Mode URL is invalid')
158
+ }
159
+ return url.href
160
+ }
161
+
162
+ /**
163
+ * Slack 客户端会拦截半角 /。已知命令可用 !help 或全角 /help 发出,规则与 Discord 相同;未知感叹号保持原文。
164
+ */
165
+ const SLACK_BANG_COMMANDS = new Set(['menu', 'm', 'new', 'clear', 'stop', 'status', 'help', 'sessions', 'models', 'export'])
166
+
167
+ export function normalizeSlackCommand(text: string): string {
168
+ const match = /^[!/]([a-z][a-z0-9_-]*)(\s*[\s\S]*)$/i.exec(text.trim())
169
+ const command = match?.[1]?.toLowerCase()
170
+ if (!command || !SLACK_BANG_COMMANDS.has(command)) return text
171
+ const name = command === 'm' ? 'menu' : command
172
+ return `/${name}${match?.[2] ?? ''}`
173
+ }
174
+
175
+ /**
176
+ * 事件 → 收件目标。返回 undefined 表示这条事件不该驱动 agent。
177
+ * 频道消息在「被 @」、所在线程已经参与过,或用 ! / 全角斜杠发出已知命令时算被呼叫。
178
+ */
179
+ export function slackRoute(
180
+ event: SlackEvent,
181
+ botUserId: string,
182
+ knownThreads?: { has(key: string): boolean },
183
+ ): SlackRoute | undefined {
184
+ if (event.type !== 'message' && event.type !== 'app_mention') return undefined
185
+ if (event.hidden === true) return undefined
186
+ if (event.subtype !== undefined && !MESSAGE_SUBTYPES.has(event.subtype)) return undefined
187
+ if (event.bot_id || !event.channel || !CHANNEL_ID.test(event.channel) || !event.ts || !MESSAGE_TS.test(event.ts)) return undefined
188
+ const userId = typeof event.user === 'string' ? event.user : ''
189
+ if (!userId || userId === botUserId) return undefined
190
+ const direct = event.channel_type === 'im'
191
+ const mentioned = event.type === 'app_mention' || slackMentionsBot(event.text, botUserId)
192
+ const inbound = slackInboundText(event.text ?? '', botUserId)
193
+ const text = normalizeSlackCommand(inbound)
194
+ const prefixed = text.startsWith('/') && text !== inbound
195
+ const threadRoot = direct ? undefined : (event.thread_ts && MESSAGE_TS.test(event.thread_ts) ? event.thread_ts : event.ts)
196
+ const threadKey = threadRoot === event.ts ? `${event.channel}~${event.ts}` : `${event.channel}~${threadRoot ?? ''}`
197
+ const inKnownThread = !direct && Boolean(event.thread_ts) && Boolean(knownThreads?.has(threadKey))
198
+ if (!direct && !mentioned && !inKnownThread && !prefixed) return undefined
199
+ return {
200
+ chatId: slackChatId(event.channel, threadRoot),
201
+ channel: event.channel,
202
+ ...(threadRoot ? { threadTs: threadRoot } : {}),
203
+ kind: direct ? 'dm' : 'group',
204
+ addressed: direct || mentioned || inKnownThread || prefixed,
205
+ userId,
206
+ ...(event.username ? { username: event.username } : {}),
207
+ text,
208
+ messageId: event.ts,
209
+ ...(direct ? {} : { threadKey }),
210
+ }
211
+ }
212
+
213
+ /** 卡片按钮回调 → 收件目标。 */
214
+ export function slackActionRoute(payload: SlackInteraction): SlackRoute | undefined {
215
+ if (payload.type !== 'block_actions') return undefined
216
+ const action = payload.actions?.[0]
217
+ const token = action?.action_id ?? action?.value
218
+ const channel = payload.container?.channel_id ?? payload.channel?.id
219
+ const userId = payload.user?.id
220
+ if (!token || typeof channel !== 'string' || !CHANNEL_ID.test(channel) || typeof userId !== 'string' || !userId) return undefined
221
+ const threadTs = payload.message?.thread_ts && MESSAGE_TS.test(payload.message.thread_ts)
222
+ ? payload.message.thread_ts
223
+ : payload.container?.thread_ts && MESSAGE_TS.test(payload.container.thread_ts) ? payload.container.thread_ts : undefined
224
+ const ts = payload.message?.ts && MESSAGE_TS.test(payload.message.ts) ? payload.message.ts : ''
225
+ return {
226
+ chatId: slackChatId(channel, threadTs),
227
+ channel,
228
+ ...(threadTs ? { threadTs } : {}),
229
+ kind: slackChatKind(channel, payload.channel?.name),
230
+ addressed: true,
231
+ userId,
232
+ ...(payload.user?.username ?? payload.user?.name ? { username: payload.user?.username ?? payload.user?.name } : {}),
233
+ text: '',
234
+ messageId: `interaction:${ts || channel}`,
235
+ actionToken: token,
236
+ }
237
+ }
238
+
239
+ function slackError(method: string, status: number, code?: string): Error {
240
+ const auth = status === 401 || (code !== undefined && AUTH_ERRORS.has(code))
241
+ // 网关响应缺失或服务器内部错误不能证明请求未执行,不能据此自动补发。
242
+ const uncertain = new Set(['invalid_response', 'internal_error', 'fatal_error', 'request_timeout', 'service_unavailable'])
243
+ const rejected = (status >= 400 && status < 500 && status !== 408)
244
+ || (status >= 200 && status < 300 && code !== undefined && !uncertain.has(code))
245
+ return Object.assign(new Error(`slack-${method}-${code ?? status}`), {
246
+ status,
247
+ ...(code === undefined ? {} : { slackCode: code }),
248
+ rejected,
249
+ ...(auth ? { code: 'slack-401' } : {}),
250
+ })
251
+ }
252
+
253
+ /** 令牌失效、缺少授权范围不会自愈,重连也没有意义。 */
254
+ function fatalSlack(error: unknown): boolean {
255
+ const value = error as { code?: string; status?: number; slackCode?: string } | undefined
256
+ if (value?.code === 'slack-401' || value?.status === 401 || value?.status === 403) return true
257
+ return value?.slackCode !== undefined && AUTH_ERRORS.has(value.slackCode)
258
+ }
259
+
260
+ function recoverableSlack(error: unknown): boolean {
261
+ if (fatalSlack(error)) return false
262
+ const status = (error as { status?: number } | undefined)?.status
263
+ if (status === undefined) return true
264
+ return status === 429 || status >= 500
265
+ }
266
+
267
+ /** 带 blocks 的消息只渲染块,纯 text 会退化成通知文案,所以正文必须自己放进 section 块。 */
268
+ function sectionBlocks(text: string): unknown[] {
269
+ return splitText(text || '…', SECTION_LIMIT).map((part) => ({
270
+ type: 'section', text: { type: 'mrkdwn', text: part },
271
+ }))
272
+ }
273
+
274
+ function actionBlocks(buttons: Array<{ label: string; token: string }>): unknown[] {
275
+ const blocks: unknown[] = []
276
+ for (let index = 0; index < buttons.length; index += 5) {
277
+ blocks.push({
278
+ type: 'actions',
279
+ elements: buttons.slice(index, index + 5).map((button) => ({
280
+ type: 'button',
281
+ text: { type: 'plain_text', text: clip(button.label, BUTTON_TEXT_LIMIT) || '…', emoji: true },
282
+ action_id: clip(button.token, 255),
283
+ value: clip(button.token, 2_000),
284
+ })),
285
+ })
286
+ }
287
+ return blocks
288
+ }
289
+
290
+ export function createSlackChannel(config: SlackConfig, log: (line: string) => void): ChannelAdapter | undefined {
291
+ const token = config.token?.trim()
292
+ const appToken = config.appToken?.trim()
293
+ if (!token || !appToken) return undefined
294
+ const fetchImpl = config.fetchImpl ?? fetch
295
+ const apiBase = `${(config.apiBase ?? API).replace(/\/+$/, '')}/`
296
+ const createSocket = config.createWebSocket ?? ((url: string) => new WebSocket(url))
297
+
298
+ let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
299
+ let stopped = true
300
+ let starting = false
301
+ let readyOnce = false
302
+ let statusText = '已停止'
303
+ let lifecycle = new AbortController()
304
+ let socket: SlackSocket | undefined
305
+ let generation = 0
306
+ let reconnectAttempt = 0
307
+ let haltReconnect = false
308
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined
309
+ let botUserId = ''
310
+ let botId = ''
311
+ /** Slack 会同时投递 app_mention 与 message 事件,按 channel+ts 去重。 */
312
+ const seenEvents = new Map<string, number>()
313
+ /** 参与过的线程:后续没被 @ 的线程回复也要继续响应。 */
314
+ const participatedThreads = new Map<string, number>()
315
+ const threadFile = config.stateDir
316
+ ? new JsonStateFile<{ botUserId?: string; threads?: unknown }>(join(config.stateDir, 'slack-threads.json'), {})
317
+ : undefined
318
+
319
+ function restoreThreads(identity: string): void {
320
+ if (botUserId !== identity) participatedThreads.clear()
321
+ const saved = threadFile?.read()
322
+ if (saved?.botUserId !== identity || !Array.isArray(saved.threads)) return
323
+ for (const key of saved.threads.slice(-512)) {
324
+ if (typeof key !== 'string') continue
325
+ try {
326
+ const route = parseSlackChatId(key)
327
+ if (route.threadTs) participatedThreads.set(key, Number.POSITIVE_INFINITY)
328
+ } catch { /* 忽略损坏的线程记录,不能扩大免提及范围。 */ }
329
+ }
330
+ }
331
+
332
+ function prune(store: Map<string, number>): void {
333
+ const now = Date.now()
334
+ for (const [key, expires] of store) if (expires <= now) store.delete(key)
335
+ while (store.size > 512) store.delete(store.keys().next().value!)
336
+ }
337
+
338
+ function rememberThread(key: string): void {
339
+ participatedThreads.delete(key)
340
+ participatedThreads.set(key, Number.POSITIVE_INFINITY)
341
+ while (participatedThreads.size > 512) participatedThreads.delete(participatedThreads.keys().next().value!)
342
+ if (threadFile) {
343
+ try { threadFile.write({ botUserId, threads: [...participatedThreads.keys()] }) }
344
+ catch { log('[slack] 参与线程记录保存失败,重启后可能需要重新 @机器人') }
345
+ }
346
+ }
347
+
348
+ function firstSight(store: Map<string, number>, key: string): boolean {
349
+ prune(store)
350
+ if (store.has(key)) return false
351
+ store.set(key, Date.now() + SEEN_TTL_MS)
352
+ return true
353
+ }
354
+
355
+ async function api<T extends Record<string, unknown>>(
356
+ method: string,
357
+ body: Record<string, unknown> = {},
358
+ options: { token?: string; signal?: AbortSignal; timeoutMs?: number } = {},
359
+ ): Promise<T> {
360
+ const credential = options.token ?? token
361
+ for (let attempt = 0; ; attempt += 1) {
362
+ const response = await fetchImpl(`${apiBase}${method}`, {
363
+ method: 'POST',
364
+ headers: { 'content-type': 'application/json; charset=utf-8', authorization: `Bearer ${credential}` },
365
+ body: JSON.stringify(body),
366
+ signal: timeoutSignal(options.timeoutMs ?? 30_000, AbortSignal.any([...(options.signal ? [options.signal] : []), lifecycle.signal])),
367
+ redirect: 'error',
368
+ })
369
+ // Slack 的频道级限流按秒计,重试一次比把失败抛给用户更合适。
370
+ if (response.status === 429 && attempt === 0) {
371
+ const wait = Math.min(Math.max(Number(response.headers.get('retry-after')) || 1, 1), 5)
372
+ await response.body?.cancel().catch(() => undefined)
373
+ await sleepWithSignal(wait * 1_000, lifecycle.signal).catch(() => undefined)
374
+ continue
375
+ }
376
+ const payload = await response.json().catch(() => undefined) as { ok?: boolean; error?: string } | undefined
377
+ // 代理返回的 HTML 页面也是 200:没有 JSON 就不能当成功。
378
+ if (!payload || typeof payload !== 'object' || typeof payload.ok !== 'boolean') throw slackError(method, response.status, 'invalid_response')
379
+ if (!response.ok) throw slackError(method, response.status, typeof payload.error === 'string' ? payload.error : undefined)
380
+ if (payload.ok === false) throw slackError(method, response.status, payload.error)
381
+ return payload as T
382
+ }
383
+ }
384
+
385
+ function sendAck(envelopeId: string): void {
386
+ try {
387
+ socket?.send(JSON.stringify({ envelope_id: envelopeId }))
388
+ } catch {
389
+ log('[slack] 事件确认失败')
390
+ }
391
+ }
392
+
393
+ function authorizedFileUrl(value: unknown): string {
394
+ const url = new URL(String(value ?? ''))
395
+ if (url.protocol !== 'https:' || url.username || url.password || (url.port && url.port !== '443') || !FILE_HOSTS.has(url.hostname.toLowerCase())) {
396
+ throw new Error('图片地址不符合安全要求')
397
+ }
398
+ return url.href
399
+ }
400
+
401
+ async function loadMedia(event: SlackEvent): Promise<ImMedia[]> {
402
+ const files = (event.files ?? []).slice(0, MAX_CHANNEL_IMAGES)
403
+ const media: ImMedia[] = []
404
+ for (const file of files) {
405
+ const raw = typeof file.url_private_download === 'string' ? file.url_private_download
406
+ : typeof file.url_private === 'string' ? file.url_private : ''
407
+ if (!raw) continue
408
+ const isImage = typeof file.mimetype === 'string' && file.mimetype.startsWith('image/')
409
+ const maxBytes = isImage ? MAX_CHANNEL_IMAGE_BYTES : FILE_LIMIT
410
+ if (typeof file.size === 'number' && file.size > maxBytes) throw new Error('文件超过大小限制')
411
+ const data = await requestChannelBytes(authorizedFileUrl(raw), {
412
+ headers: { authorization: `Bearer ${token}` },
413
+ maxBytes,
414
+ timeoutMs: 30_000,
415
+ signal: AbortSignal.any([lifecycle.signal, AbortSignal.timeout(60_000)]),
416
+ sameHostRedirects: 3,
417
+ })
418
+ const head = data.subarray(0, 32).toString('utf8').trimStart().toLowerCase()
419
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) throw new Error('图片地址不符合安全要求')
420
+ media.push(isImage ? imageMedia(data) : fileMedia(data, file.name ?? 'file.bin'))
421
+ }
422
+ return media
423
+ }
424
+
425
+ async function postMessage(chatId: string, text: string, signal?: AbortSignal, blocks?: unknown[]): Promise<{ ts?: string; channel?: string }> {
426
+ const route = parseSlackChatId(chatId)
427
+ return api<{ ts?: string; channel?: string }>('chat.postMessage', {
428
+ channel: route.channel,
429
+ text,
430
+ mrkdwn: true,
431
+ unfurl_links: false,
432
+ unfurl_media: false,
433
+ ...(route.threadTs ? { thread_ts: route.threadTs } : {}),
434
+ ...(blocks ? { blocks } : {}),
435
+ }, { signal })
436
+ }
437
+
438
+ async function acceptEvent(event: SlackEvent): Promise<void> {
439
+ const route = slackRoute(event, botUserId, participatedThreads)
440
+ if (!route) return
441
+ if (!firstSight(seenEvents, `${route.channel}:${route.messageId}`)) return
442
+ if (route.threadKey) rememberThread(route.threadKey)
443
+ let media: ImMedia[] = []
444
+ if (event.files?.length) {
445
+ try {
446
+ media = await loadMedia(event)
447
+ } catch {
448
+ if (stopped) return
449
+ // 失败原因可能带签名地址,只写本机日志;聊天里给固定文案。
450
+ log('[slack] 图片或文件接收失败')
451
+ await postMessage(route.chatId, channelNotice(config.host, '图片或文件接收失败,请检查格式和大小后重新发送完整消息。'), undefined, undefined)
452
+ .catch(() => log('[slack] 失败提示发送失败'))
453
+ return
454
+ }
455
+ }
456
+ if (stopped) return
457
+ await handler?.({
458
+ chatId: route.chatId,
459
+ userId: route.userId,
460
+ ...(route.username ? { username: route.username } : {}),
461
+ text: route.text,
462
+ ...(media.length ? { media } : {}),
463
+ kind: route.kind,
464
+ addressed: route.addressed,
465
+ messageId: route.messageId,
466
+ })
467
+ }
468
+
469
+ async function acceptEnvelope(envelope: SlackEnvelope): Promise<void> {
470
+ if (envelope.type === 'events_api') {
471
+ const payload = envelope.payload as { event?: SlackEvent } | undefined
472
+ if (payload?.event) await acceptEvent(payload.event)
473
+ return
474
+ }
475
+ if (envelope.type === 'interactive') {
476
+ const route = slackActionRoute(envelope.payload as SlackInteraction)
477
+ if (!route) return
478
+ await handler?.({
479
+ chatId: route.chatId,
480
+ userId: route.userId,
481
+ ...(route.username ? { username: route.username } : {}),
482
+ text: '',
483
+ kind: route.kind,
484
+ addressed: true,
485
+ messageId: route.messageId,
486
+ ...(route.actionToken ? { actionToken: route.actionToken } : {}),
487
+ })
488
+ return
489
+ }
490
+ if (envelope.type === 'slash_commands') {
491
+ const payload = envelope.payload as {
492
+ channel_id?: string
493
+ channel_name?: string
494
+ user_id?: string
495
+ user_name?: string
496
+ command?: string
497
+ text?: string
498
+ trigger_id?: string
499
+ thread_ts?: string
500
+ } | undefined
501
+ const channel = payload?.channel_id
502
+ const userId = payload?.user_id
503
+ if (typeof channel !== 'string' || !CHANNEL_ID.test(channel) || typeof userId !== 'string' || !userId || userId === botUserId) return
504
+ const kind = slackChatKind(channel, payload?.channel_name)
505
+ const command = (payload?.command ?? '').trim().replace(/^\//, '')
506
+ const text = `/${command}${payload?.text ? ` ${payload.text}` : ''}`.trim()
507
+ const trigger = typeof payload?.trigger_id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(payload.trigger_id)
508
+ ? payload.trigger_id
509
+ : envelope.envelope_id || `${channel}:${Date.now()}`
510
+ // 必须先去重再发送线程根,网关的去重发生在这些副作用之后。
511
+ if (!firstSight(seenEvents, `slash:${trigger}`)) return
512
+ let threadTs = kind === 'group' && payload?.thread_ts && MESSAGE_TS.test(payload.thread_ts) ? payload.thread_ts : undefined
513
+ if (kind === 'group' && !threadTs) {
514
+ const opened = await postMessage(slackChatId(channel), text)
515
+ threadTs = opened.ts && MESSAGE_TS.test(opened.ts) ? opened.ts : undefined
516
+ if (!threadTs) return
517
+ }
518
+ if (kind === 'group' && threadTs) rememberThread(`${channel}~${threadTs}`)
519
+ await handler?.({
520
+ chatId: slackChatId(channel, threadTs),
521
+ userId,
522
+ ...(payload?.user_name ? { username: payload.user_name } : {}),
523
+ text,
524
+ kind,
525
+ addressed: true,
526
+ messageId: `slash:${trigger}`,
527
+ })
528
+ }
529
+ }
530
+
531
+ async function openSocket(): Promise<void> {
532
+ // apps.connections.open 用 App-Level Token,其余 Web API 调用用 Bot Token。
533
+ const opened = await api<{ url?: string }>('apps.connections.open', {}, { token: appToken, timeoutMs: 15_000 })
534
+ const target = slackSocketUrl(opened.url)
535
+ const current = createSocket(target)
536
+ socket = current
537
+ const currentGeneration = generation
538
+ await new Promise<void>((resolve, reject) => {
539
+ let settled = false
540
+ const finish = (error?: unknown) => {
541
+ if (settled) return
542
+ settled = true
543
+ clearTimeout(timer)
544
+ if (error) reject(error)
545
+ else resolve()
546
+ }
547
+ const timer = setTimeout(() => {
548
+ statusText = readyOnce ? '重连中' : '连接中'
549
+ finish(new Error('slack-socket-timeout'))
550
+ try { current.close(1000, 'timeout') } catch { /* 已经断开 */ }
551
+ }, config.connectTimeoutMs ?? 20_000)
552
+ current.addEventListener('message', (messageEvent) => {
553
+ if (stopped || currentGeneration !== generation) return
554
+ const raw = typeof messageEvent.data === 'string' ? messageEvent.data : ''
555
+ if (!raw) return
556
+ let envelope: SlackEnvelope
557
+ try { envelope = JSON.parse(raw) as SlackEnvelope } catch { log('[slack] 忽略无法解析的事件帧'); return }
558
+ if (envelope.type === 'hello') {
559
+ reconnectAttempt = 0
560
+ readyOnce = true
561
+ statusText = '长连接已建立'
562
+ finish()
563
+ return
564
+ }
565
+ if (envelope.type === 'disconnect') {
566
+ // refresh_requested 是 Slack 的正常轮换,重新连接即可;其余原因需要管理员处理。
567
+ const reason = typeof envelope.reason === 'string' ? envelope.reason : ''
568
+ if (reason === 'refresh_requested') {
569
+ try { current.close(1000, 'refresh') } catch { /* 已经断开 */ }
570
+ return
571
+ }
572
+ if (reason === 'link_disabled') {
573
+ haltReconnect = true
574
+ statusText = '连接失败,请查看本机日志'
575
+ log(`[slack] Socket Mode 已断开: ${reason}`)
576
+ clearTimeout(reconnectTimer)
577
+ try { current.close(1000, 'disconnect') } catch { /* 已经断开 */ }
578
+ return
579
+ }
580
+ statusText = '连接失败,请查看本机日志'
581
+ log(`[slack] Socket Mode 已断开: ${reason || 'unknown'}`)
582
+ try { current.close(1000, 'disconnect') } catch { /* 已经断开 */ }
583
+ return
584
+ }
585
+ // 事件必须在 3 秒内确认,且确认不能等业务处理完。
586
+ if (envelope.envelope_id) sendAck(envelope.envelope_id)
587
+ void acceptEnvelope(envelope).catch((error) => log(`[slack] 事件处理失败: ${errorMessage(error)}`))
588
+ })
589
+ current.addEventListener('close', () => {
590
+ if (currentGeneration !== generation) return
591
+ if (socket === current) socket = undefined
592
+ if (haltReconnect) {
593
+ statusText = '连接失败,请查看本机日志'
594
+ finish(new Error('slack-link-disabled'))
595
+ return
596
+ }
597
+ if (stopped) {
598
+ finish(Object.assign(new Error('Stopped'), { name: 'AbortError' }))
599
+ return
600
+ }
601
+ statusText = readyOnce ? '重连中' : '连接中'
602
+ finish(new Error('slack-socket-closed'))
603
+ if (!starting) scheduleReconnect()
604
+ })
605
+ current.addEventListener('error', () => {
606
+ if (currentGeneration === generation && !stopped) log('[slack] Socket Mode WebSocket 错误')
607
+ })
608
+ })
609
+ }
610
+
611
+ function scheduleReconnect(): void {
612
+ clearTimeout(reconnectTimer)
613
+ const delay = RECONNECT_DELAYS[Math.min(reconnectAttempt, RECONNECT_DELAYS.length - 1)]!
614
+ reconnectAttempt += 1
615
+ reconnectTimer = setTimeout(() => {
616
+ if (stopped || haltReconnect) return
617
+ void openSocket().catch((error) => {
618
+ if (stopped || fatalSlack(error)) return
619
+ log(`[slack] 重连失败: ${errorMessage(error)}`)
620
+ scheduleReconnect()
621
+ })
622
+ }, delay)
623
+ }
624
+
625
+ async function connectOnce(): Promise<void> {
626
+ await openSocket()
627
+ }
628
+
629
+ return {
630
+ id: 'slack',
631
+ label: 'Slack',
632
+ maxMessageLength: MESSAGE_LIMIT,
633
+ choiceLimits: { maxButtons: MAX_BUTTONS, maxTextLength: 3_000 },
634
+ async start() {
635
+ await this.stop()
636
+ stopped = false
637
+ starting = true
638
+ readyOnce = false
639
+ reconnectAttempt = 0
640
+ statusText = '连接中'
641
+ lifecycle = new AbortController()
642
+ seenEvents.clear()
643
+ try {
644
+ // 先按前缀拦一次:Slack 应用页面上那五个 App Credentials 都不是这里要填的东西,
645
+ // 直接在日志里说清楚,比让 auth.test 回一个 invalid_auth 有用。
646
+ if (!BOT_TOKEN_PREFIX.test(token)) throw credentialError(BOT_TOKEN_HINT)
647
+ if (!APP_TOKEN_PREFIX.test(appToken)) throw credentialError(APP_TOKEN_HINT)
648
+ let identity: { user_id?: string; bot_id?: string }
649
+ try {
650
+ identity = await api<{ user_id?: string; bot_id?: string }>('auth.test', {}, { timeoutMs: 15_000 })
651
+ } catch (error) {
652
+ throw fatalSlack(error) ? credentialError(BOT_TOKEN_HINT) : error
653
+ }
654
+ if (typeof identity.user_id !== 'string' || !identity.user_id) throw credentialError(APP_TOKEN_HINT)
655
+ restoreThreads(identity.user_id)
656
+ botUserId = identity.user_id
657
+ botId = typeof identity.bot_id === 'string' ? identity.bot_id : ''
658
+ await connectOnce()
659
+ starting = false
660
+ log(`[slack] Socket Mode 已连接${botId ? `(${botId})` : ''}`)
661
+ } catch (error) {
662
+ starting = false
663
+ // 令牌或授权范围有问题时不停在重连,直接把失败交给管理器展示。
664
+ if (!recoverableSlack(error)) {
665
+ statusText = '连接失败,请查看本机日志'
666
+ await this.stop()
667
+ throw error
668
+ }
669
+ statusText = '重连中'
670
+ log(`[slack] 启动时 Socket Mode 未就绪,将自动重连: ${errorMessage(error)}`)
671
+ scheduleReconnect()
672
+ } finally {
673
+ starting = false
674
+ }
675
+ },
676
+ async stop() {
677
+ stopped = true
678
+ haltReconnect = false
679
+ readyOnce = false
680
+ statusText = '已停止'
681
+ clearTimeout(reconnectTimer)
682
+ generation += 1
683
+ lifecycle.abort()
684
+ try { socket?.close(1000, 'stopped') } catch { /* 已经断开 */ }
685
+ socket = undefined
686
+ },
687
+ canDeliverDeferred() { return !stopped && statusText === '长连接已建立' },
688
+ async send(chatId, text) {
689
+ const rendered = prepareSlackText(text)
690
+ const parts = codePoints(rendered).length <= MESSAGE_LIMIT ? [rendered] : splitText(rendered, MESSAGE_LIMIT)
691
+ for (const part of parts) {
692
+ if (part.trim() === '') continue
693
+ await postMessage(chatId, part)
694
+ }
695
+ },
696
+ async sendFile(chatId, file, signal) {
697
+ const route = parseSlackChatId(chatId)
698
+ const name = file.name.replace(/\\/g, '/').split('/').pop()?.replace(/[\x00-\x1f]/g, '').slice(0, 200) || 'file'
699
+ const abort = AbortSignal.any([...(signal ? [signal] : []), lifecycle.signal, AbortSignal.timeout(120_000)])
700
+ const ticket = await api<{ upload_url?: string; file_id?: string }>('files.getUploadURLExternal', {
701
+ filename: name,
702
+ length: file.data.byteLength,
703
+ }, { signal: abort })
704
+ const uploadUrl = typeof ticket.upload_url === 'string' ? ticket.upload_url : ''
705
+ const fileId = typeof ticket.file_id === 'string' ? ticket.file_id : ''
706
+ if (!uploadUrl || !fileId) throw Object.assign(new Error('slack-upload-ticket'), { rejected: true })
707
+ const target = new URL(uploadUrl)
708
+ if (target.protocol !== 'https:' || !target.hostname.toLowerCase().endsWith('.slack.com')) throw Object.assign(new Error('slack-upload-url'), { rejected: true })
709
+ const upload = await fetchImpl(uploadUrl, {
710
+ method: 'POST',
711
+ body: fileForm({ name, data: file.data }, 'file'),
712
+ signal: abort,
713
+ redirect: 'error',
714
+ })
715
+ if (!upload.ok) {
716
+ await upload.body?.cancel().catch(() => undefined)
717
+ throw Object.assign(new Error(`slack-upload-http-${upload.status}`), { status: upload.status })
718
+ }
719
+ await upload.body?.cancel().catch(() => undefined)
720
+ await api('files.completeUploadExternal', {
721
+ files: [{ id: fileId, title: name }],
722
+ channel_id: route.channel,
723
+ ...(route.threadTs ? { thread_ts: route.threadTs } : {}),
724
+ }, { signal: abort })
725
+ },
726
+ async sendChoices(message, text, buttons) {
727
+ const rendered = prepareSlackText(text)
728
+ if (!buttons.length || buttons.length > MAX_BUTTONS || codePoints(rendered).length > MESSAGE_LIMIT) {
729
+ throw choiceSendError(Object.assign(new Error('slack-choice-limit'), { status: 400, rejected: true }))
730
+ }
731
+ try {
732
+ const route = parseSlackChatId(message.chatId)
733
+ const sent = await postMessage(message.chatId, rendered, undefined, [...sectionBlocks(rendered), ...actionBlocks(buttons)])
734
+ if (!sent.ts) return
735
+ return {
736
+ close: async (status: string) => {
737
+ // 卡片只能改原消息:去掉按钮块,避免旧按钮被重复点击。
738
+ const body = `${rendered}\n\n${status}`
739
+ await api('chat.update', {
740
+ channel: route.channel,
741
+ ts: sent.ts,
742
+ text: body,
743
+ blocks: sectionBlocks(body),
744
+ })
745
+ },
746
+ }
747
+ } catch (error) {
748
+ throw choiceSendError(error)
749
+ }
750
+ },
751
+ async addStatusReaction(message, state, _label, signal) {
752
+ if (!message.messageId || state === 'cancelled' || message.messageId.startsWith('interaction:') || message.messageId.startsWith('slash:')) return
753
+ if (!MESSAGE_TS.test(message.messageId)) return
754
+ const name = state === 'success' || state === 'ended' ? 'white_check_mark'
755
+ : state === 'error' ? 'x' : state === 'waiting' ? 'thinking_face' : 'eyes'
756
+ await api('reactions.add', { channel: parseSlackChatId(message.chatId).channel, timestamp: message.messageId, name }, { signal })
757
+ return name
758
+ },
759
+ async removeStatusReaction(message, reaction, signal) {
760
+ if (!message.messageId || !reaction || message.messageId.startsWith('interaction:') || message.messageId.startsWith('slash:')) return
761
+ if (!MESSAGE_TS.test(message.messageId)) return
762
+ await api('reactions.remove', { channel: parseSlackChatId(message.chatId).channel, timestamp: message.messageId, name: reaction }, { signal })
763
+ },
764
+ async beginReply(chatId): Promise<ReplyStream> {
765
+ const route = parseSlackChatId(chatId)
766
+ const first = await postMessage(chatId, '…')
767
+ let last = '…'
768
+ let timer: ReturnType<typeof setTimeout> | undefined
769
+ let pending: string | undefined
770
+ let inflight = Promise.resolve()
771
+
772
+ const flush = async (text: string, allowSend: boolean) => {
773
+ const next = clip(text, MESSAGE_LIMIT) || '…'
774
+ if (next === last) return
775
+ try {
776
+ if (!first.ts) throw Object.assign(new Error('slack-stream-missing-ts'), { rejected: true })
777
+ await api('chat.update', { channel: route.channel, ts: first.ts, text: next })
778
+ last = next
779
+ } catch (error) {
780
+ if (!allowSend) return
781
+ // 只有平台明确拒绝更新时才能补发;响应丢失时原消息可能已经更新。
782
+ if (choiceSendError(error).reason === 'delivery-unknown') throw error
783
+ await postMessage(chatId, next)
784
+ last = next
785
+ }
786
+ }
787
+
788
+ return {
789
+ async update(text) {
790
+ pending = text
791
+ if (timer) return
792
+ timer = setTimeout(() => {
793
+ timer = undefined
794
+ const next = pending
795
+ pending = undefined
796
+ if (next !== undefined) inflight = inflight.then(() => flush(prepareSlackText(next), false))
797
+ }, FLUSH_INTERVAL_MS)
798
+ },
799
+ async finish(text) {
800
+ if (timer) clearTimeout(timer)
801
+ timer = undefined
802
+ await inflight.catch(() => undefined)
803
+ const parts = splitText(prepareSlackText(text || pending || last), MESSAGE_LIMIT)
804
+ await flush(parts[0] || '…', true)
805
+ for (const part of parts.slice(1)) {
806
+ if (part.trim() === '') continue
807
+ await postMessage(chatId, part)
808
+ }
809
+ },
810
+ }
811
+ },
812
+ setMessageHandler(next) { handler = next },
813
+ async diagnose(signal) {
814
+ const identity = await probe('bot', signal, async () => {
815
+ const data = await diagnosticJson(`${apiBase}auth.test`, signal, {}, { authorization: `Bearer ${token}` })
816
+ if (data.ok === false) throw new DiagnosticError(AUTH_ERRORS.has(String(data.error)) ? 'auth' : 'rejected')
817
+ requireDiagnostic(data.ok === true && typeof data.user_id === 'string' && data.user_id)
818
+ })
819
+ if (identity.status !== 'passed') return [identity]
820
+ if (!appToken || !readyOnce) return [identity]
821
+ // 只读现有连接状态,不新建连接,也不发测试消息。
822
+ return [identity, await probe('gateway', signal, async () => {
823
+ if (stopped || statusText !== '长连接已建立') throw new DiagnosticError('not-connected')
824
+ })]
825
+ },
826
+ status() { return statusText },
827
+ }
828
+ }