@michengai/dsh-im-connect 0.1.0

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 (162) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +39 -0
  3. package/client.js +1479 -0
  4. package/cordis.patch.yml +4 -0
  5. package/lib/channels/dingtalk-card.d.ts +24 -0
  6. package/lib/channels/dingtalk-card.d.ts.map +1 -0
  7. package/lib/channels/dingtalk-card.js +182 -0
  8. package/lib/channels/dingtalk-card.js.map +1 -0
  9. package/lib/channels/dingtalk.d.ts +7 -0
  10. package/lib/channels/dingtalk.d.ts.map +1 -0
  11. package/lib/channels/dingtalk.js +107 -0
  12. package/lib/channels/dingtalk.js.map +1 -0
  13. package/lib/channels/factory.d.ts +4 -0
  14. package/lib/channels/factory.d.ts.map +1 -0
  15. package/lib/channels/factory.js +24 -0
  16. package/lib/channels/factory.js.map +1 -0
  17. package/lib/channels/feishu.d.ts +8 -0
  18. package/lib/channels/feishu.d.ts.map +1 -0
  19. package/lib/channels/feishu.js +73 -0
  20. package/lib/channels/feishu.js.map +1 -0
  21. package/lib/channels/meta.d.ts +20 -0
  22. package/lib/channels/meta.d.ts.map +1 -0
  23. package/lib/channels/meta.js +69 -0
  24. package/lib/channels/meta.js.map +1 -0
  25. package/lib/channels/qr/dingtalk.d.ts +12 -0
  26. package/lib/channels/qr/dingtalk.d.ts.map +1 -0
  27. package/lib/channels/qr/dingtalk.js +69 -0
  28. package/lib/channels/qr/dingtalk.js.map +1 -0
  29. package/lib/channels/qr/feishu.d.ts +14 -0
  30. package/lib/channels/qr/feishu.d.ts.map +1 -0
  31. package/lib/channels/qr/feishu.js +87 -0
  32. package/lib/channels/qr/feishu.js.map +1 -0
  33. package/lib/channels/qr/hub.d.ts +22 -0
  34. package/lib/channels/qr/hub.d.ts.map +1 -0
  35. package/lib/channels/qr/hub.js +193 -0
  36. package/lib/channels/qr/hub.js.map +1 -0
  37. package/lib/channels/qr/render.d.ts +3 -0
  38. package/lib/channels/qr/render.d.ts.map +1 -0
  39. package/lib/channels/qr/render.js +9 -0
  40. package/lib/channels/qr/render.js.map +1 -0
  41. package/lib/channels/qr/shared.d.ts +39 -0
  42. package/lib/channels/qr/shared.d.ts.map +1 -0
  43. package/lib/channels/qr/shared.js +51 -0
  44. package/lib/channels/qr/shared.js.map +1 -0
  45. package/lib/channels/qr/wecom.d.ts +10 -0
  46. package/lib/channels/qr/wecom.d.ts.map +1 -0
  47. package/lib/channels/qr/wecom.js +81 -0
  48. package/lib/channels/qr/wecom.js.map +1 -0
  49. package/lib/channels/qr/weixin.d.ts +10 -0
  50. package/lib/channels/qr/weixin.d.ts.map +1 -0
  51. package/lib/channels/qr/weixin.js +77 -0
  52. package/lib/channels/qr/weixin.js.map +1 -0
  53. package/lib/channels/telegram.d.ts +7 -0
  54. package/lib/channels/telegram.d.ts.map +1 -0
  55. package/lib/channels/telegram.js +133 -0
  56. package/lib/channels/telegram.js.map +1 -0
  57. package/lib/channels/wecom.d.ts +28 -0
  58. package/lib/channels/wecom.d.ts.map +1 -0
  59. package/lib/channels/wecom.js +168 -0
  60. package/lib/channels/wecom.js.map +1 -0
  61. package/lib/channels/weixin.d.ts +41 -0
  62. package/lib/channels/weixin.d.ts.map +1 -0
  63. package/lib/channels/weixin.js +678 -0
  64. package/lib/channels/weixin.js.map +1 -0
  65. package/lib/client.js +1479 -0
  66. package/lib/engine/access.d.ts +11 -0
  67. package/lib/engine/access.d.ts.map +1 -0
  68. package/lib/engine/access.js +11 -0
  69. package/lib/engine/access.js.map +1 -0
  70. package/lib/engine/agent-options.d.ts +25 -0
  71. package/lib/engine/agent-options.d.ts.map +1 -0
  72. package/lib/engine/agent-options.js +19 -0
  73. package/lib/engine/agent-options.js.map +1 -0
  74. package/lib/engine/approval.d.ts +9 -0
  75. package/lib/engine/approval.d.ts.map +1 -0
  76. package/lib/engine/approval.js +38 -0
  77. package/lib/engine/approval.js.map +1 -0
  78. package/lib/engine/assistant-settings.d.ts +17 -0
  79. package/lib/engine/assistant-settings.d.ts.map +1 -0
  80. package/lib/engine/assistant-settings.js +35 -0
  81. package/lib/engine/assistant-settings.js.map +1 -0
  82. package/lib/engine/credentials.d.ts +17 -0
  83. package/lib/engine/credentials.d.ts.map +1 -0
  84. package/lib/engine/credentials.js +51 -0
  85. package/lib/engine/credentials.js.map +1 -0
  86. package/lib/engine/gateway.d.ts +46 -0
  87. package/lib/engine/gateway.d.ts.map +1 -0
  88. package/lib/engine/gateway.js +333 -0
  89. package/lib/engine/gateway.js.map +1 -0
  90. package/lib/engine/json-state.d.ts +8 -0
  91. package/lib/engine/json-state.d.ts.map +1 -0
  92. package/lib/engine/json-state.js +24 -0
  93. package/lib/engine/json-state.js.map +1 -0
  94. package/lib/engine/merge.d.ts +21 -0
  95. package/lib/engine/merge.d.ts.map +1 -0
  96. package/lib/engine/merge.js +55 -0
  97. package/lib/engine/merge.js.map +1 -0
  98. package/lib/engine/router.d.ts +88 -0
  99. package/lib/engine/router.d.ts.map +1 -0
  100. package/lib/engine/router.js +309 -0
  101. package/lib/engine/router.js.map +1 -0
  102. package/lib/engine/seen-store.d.ts +12 -0
  103. package/lib/engine/seen-store.d.ts.map +1 -0
  104. package/lib/engine/seen-store.js +38 -0
  105. package/lib/engine/seen-store.js.map +1 -0
  106. package/lib/engine/session-id.d.ts +30 -0
  107. package/lib/engine/session-id.d.ts.map +1 -0
  108. package/lib/engine/session-id.js +53 -0
  109. package/lib/engine/session-id.js.map +1 -0
  110. package/lib/engine/session-store.d.ts +13 -0
  111. package/lib/engine/session-store.d.ts.map +1 -0
  112. package/lib/engine/session-store.js +38 -0
  113. package/lib/engine/session-store.js.map +1 -0
  114. package/lib/engine/split.d.ts +2 -0
  115. package/lib/engine/split.d.ts.map +1 -0
  116. package/lib/engine/split.js +41 -0
  117. package/lib/engine/split.js.map +1 -0
  118. package/lib/engine/types.d.ts +52 -0
  119. package/lib/engine/types.d.ts.map +1 -0
  120. package/lib/engine/types.js +2 -0
  121. package/lib/engine/types.js.map +1 -0
  122. package/lib/index.d.ts +22 -0
  123. package/lib/index.d.ts.map +1 -0
  124. package/lib/index.js +53 -0
  125. package/lib/index.js.map +1 -0
  126. package/lib/manager.d.ts +103 -0
  127. package/lib/manager.d.ts.map +1 -0
  128. package/lib/manager.js +543 -0
  129. package/lib/manager.js.map +1 -0
  130. package/package.json +63 -0
  131. package/src/channels/dingtalk-card.ts +191 -0
  132. package/src/channels/dingtalk.ts +113 -0
  133. package/src/channels/factory.ts +32 -0
  134. package/src/channels/feishu.ts +77 -0
  135. package/src/channels/meta.ts +89 -0
  136. package/src/channels/qr/dingtalk.ts +71 -0
  137. package/src/channels/qr/feishu.ts +90 -0
  138. package/src/channels/qr/hub.ts +206 -0
  139. package/src/channels/qr/render.ts +7 -0
  140. package/src/channels/qr/shared.ts +80 -0
  141. package/src/channels/qr/wecom.ts +78 -0
  142. package/src/channels/qr/weixin.ts +78 -0
  143. package/src/channels/telegram.ts +145 -0
  144. package/src/channels/wecom.ts +182 -0
  145. package/src/channels/weixin.ts +712 -0
  146. package/src/engine/access.ts +17 -0
  147. package/src/engine/agent-options.ts +24 -0
  148. package/src/engine/approval.ts +45 -0
  149. package/src/engine/assistant-settings.ts +41 -0
  150. package/src/engine/credentials.ts +64 -0
  151. package/src/engine/gateway.ts +330 -0
  152. package/src/engine/json-state.ts +20 -0
  153. package/src/engine/merge.ts +60 -0
  154. package/src/engine/router.ts +333 -0
  155. package/src/engine/seen-store.ts +36 -0
  156. package/src/engine/session-id.ts +65 -0
  157. package/src/engine/session-store.ts +45 -0
  158. package/src/engine/split.ts +29 -0
  159. package/src/engine/types.ts +55 -0
  160. package/src/index.ts +81 -0
  161. package/src/manager.ts +571 -0
  162. package/src/optional-modules.d.ts +13 -0
@@ -0,0 +1,191 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { ReplyStream } from '../engine/types.js'
3
+
4
+ const API = 'https://api.dingtalk.com/'
5
+ const TEMPLATE_ID = '02fcf2f4-5e02-4a85-b672-46d1f715543e.schema'
6
+ const UPDATE_INTERVAL_MS = 500
7
+
8
+ export type CardTarget =
9
+ | { type: 'user'; userId: string }
10
+ | { type: 'group'; openConversationId: string }
11
+
12
+ export function normalizeDingtalkCardMarkdown(value: string): string {
13
+ const text = value.replace(/\r\n?/g, '\n')
14
+ const lines = text.split('\n')
15
+ let inCode = false
16
+ return lines.map((line, index) => {
17
+ const fenced = /^\s{0,3}```/.test(line)
18
+ const wasInCode = inCode
19
+ if (fenced) inCode = !inCode
20
+ if (index === lines.length - 1) return line
21
+ if (wasInCode || fenced || inCode || !line || !lines[index + 1]) return `${line}\n`
22
+ if (/^\s{0,3}(?:[-*+] |\d+[.)] |#{1,6} |\||> )/.test(lines[index + 1] ?? '')) return `${line}\n`
23
+ return `${line}<br>`
24
+ }).join('')
25
+ }
26
+
27
+ function cardData(text: string, flowStatus: string) {
28
+ return {
29
+ cardParamMap: {
30
+ flowStatus,
31
+ msgContent: normalizeDingtalkCardMarkdown(text),
32
+ staticMsgContent: '',
33
+ sys_full_json_obj: JSON.stringify({ order: ['msgContent'] }),
34
+ config: JSON.stringify({ autoLayout: true }),
35
+ },
36
+ }
37
+ }
38
+
39
+ function deliverBody(cardInstanceId: string, target: CardTarget, robotCode: string) {
40
+ if (target.type === 'group') {
41
+ return {
42
+ outTrackId: cardInstanceId,
43
+ userIdType: 1,
44
+ openSpaceId: `dtv1.card//IM_GROUP.${target.openConversationId}`,
45
+ imGroupOpenDeliverModel: { robotCode },
46
+ }
47
+ }
48
+ return {
49
+ outTrackId: cardInstanceId,
50
+ userIdType: 1,
51
+ openSpaceId: `dtv1.card//IM_ROBOT.${target.userId}`,
52
+ imRobotOpenDeliverModel: {
53
+ spaceType: 'IM_ROBOT',
54
+ robotCode,
55
+ extension: { dynamicSummary: 'true' },
56
+ },
57
+ }
58
+ }
59
+
60
+ export class DingtalkCardClient {
61
+ private token = ''
62
+ private tokenExpiresAt = 0
63
+
64
+ constructor(
65
+ private readonly clientId: string,
66
+ private readonly clientSecret: string,
67
+ ) {}
68
+
69
+ async create(target: CardTarget, initialText: string): Promise<string> {
70
+ const token = await this.accessToken()
71
+ const cardInstanceId = `imc_${randomUUID()}`
72
+ const headers = { 'x-acs-dingtalk-access-token': token }
73
+ await this.request('v1.0/card/instances', {
74
+ cardTemplateId: TEMPLATE_ID,
75
+ outTrackId: cardInstanceId,
76
+ cardData: { cardParamMap: { config: JSON.stringify({ autoLayout: true }) } },
77
+ callbackType: 'STREAM',
78
+ imGroupOpenSpaceModel: { supportForward: true },
79
+ imRobotOpenSpaceModel: { supportForward: true },
80
+ }, headers)
81
+ await this.request('v1.0/card/instances/deliver', deliverBody(cardInstanceId, target, this.clientId), headers)
82
+ await this.request('v1.0/card/instances', {
83
+ outTrackId: cardInstanceId,
84
+ cardData: cardData(initialText, '2'),
85
+ }, headers, 'PUT')
86
+ await this.stream(cardInstanceId, initialText, false, headers)
87
+ return cardInstanceId
88
+ }
89
+
90
+ async update(cardInstanceId: string, text: string): Promise<void> {
91
+ const token = await this.accessToken()
92
+ await this.stream(cardInstanceId, text, false, { 'x-acs-dingtalk-access-token': token })
93
+ }
94
+
95
+ async finish(cardInstanceId: string, text: string): Promise<void> {
96
+ const token = await this.accessToken()
97
+ const headers = { 'x-acs-dingtalk-access-token': token }
98
+ await this.stream(cardInstanceId, text, true, headers)
99
+ await this.request('v1.0/card/instances', {
100
+ outTrackId: cardInstanceId,
101
+ cardData: cardData(text, '3'),
102
+ }, headers, 'PUT')
103
+ }
104
+
105
+ private async stream(cardInstanceId: string, text: string, finalize: boolean, headers: Record<string, string>): Promise<void> {
106
+ await this.request('v1.0/card/streaming', {
107
+ outTrackId: cardInstanceId,
108
+ guid: randomUUID(),
109
+ key: 'msgContent',
110
+ content: finalize ? normalizeDingtalkCardMarkdown(text) : normalizeDingtalkCardMarkdown(text).replace(/\n+$/, ''),
111
+ isFull: true,
112
+ isFinalize: finalize,
113
+ isError: false,
114
+ }, headers, 'PUT')
115
+ }
116
+
117
+ private async accessToken(): Promise<string> {
118
+ if (this.token && Date.now() < this.tokenExpiresAt) return this.token
119
+ const res = await fetch(new URL('v1.0/oauth2/accessToken', API), {
120
+ method: 'POST',
121
+ headers: { 'content-type': 'application/json' },
122
+ body: JSON.stringify({ appKey: this.clientId, appSecret: this.clientSecret }),
123
+ })
124
+ const data = await res.json() as { accessToken?: string; expireIn?: number }
125
+ if (!data.accessToken) throw new Error('钉钉没有返回 accessToken')
126
+ this.token = data.accessToken
127
+ this.tokenExpiresAt = Date.now() + Math.max(1000, ((data.expireIn ?? 7200) - 60) * 1000)
128
+ return this.token
129
+ }
130
+
131
+ private async request(path: string, body: unknown, headers: Record<string, string>, method = 'POST'): Promise<void> {
132
+ const res = await fetch(new URL(path, API), {
133
+ method,
134
+ headers: { 'content-type': 'application/json', ...headers },
135
+ body: JSON.stringify(body),
136
+ })
137
+ if (!res.ok) {
138
+ const text = await res.text().catch(() => '')
139
+ throw new Error(`钉钉 ${path} HTTP ${res.status} ${text.slice(0, 200)}`)
140
+ }
141
+ }
142
+ }
143
+
144
+ export async function openDingtalkCardStream(
145
+ client: DingtalkCardClient,
146
+ target: CardTarget,
147
+ log: (line: string) => void,
148
+ ): Promise<ReplyStream> {
149
+ const cardInstanceId = await client.create(target, '正在思考…')
150
+ let pending: string | null = null
151
+ let timer: NodeJS.Timeout | null = null
152
+ let last = 0
153
+ let closed = false
154
+
155
+ const flush = async (text: string) => {
156
+ if (closed) return
157
+ pending = null
158
+ await client.update(cardInstanceId, text)
159
+ last = Date.now()
160
+ }
161
+
162
+ return {
163
+ async update(text) {
164
+ if (closed || !text.trim()) return
165
+ pending = text
166
+ const wait = Math.max(0, last + UPDATE_INTERVAL_MS - Date.now())
167
+ if (timer) return
168
+ timer = setTimeout(() => {
169
+ timer = null
170
+ const next = pending
171
+ if (next) void flush(next).catch((error) => {
172
+ log(`[dingtalk] AI Card 更新失败: ${error instanceof Error ? error.message : String(error)}`)
173
+ })
174
+ }, wait)
175
+ timer.unref?.()
176
+ },
177
+ async finish(text) {
178
+ if (closed) return
179
+ closed = true
180
+ if (timer) clearTimeout(timer)
181
+ timer = null
182
+ try {
183
+ await client.finish(cardInstanceId, text || '(无文本回复)')
184
+ } catch (error) {
185
+ log(`[dingtalk] AI Card 收口失败: ${error instanceof Error ? error.message : String(error)}`)
186
+ throw error
187
+ }
188
+ },
189
+ }
190
+ }
191
+
@@ -0,0 +1,113 @@
1
+ import type { ChannelAdapter, ImMessage, ReplyStream } from '../engine/types.js'
2
+ import { DingtalkCardClient, openDingtalkCardStream, type CardTarget } from './dingtalk-card.js'
3
+
4
+ export interface DingtalkConfig {
5
+ clientId?: string
6
+ clientSecret?: string
7
+ }
8
+
9
+ export function createDingtalkChannel(config: DingtalkConfig, log: (line: string) => void): ChannelAdapter | undefined {
10
+ const clientId = config.clientId?.trim()
11
+ const clientSecret = config.clientSecret?.trim()
12
+ if (!clientId || !clientSecret) return undefined
13
+
14
+ let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
15
+ let client: { connect(): Promise<void>; disconnect(): void; registerCallbackListener(topic: string, cb: (res: { data: string }) => unknown): void } | undefined
16
+ let statusText = '未连接'
17
+ const webhooks = new Map<string, string>()
18
+ const targets = new Map<string, CardTarget>()
19
+ const cards = new DingtalkCardClient(clientId, clientSecret)
20
+
21
+ return {
22
+ id: 'dingtalk',
23
+ label: '钉钉',
24
+ maxMessageLength: 4000,
25
+ async start() {
26
+ try {
27
+ const sdk = await import('dingtalk-stream') as {
28
+ DWClient: new (opts: Record<string, unknown>) => NonNullable<typeof client>
29
+ TOPIC_ROBOT: string
30
+ }
31
+ client = new sdk.DWClient({ clientId, clientSecret, autoReconnect: true })
32
+ client.registerCallbackListener(sdk.TOPIC_ROBOT, (res) => {
33
+ let payload: {
34
+ text?: { content?: string }
35
+ senderStaffId?: string
36
+ senderId?: string
37
+ conversationId?: string
38
+ conversationType?: string
39
+ sessionWebhook?: string
40
+ }
41
+ try { payload = JSON.parse(res.data) as typeof payload } catch { return }
42
+ const text = payload.text?.content?.trim() ?? ''
43
+ const sender = payload.senderStaffId ?? payload.senderId ?? ''
44
+ const group = String(payload.conversationType) === '2'
45
+ const chatId = group ? (payload.conversationId ?? '') : sender
46
+ if (payload.sessionWebhook && chatId) webhooks.set(chatId, payload.sessionWebhook)
47
+ if (chatId) {
48
+ targets.set(chatId, group
49
+ ? { type: 'group', openConversationId: payload.conversationId ?? chatId }
50
+ : { type: 'user', userId: sender })
51
+ }
52
+ if (!chatId || !text) return { status: 'SUCCESS' }
53
+ void handler?.({
54
+ chatId,
55
+ userId: sender,
56
+ text,
57
+ kind: group ? 'group' : 'dm',
58
+ addressed: true,
59
+ })
60
+ return { status: 'SUCCESS' }
61
+ })
62
+ await client.connect()
63
+ statusText = 'Stream 已连接'
64
+ log('[dingtalk] Stream 已连接')
65
+ } catch (error) {
66
+ const message = error instanceof Error ? error.message : String(error)
67
+ const missing = /Cannot find package ['"]dingtalk-stream['"]/i.test(message)
68
+ throw new Error(missing ? '缺少依赖 dingtalk-stream' : `钉钉连接失败: ${message}`)
69
+ }
70
+ },
71
+ async stop() {
72
+ client?.disconnect()
73
+ client = undefined
74
+ statusText = '已停止'
75
+ },
76
+ async send(chatId, text) {
77
+ const webhook = webhooks.get(chatId)
78
+ if (!webhook) throw new Error('dingtalk: 没有可回复的 webhook,请先在钉钉里发一条消息')
79
+ const res = await fetch(webhook, {
80
+ method: 'POST',
81
+ headers: { 'content-type': 'application/json' },
82
+ body: JSON.stringify({ msgtype: 'markdown', markdown: { title: 'IM助理', text } }),
83
+ })
84
+ if (!res.ok) throw new Error(`dingtalk send HTTP ${res.status}`)
85
+ },
86
+ async beginReply(chatId): Promise<ReplyStream> {
87
+ const target = targets.get(chatId)
88
+ if (!target) throw new Error('dingtalk: 还没有卡片投放目标')
89
+ try {
90
+ return await openDingtalkCardStream(cards, target, log)
91
+ } catch (error) {
92
+ log(`[dingtalk] AI Card 创建失败,回退普通文本: ${error instanceof Error ? error.message : String(error)}`)
93
+ const sendText = async (text: string) => {
94
+ const webhook = webhooks.get(chatId)
95
+ if (!webhook) throw new Error('dingtalk: 没有可回复的 webhook')
96
+ await fetch(webhook, {
97
+ method: 'POST',
98
+ headers: { 'content-type': 'application/json' },
99
+ body: JSON.stringify({ msgtype: 'markdown', markdown: { title: 'IM助理', text } }),
100
+ })
101
+ }
102
+ return {
103
+ async update() { /* 普通文本无法中途改 */ },
104
+ async finish(text) { await sendText(text) },
105
+ }
106
+ }
107
+ },
108
+ setMessageHandler(h) { handler = h },
109
+ status() { return statusText },
110
+ }
111
+ }
112
+
113
+
@@ -0,0 +1,32 @@
1
+ import type { ChannelAdapter } from '../engine/types.js'
2
+ import type { ChannelId } from '../engine/session-id.js'
3
+ import { createDingtalkChannel } from './dingtalk.js'
4
+ import { createFeishuChannel } from './feishu.js'
5
+ import { createTelegramChannel } from './telegram.js'
6
+ import { createWecomChannel } from './wecom.js'
7
+ import { createWeixinChannel } from './weixin.js'
8
+
9
+ export function createChannelAdapter(
10
+ id: ChannelId,
11
+ config: Record<string, string>,
12
+ log: (line: string) => void,
13
+ stateDir: string,
14
+ ): ChannelAdapter | undefined {
15
+ switch (id) {
16
+ case 'telegram':
17
+ return createTelegramChannel({ token: config.token, stateDir }, log)
18
+ case 'feishu':
19
+ return createFeishuChannel('feishu', { appId: config.appId, appSecret: config.appSecret }, log)
20
+ case 'lark':
21
+ return createFeishuChannel('lark', { appId: config.appId, appSecret: config.appSecret, domain: 'lark' }, log)
22
+ case 'weixin':
23
+ return createWeixinChannel({ enabled: true, stateDir }, log, stateDir)
24
+ case 'wecom':
25
+ return createWecomChannel({ botId: config.botId, secret: config.secret }, log)
26
+ case 'dingtalk':
27
+ return createDingtalkChannel({ clientId: config.clientId, clientSecret: config.clientSecret }, log)
28
+ default:
29
+ return undefined
30
+ }
31
+ }
32
+
@@ -0,0 +1,77 @@
1
+ import type { ChannelAdapter, ImMessage } from '../engine/types.js'
2
+
3
+ export interface FeishuConfig {
4
+ appId?: string
5
+ appSecret?: string
6
+ domain?: 'feishu' | 'lark'
7
+ }
8
+
9
+ export function createFeishuChannel(id: 'feishu' | 'lark', config: FeishuConfig, log: (line: string) => void): ChannelAdapter | undefined {
10
+ const appId = config.appId?.trim()
11
+ const appSecret = config.appSecret?.trim()
12
+ if (!appId || !appSecret) return undefined
13
+
14
+ let handler: ((msg: ImMessage) => void | Promise<void>) | undefined
15
+ let client: { im: { message: { create(opts: unknown): Promise<unknown> } } } | undefined
16
+ let ws: { close(opts?: { force?: boolean }): void } | undefined
17
+ let statusText = '未连接'
18
+ const label = id === 'lark' ? 'Lark' : '飞书'
19
+
20
+ return {
21
+ id,
22
+ label,
23
+ maxMessageLength: 4000,
24
+ async start() {
25
+ let sdk: typeof import('@larksuiteoapi/node-sdk')
26
+ try {
27
+ sdk = await import('@larksuiteoapi/node-sdk')
28
+ } catch {
29
+ throw new Error('缺少依赖 @larksuiteoapi/node-sdk')
30
+ }
31
+ const domain = id === 'lark' || config.domain === 'lark' ? 'https://open.larksuite.com' : undefined
32
+ client = new sdk.Client({ appId, appSecret, ...(domain ? { domain } : {}) }) as unknown as typeof client
33
+ const dispatcher = new sdk.EventDispatcher({}).register({
34
+ 'im.message.receive_v1': (data: {
35
+ sender?: { sender_id?: { open_id?: string } }
36
+ message?: { chat_id?: string; chat_type?: string; message_type?: string; content?: string; mentions?: Array<{ key?: string }> }
37
+ }) => {
38
+ const message = data.message
39
+ if (!message || message.message_type !== 'text') return
40
+ let text = ''
41
+ try { text = (JSON.parse(message.content ?? '{}') as { text?: string }).text ?? '' } catch { text = message.content ?? '' }
42
+ const group = message.chat_type === 'group'
43
+ if (group && Array.isArray(message.mentions) === false) {
44
+ /* 群聊未带 mentions 时仍交给引擎,由 addressed 默认 true 以免漏消息;有 mentions 再判断 */
45
+ }
46
+ void handler?.({
47
+ chatId: message.chat_id ?? '',
48
+ userId: data.sender?.sender_id?.open_id,
49
+ text,
50
+ kind: group ? 'group' : 'dm',
51
+ addressed: !group || (message.mentions?.length ?? 0) > 0,
52
+ })
53
+ },
54
+ })
55
+ const wsClient = new sdk.WSClient({ appId, appSecret, ...(domain ? { domain } : {}) })
56
+ ws = wsClient
57
+ await wsClient.start({ eventDispatcher: dispatcher })
58
+ statusText = '长连接已建立'
59
+ log(`[${id}] WebSocket 长连接已启动`)
60
+ },
61
+ async stop() {
62
+ ws?.close({ force: true })
63
+ ws = undefined
64
+ statusText = '已停止'
65
+ },
66
+ async send(chatId, text) {
67
+ if (!client) throw new Error(`${id}: 尚未连接`)
68
+ await client.im.message.create({
69
+ params: { receive_id_type: 'chat_id' },
70
+ data: { receive_id: chatId, msg_type: 'text', content: JSON.stringify({ text }) },
71
+ })
72
+ },
73
+ setMessageHandler(h) { handler = h },
74
+ status() { return statusText },
75
+ }
76
+ }
77
+
@@ -0,0 +1,89 @@
1
+ import type { ChannelId } from '../engine/session-id.js'
2
+
3
+ export type ChannelKind = 'qr' | 'credentials' | 'qr-or-credentials'
4
+
5
+ export interface ChannelField {
6
+ key: string
7
+ label: string
8
+ secret?: boolean
9
+ }
10
+
11
+ export interface ChannelMeta {
12
+ id: ChannelId
13
+ label: string
14
+ description: string
15
+ kind: ChannelKind
16
+ fields: ChannelField[]
17
+ }
18
+
19
+ /** 设置页卡片顺序,对标视觉稿后再补 Telegram。 */
20
+ export const CHANNEL_ORDER: ChannelId[] = [
21
+ 'dingtalk',
22
+ 'feishu',
23
+ 'lark',
24
+ 'weixin',
25
+ 'wecom',
26
+ 'telegram',
27
+ ]
28
+
29
+ export const CHANNEL_META: Record<ChannelId, ChannelMeta> = {
30
+ dingtalk: {
31
+ id: 'dingtalk',
32
+ label: '钉钉',
33
+ description: '通过钉钉机器人接收并回复用户消息',
34
+ kind: 'qr-or-credentials',
35
+ fields: [
36
+ { key: 'clientId', label: 'Client ID(原 AppKey)' },
37
+ { key: 'clientSecret', label: 'Client Secret(原 AppSecret)', secret: true },
38
+ ],
39
+ },
40
+ feishu: {
41
+ id: 'feishu',
42
+ label: '飞书',
43
+ description: '通过飞书机器人接收并回复用户消息',
44
+ kind: 'qr',
45
+ fields: [],
46
+ },
47
+ lark: {
48
+ id: 'lark',
49
+ label: 'Lark',
50
+ description: '通过 Lark 机器人接收并回复用户消息',
51
+ kind: 'qr',
52
+ fields: [],
53
+ },
54
+ weixin: {
55
+ id: 'weixin',
56
+ label: '微信',
57
+ description: '通过微信机器人接收并回复用户消息',
58
+ kind: 'qr',
59
+ fields: [],
60
+ },
61
+ wecom: {
62
+ id: 'wecom',
63
+ label: '企业微信',
64
+ description: '通过企业微信机器人接收并回复用户消息',
65
+ kind: 'qr-or-credentials',
66
+ fields: [
67
+ { key: 'botId', label: 'Bot ID' },
68
+ { key: 'secret', label: 'Secret', secret: true },
69
+ ],
70
+ },
71
+ telegram: {
72
+ id: 'telegram',
73
+ label: 'Telegram',
74
+ description: '通过 Telegram 机器人接收并回复用户消息',
75
+ kind: 'credentials',
76
+ fields: [
77
+ { key: 'token', label: 'Bot Token', secret: true },
78
+ ],
79
+ },
80
+ }
81
+
82
+ export function listChannelMeta(): ChannelMeta[] {
83
+ return CHANNEL_ORDER.map((id) => CHANNEL_META[id])
84
+ }
85
+
86
+ export function supportsQr(id: ChannelId): boolean {
87
+ const kind = CHANNEL_META[id]?.kind
88
+ return kind === 'qr' || kind === 'qr-or-credentials'
89
+ }
@@ -0,0 +1,71 @@
1
+ /** 钉钉设备注册扫码:拿到 Client ID / Client Secret。 */
2
+ import { asRecord, cleanString, readJson, type PairingBegin, type PairingPoll } from './shared.js'
3
+
4
+ const BASE_URL = 'https://oapi.dingtalk.com'
5
+ const SOURCE = 'DING_DWS_CLAW'
6
+
7
+ export function parseDingtalkInit(body: unknown): string {
8
+ const record = asRecord(body)
9
+ if (Number(record.errcode ?? 0) !== 0) throw new Error('钉钉注册初始化被拒绝')
10
+ const nonce = cleanString(record.nonce)
11
+ if (!nonce) throw new Error('钉钉注册初始化没有返回 nonce')
12
+ return nonce
13
+ }
14
+
15
+ export function parseDingtalkBegin(body: unknown, now = Date.now()): {
16
+ deviceCode: string
17
+ verificationUrl: string
18
+ expiresAt: number
19
+ pollIntervalMs: number
20
+ } {
21
+ const record = asRecord(body)
22
+ if (Number(record.errcode ?? 0) !== 0) throw new Error('钉钉注册开始被拒绝')
23
+ const deviceCode = cleanString(record.device_code)
24
+ const verificationUrl = cleanString(record.verification_uri_complete)
25
+ if (!deviceCode || !verificationUrl) throw new Error('钉钉注册没有返回完整二维码')
26
+ const expiresInSeconds = Number(record.expires_in)
27
+ const interval = Number(record.interval)
28
+ return {
29
+ deviceCode,
30
+ verificationUrl,
31
+ expiresAt: now + (Number.isFinite(expiresInSeconds) && expiresInSeconds > 0 ? expiresInSeconds : 7200) * 1000,
32
+ pollIntervalMs: (Number.isFinite(interval) && interval > 0 ? interval : 5) * 1000,
33
+ }
34
+ }
35
+
36
+ export function parseDingtalkPoll(body: unknown): PairingPoll {
37
+ const record = asRecord(body)
38
+ if (Number(record.errcode ?? 0) !== 0) throw new Error('钉钉扫码查询被拒绝')
39
+ const raw = cleanString(record.status)?.toUpperCase()
40
+ if (raw === 'SUCCESS') {
41
+ const clientId = cleanString(record.client_id)
42
+ const clientSecret = cleanString(record.client_secret)
43
+ if (!clientId || !clientSecret) throw new Error('钉钉扫码结果缺少 Client 凭据')
44
+ return { status: 'success', credentials: { clientId, clientSecret } }
45
+ }
46
+ if (raw === 'EXPIRED') return { status: 'expired', error: '二维码已过期' }
47
+ if (raw === 'FAIL') return { status: 'failed', error: cleanString(record.fail_reason) ?? '扫码未完成' }
48
+ return { status: 'waiting' }
49
+ }
50
+
51
+ async function post(path: string, payload: Record<string, string>, signal?: AbortSignal): Promise<Record<string, unknown>> {
52
+ const response = await fetch(`${BASE_URL}${path}`, {
53
+ method: 'POST',
54
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
55
+ body: JSON.stringify(payload),
56
+ redirect: 'error',
57
+ signal: signal ?? AbortSignal.timeout(15_000),
58
+ })
59
+ return readJson(response, `钉钉${path}`)
60
+ }
61
+
62
+ export async function beginDingtalkQr(signal?: AbortSignal): Promise<PairingBegin> {
63
+ const nonce = parseDingtalkInit(await post('/app/registration/init', { source: SOURCE }, signal))
64
+ const begun = parseDingtalkBegin(await post('/app/registration/begin', { nonce }, signal))
65
+ return {
66
+ qrUrl: begun.verificationUrl,
67
+ expiresAt: begun.expiresAt,
68
+ pollIntervalMs: begun.pollIntervalMs,
69
+ poll: async (pollSignal) => parseDingtalkPoll(await post('/app/registration/poll', { device_code: begun.deviceCode }, pollSignal)),
70
+ }
71
+ }
@@ -0,0 +1,90 @@
1
+ /** 飞书 / Lark 设备注册扫码,自动创建机器人。 */
2
+ import { asRecord, cleanString, readJson, type PairingBegin, type PairingPoll } from './shared.js'
3
+
4
+ const FEISHU_ACCOUNTS = 'https://accounts.feishu.cn'
5
+ const LARK_ACCOUNTS = 'https://accounts.larksuite.com'
6
+
7
+ export function accountsBase(domain: 'feishu' | 'lark'): string {
8
+ return domain === 'lark' ? LARK_ACCOUNTS : FEISHU_ACCOUNTS
9
+ }
10
+
11
+ export function parseFeishuBegin(body: unknown, now = Date.now()): {
12
+ deviceCode: string
13
+ qrUrl: string
14
+ expiresAt: number
15
+ pollIntervalMs: number
16
+ } {
17
+ const record = asRecord(body)
18
+ const err = cleanString(record.error)
19
+ if (err) throw new Error(`飞书注册开始失败:${err}`)
20
+ const deviceCode = cleanString(record.device_code)
21
+ const qrUrl = cleanString(record.verification_uri_complete)
22
+ if (!deviceCode || !qrUrl) throw new Error('飞书注册没有返回完整二维码')
23
+ const expiresIn = Number(record.expire_in ?? record.expires_in)
24
+ const interval = Number(record.interval)
25
+ return {
26
+ deviceCode,
27
+ qrUrl,
28
+ expiresAt: now + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 300) * 1000,
29
+ pollIntervalMs: (Number.isFinite(interval) && interval > 0 ? interval : 5) * 1000,
30
+ }
31
+ }
32
+
33
+ export function parseFeishuPoll(body: unknown, currentBase: string): PairingPoll & { baseUrl?: string } {
34
+ const record = asRecord(body)
35
+ const userInfo = asRecord(record.user_info)
36
+ const brand = cleanString(userInfo.tenant_brand)
37
+ let baseUrl = currentBase
38
+ if (brand?.toLowerCase() === 'lark' && currentBase !== LARK_ACCOUNTS) baseUrl = LARK_ACCOUNTS
39
+
40
+ const appId = cleanString(record.client_id)
41
+ const appSecret = cleanString(record.client_secret)
42
+ if (appId && appSecret) {
43
+ const ownerOpenId = cleanString(userInfo.open_id)
44
+ return {
45
+ status: 'success',
46
+ credentials: ownerOpenId ? { appId, appSecret, ownerOpenId } : { appId, appSecret },
47
+ baseUrl,
48
+ }
49
+ }
50
+
51
+ const err = cleanString(record.error)
52
+ if (err === 'authorization_pending') return { status: 'waiting', baseUrl }
53
+ if (err === 'slow_down') return { status: 'waiting', baseUrl, pollIntervalMs: 10_000 }
54
+ if (err === 'access_denied') return { status: 'failed', error: '用户拒绝授权', baseUrl }
55
+ if (err === 'expired_token') return { status: 'expired', error: '二维码已过期', baseUrl }
56
+ if (err) return { status: 'failed', error: err, baseUrl }
57
+ return { status: 'waiting', baseUrl }
58
+ }
59
+
60
+ async function call(baseUrl: string, action: string, params: Record<string, string>, signal?: AbortSignal): Promise<Record<string, unknown>> {
61
+ const form = new URLSearchParams({ action, ...params })
62
+ const response = await fetch(`${baseUrl}/oauth/v1/app/registration`, {
63
+ method: 'POST',
64
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
65
+ body: form.toString(),
66
+ redirect: 'error',
67
+ signal: signal ?? AbortSignal.timeout(15_000),
68
+ })
69
+ return readJson(response, `飞书${action}`)
70
+ }
71
+
72
+ export async function beginFeishuQr(domain: 'feishu' | 'lark', signal?: AbortSignal): Promise<PairingBegin> {
73
+ let baseUrl = accountsBase(domain)
74
+ await call(baseUrl, 'init', {}, signal)
75
+ const begun = parseFeishuBegin(await call(baseUrl, 'begin', {
76
+ archetype: 'PersonalAgent',
77
+ auth_method: 'client_secret',
78
+ request_user_info: 'open_id',
79
+ }, signal))
80
+ return {
81
+ qrUrl: begun.qrUrl,
82
+ expiresAt: begun.expiresAt,
83
+ pollIntervalMs: begun.pollIntervalMs,
84
+ poll: async (pollSignal) => {
85
+ const polled = parseFeishuPoll(await call(baseUrl, 'poll', { device_code: begun.deviceCode }, pollSignal), baseUrl)
86
+ if (polled.baseUrl) baseUrl = polled.baseUrl
87
+ return polled
88
+ },
89
+ }
90
+ }