@michengai/dsh-im-connect 0.1.19 → 0.1.21

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 (67) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/SECURITY.md +1 -1
  4. package/lib/channels/dingtalk-card.d.ts.map +1 -1
  5. package/lib/channels/dingtalk-card.js +3 -0
  6. package/lib/channels/dingtalk-card.js.map +1 -1
  7. package/lib/channels/dingtalk.d.ts.map +1 -1
  8. package/lib/channels/dingtalk.js +6 -1
  9. package/lib/channels/dingtalk.js.map +1 -1
  10. package/lib/channels/feishu.d.ts +9 -0
  11. package/lib/channels/feishu.d.ts.map +1 -1
  12. package/lib/channels/feishu.js +23 -6
  13. package/lib/channels/feishu.js.map +1 -1
  14. package/lib/channels/qq.d.ts.map +1 -1
  15. package/lib/channels/qq.js +17 -1
  16. package/lib/channels/qq.js.map +1 -1
  17. package/lib/channels/telegram.d.ts.map +1 -1
  18. package/lib/channels/telegram.js +17 -4
  19. package/lib/channels/telegram.js.map +1 -1
  20. package/lib/channels/wecom.d.ts +7 -1
  21. package/lib/channels/wecom.d.ts.map +1 -1
  22. package/lib/channels/wecom.js +44 -11
  23. package/lib/channels/wecom.js.map +1 -1
  24. package/lib/channels/weixin.d.ts +3 -0
  25. package/lib/channels/weixin.d.ts.map +1 -1
  26. package/lib/channels/weixin.js +68 -15
  27. package/lib/channels/weixin.js.map +1 -1
  28. package/lib/engine/abort.d.ts +4 -0
  29. package/lib/engine/abort.d.ts.map +1 -0
  30. package/lib/engine/abort.js +26 -0
  31. package/lib/engine/abort.js.map +1 -0
  32. package/lib/engine/atomic-file.d.ts +5 -0
  33. package/lib/engine/atomic-file.d.ts.map +1 -0
  34. package/lib/engine/atomic-file.js +46 -0
  35. package/lib/engine/atomic-file.js.map +1 -0
  36. package/lib/engine/json-state.d.ts.map +1 -1
  37. package/lib/engine/json-state.js +7 -5
  38. package/lib/engine/json-state.js.map +1 -1
  39. package/lib/engine/secure-file.d.ts.map +1 -1
  40. package/lib/engine/secure-file.js +2 -12
  41. package/lib/engine/secure-file.js.map +1 -1
  42. package/lib/engine/seen-store.d.ts.map +1 -1
  43. package/lib/engine/seen-store.js +4 -4
  44. package/lib/engine/seen-store.js.map +1 -1
  45. package/lib/engine/session-store.d.ts.map +1 -1
  46. package/lib/engine/session-store.js +7 -5
  47. package/lib/engine/session-store.js.map +1 -1
  48. package/lib/manager.d.ts +7 -0
  49. package/lib/manager.d.ts.map +1 -1
  50. package/lib/manager.js +50 -42
  51. package/lib/manager.js.map +1 -1
  52. package/package.json +1 -1
  53. package/src/channels/dingtalk-card.ts +195 -192
  54. package/src/channels/dingtalk.ts +144 -140
  55. package/src/channels/feishu.ts +92 -66
  56. package/src/channels/qq.ts +303 -288
  57. package/src/channels/telegram.ts +170 -158
  58. package/src/channels/wecom.ts +209 -177
  59. package/src/channels/weixin.ts +158 -112
  60. package/src/engine/abort.ts +25 -0
  61. package/src/engine/access.ts +34 -34
  62. package/src/engine/atomic-file.ts +36 -0
  63. package/src/engine/json-state.ts +16 -15
  64. package/src/engine/secure-file.ts +7 -13
  65. package/src/engine/seen-store.ts +39 -39
  66. package/src/engine/session-store.ts +40 -39
  67. package/src/manager.ts +346 -321
@@ -1,175 +1,187 @@
1
1
  import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
2
2
  import { JsonStateFile } from '../engine/json-state.js'
3
-
4
- export interface TelegramConfig {
5
- token?: string
6
- stateDir?: string
7
- }
8
-
9
- interface TgUpdate {
10
- update_id: number
11
- message?: {
12
- message_id: number
13
- chat: { id: number; type: string }
14
- from?: { id: number; username?: string; first_name?: string; is_bot?: boolean }
15
- text?: string
16
- caption?: string
17
- entities?: Array<{ type: string; offset: number; length: number }>
18
- reply_to_message?: { from?: { id: number } }
19
- }
20
- }
21
-
22
- const API = 'https://api.telegram.org'
23
-
24
- export function createTelegramChannel(config: TelegramConfig, log: (line: string) => void): ChannelAdapter | undefined {
25
- const token = config.token?.trim()
26
- if (!token) return undefined
27
- const cursorFile = new JsonStateFile(config.stateDir ? `${config.stateDir.replace(/[\\/]$/, '')}/cursor.json` : '', { offset: 0 })
28
- const persist = Boolean(config.stateDir)
29
-
30
- let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
31
- let offset = persist ? cursorFile.read().offset : 0
32
- let stopped = false
33
- let lastError = ''
3
+ import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
4
+
5
+ export interface TelegramConfig {
6
+ token?: string
7
+ stateDir?: string
8
+ }
9
+
10
+ interface TgUpdate {
11
+ update_id: number
12
+ message?: {
13
+ message_id: number
14
+ chat: { id: number; type: string }
15
+ from?: { id: number; username?: string; first_name?: string; is_bot?: boolean }
16
+ text?: string
17
+ caption?: string
18
+ entities?: Array<{ type: string; offset: number; length: number }>
19
+ reply_to_message?: { from?: { id: number } }
20
+ }
21
+ }
22
+
23
+ const API = 'https://api.telegram.org'
24
+
25
+ export function createTelegramChannel(config: TelegramConfig, log: (line: string) => void): ChannelAdapter | undefined {
26
+ const token = config.token?.trim()
27
+ if (!token) return undefined
28
+ const cursorFile = new JsonStateFile(config.stateDir ? `${config.stateDir.replace(/[\\/]$/, '')}/cursor.json` : '', { offset: 0 })
29
+ const persist = Boolean(config.stateDir)
30
+
31
+ let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
32
+ let offset = persist ? cursorFile.read().offset : 0
33
+ let stopped = false
34
+ let lastError = ''
34
35
  let botId = ''
35
36
  let username = ''
37
+ let lifecycle: AbortController | undefined
38
+ let pollTask: Promise<void> | undefined
36
39
 
37
- async function api<T>(method: string, body: Record<string, unknown>): Promise<T> {
40
+ async function api<T>(method: string, body: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
38
41
  const res = await fetch(`${API}/bot${token}/${method}`, {
39
- method: 'POST',
42
+ method: 'POST',
40
43
  headers: { 'content-type': 'application/json' },
41
44
  body: JSON.stringify(body),
42
- })
43
- const data = (await res.json()) as { ok: boolean; description?: string; error_code?: number; result: T }
44
- if (!data.ok) {
45
- const error = new Error(`telegram ${method}: ${data.description ?? 'unknown'}`)
46
- if (data.error_code === 401) (error as Error & { code?: string }).code = 'telegram-401'
47
- throw error
48
- }
49
- return data.result
50
- }
51
-
52
- function mentioned(message: NonNullable<TgUpdate['message']>): boolean {
53
- if (!username || !message.text || !Array.isArray(message.entities)) return false
54
- return message.entities.some((entity) => {
55
- if (entity.type !== 'mention') return false
56
- return message.text!.slice(entity.offset, entity.offset + entity.length).toLowerCase() === `@${username.toLowerCase()}`
57
- })
58
- }
59
-
60
- async function pollLoop(): Promise<void> {
61
- while (!stopped) {
62
- try {
45
+ signal: timeoutSignal(timeoutMs, lifecycle?.signal),
46
+ })
47
+ const data = (await res.json()) as { ok: boolean; description?: string; error_code?: number; result: T }
48
+ if (!data.ok) {
49
+ const error = new Error(`telegram ${method}: ${data.description ?? 'unknown'}`)
50
+ if (data.error_code === 401) (error as Error & { code?: string }).code = 'telegram-401'
51
+ throw error
52
+ }
53
+ return data.result
54
+ }
55
+
56
+ function mentioned(message: NonNullable<TgUpdate['message']>): boolean {
57
+ if (!username || !message.text || !Array.isArray(message.entities)) return false
58
+ return message.entities.some((entity) => {
59
+ if (entity.type !== 'mention') return false
60
+ return message.text!.slice(entity.offset, entity.offset + entity.length).toLowerCase() === `@${username.toLowerCase()}`
61
+ })
62
+ }
63
+
64
+ async function pollLoop(): Promise<void> {
65
+ while (!stopped) {
66
+ try {
63
67
  const updates = await api<TgUpdate[]>('getUpdates', {
64
- offset,
65
- timeout: 25,
66
- allowed_updates: ['message'],
67
- })
68
- lastError = ''
69
- for (const update of updates) {
70
- // Telegram offset 是 at-most-once 取舍:先确认游标可避免崩溃重启后重复驱动 agent,代价是极端情况下丢一条未完成消息。
71
- offset = update.update_id + 1
72
- if (persist) cursorFile.write({ offset })
73
- const message = update.message
74
- if (!message || message.from?.is_bot) continue
75
- if (!['private', 'group', 'supergroup'].includes(message.chat.type)) continue
76
- const direct = message.chat.type === 'private'
77
- const addressed = direct
78
- || String(message.reply_to_message?.from?.id ?? '') === botId
79
- || mentioned(message)
80
- let text = message.text ?? message.caption ?? ''
81
- if (username) text = text.replace(new RegExp(`@${username}\\b`, 'ig'), '').trim()
82
- void handler?.({
83
- chatId: String(message.chat.id),
84
- userId: message.from ? String(message.from.id) : undefined,
85
- username: message.from?.username ?? message.from?.first_name,
86
- text,
87
- kind: direct ? 'dm' : 'group',
88
- addressed,
89
- messageId: String(update.update_id),
90
- })
91
- }
92
- } catch (error) {
93
- lastError = error instanceof Error ? error.message : String(error)
94
- log(`[telegram] 轮询错误: ${lastError}`)
95
- if (stopped) break
96
- await new Promise((resolve) => setTimeout(resolve, 3000))
97
- }
98
- }
99
- }
100
-
101
- return {
102
- id: 'telegram',
103
- label: 'Telegram',
104
- maxMessageLength: 4000,
68
+ offset,
69
+ timeout: 25,
70
+ allowed_updates: ['message'],
71
+ }, 35_000)
72
+ lastError = ''
73
+ for (const update of updates) {
74
+ // Telegram offset 是 at-most-once 取舍:先确认游标可避免崩溃重启后重复驱动 agent,代价是极端情况下丢一条未完成消息。
75
+ offset = update.update_id + 1
76
+ if (persist) cursorFile.write({ offset })
77
+ const message = update.message
78
+ if (!message || message.from?.is_bot) continue
79
+ if (!['private', 'group', 'supergroup'].includes(message.chat.type)) continue
80
+ const direct = message.chat.type === 'private'
81
+ const addressed = direct
82
+ || String(message.reply_to_message?.from?.id ?? '') === botId
83
+ || 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
+ })
95
+ }
96
+ } catch (error) {
97
+ lastError = error instanceof Error ? error.message : String(error)
98
+ log(`[telegram] 轮询错误: ${lastError}`)
99
+ if (stopped) break
100
+ await sleepWithSignal(3000, lifecycle?.signal).catch(() => undefined)
101
+ }
102
+ }
103
+ }
104
+
105
+ return {
106
+ id: 'telegram',
107
+ label: 'Telegram',
108
+ maxMessageLength: 4000,
105
109
  async start() {
110
+ lifecycle?.abort()
111
+ lifecycle = new AbortController()
106
112
  stopped = false
107
- const me = await api<{ id: number; username?: string; is_bot: boolean }>('getMe', {})
108
- botId = String(me.id)
109
- username = me.username ?? ''
110
- const hook = await api<{ url?: string }>('getWebhookInfo', {})
113
+ const me = await api<{ id: number; username?: string; is_bot: boolean }>('getMe', {})
114
+ botId = String(me.id)
115
+ username = me.username ?? ''
116
+ const hook = await api<{ url?: string }>('getWebhookInfo', {})
111
117
  if (hook.url) throw Object.assign(new Error('该 Telegram 机器人已配置 Webhook,请先在原服务中移除。'), { code: 'webhook-configured' })
112
118
  log('[telegram] 开始长轮询')
113
- void pollLoop()
119
+ pollTask = pollLoop().catch((error) => {
120
+ if (!stopped) log(`[telegram] 轮询循环退出: ${error instanceof Error ? error.message : String(error)}`)
121
+ })
114
122
  },
115
123
  async stop() {
116
124
  stopped = true
125
+ lifecycle?.abort()
126
+ await pollTask?.catch(() => undefined)
127
+ pollTask = undefined
128
+ lifecycle = undefined
117
129
  if (persist) cursorFile.write({ offset })
118
- },
119
- async send(chatId, text) {
120
- await api('sendMessage', { chat_id: Number(chatId), text })
121
- },
122
- async sendAction(chatId) {
123
- await api('sendChatAction', { chat_id: Number(chatId), action: 'typing' }).catch(() => undefined)
124
- },
125
- async beginReply(chatId): Promise<ReplyStream> {
126
- const first = await api<{ message_id: number }>('sendMessage', { chat_id: Number(chatId), text: '…' })
127
- let last = '…'
128
- let timer: ReturnType<typeof setTimeout> | undefined
129
- let pending: string | undefined
130
- let inflight = Promise.resolve()
131
-
132
- const flush = async (text: string, allowSend: boolean) => {
133
- const next = text.slice(0, 4000) || '…'
134
- if (next === last) return
135
- // last 只在发送成功后更新:失败时保留旧值,finish 才能靠 sendMessage 兜底送出全文
136
- try {
137
- await api('editMessageText', { chat_id: Number(chatId), message_id: first.message_id, text: next })
138
- last = next
139
- } catch (error) {
140
- const detail = error instanceof Error ? error.message : String(error)
141
- if (detail.includes('message is not modified')) {
142
- last = next
143
- return
144
- }
145
- if (!allowSend) return
146
- await api('sendMessage', { chat_id: Number(chatId), text: next })
147
- last = next
148
- }
149
- }
150
-
151
- return {
152
- async update(text) {
153
- pending = text
154
- if (timer) return
155
- timer = setTimeout(() => {
156
- timer = undefined
157
- const next = pending
158
- pending = undefined
159
- if (next !== undefined) inflight = inflight.then(() => flush(next, false))
160
- }, 400)
161
- },
162
- async finish(text) {
163
- if (timer) {
164
- clearTimeout(timer)
165
- timer = undefined
166
- }
167
- await inflight.catch(() => undefined)
168
- await flush(text || pending || last, true)
169
- },
170
- }
171
- },
172
- setMessageHandler(h) { handler = h },
173
- status() { return stopped ? '已停止' : lastError ? '轮询异常(详情见本机日志)' : '轮询中' },
174
- }
175
- }
130
+ },
131
+ async send(chatId, text) {
132
+ await api('sendMessage', { chat_id: Number(chatId), text })
133
+ },
134
+ async sendAction(chatId) {
135
+ await api('sendChatAction', { chat_id: Number(chatId), action: 'typing' }).catch(() => undefined)
136
+ },
137
+ async beginReply(chatId): Promise<ReplyStream> {
138
+ const first = await api<{ message_id: number }>('sendMessage', { chat_id: Number(chatId), text: '…' })
139
+ let last = '…'
140
+ let timer: ReturnType<typeof setTimeout> | undefined
141
+ let pending: string | undefined
142
+ let inflight = Promise.resolve()
143
+
144
+ const flush = async (text: string, allowSend: boolean) => {
145
+ const next = text.slice(0, 4000) || '…'
146
+ if (next === last) return
147
+ // last 只在发送成功后更新:失败时保留旧值,finish 才能靠 sendMessage 兜底送出全文
148
+ try {
149
+ await api('editMessageText', { chat_id: Number(chatId), message_id: first.message_id, text: next })
150
+ last = next
151
+ } catch (error) {
152
+ const detail = error instanceof Error ? error.message : String(error)
153
+ if (detail.includes('message is not modified')) {
154
+ last = next
155
+ return
156
+ }
157
+ if (!allowSend) return
158
+ await api('sendMessage', { chat_id: Number(chatId), text: next })
159
+ last = next
160
+ }
161
+ }
162
+
163
+ return {
164
+ async update(text) {
165
+ pending = text
166
+ if (timer) return
167
+ timer = setTimeout(() => {
168
+ timer = undefined
169
+ const next = pending
170
+ pending = undefined
171
+ if (next !== undefined) inflight = inflight.then(() => flush(next, false))
172
+ }, 400)
173
+ },
174
+ async finish(text) {
175
+ if (timer) {
176
+ clearTimeout(timer)
177
+ timer = undefined
178
+ }
179
+ await inflight.catch(() => undefined)
180
+ await flush(text || pending || last, true)
181
+ },
182
+ }
183
+ },
184
+ setMessageHandler(h) { handler = h },
185
+ status() { return stopped ? '已停止' : lastError ? '轮询异常(详情见本机日志)' : '轮询中' },
186
+ }
187
+ }