@michengai/dsh-im-connect 0.1.25 → 0.1.26

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.
@@ -1,201 +1,201 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import type { ReplyStream } from '../engine/types.js'
3
3
  import { timeoutSignal } from '../engine/abort.js'
4
-
5
- const API = 'https://api.dingtalk.com/'
6
- const TEMPLATE_ID = '02fcf2f4-5e02-4a85-b672-46d1f715543e.schema'
7
- const UPDATE_INTERVAL_MS = 500
8
-
9
- export type CardTarget =
10
- | { type: 'user'; userId: string }
11
- | { type: 'group'; openConversationId: string }
12
-
13
- export function normalizeDingtalkCardMarkdown(value: string): string {
14
- const text = value.replace(/\r\n?/g, '\n')
15
- const lines = text.split('\n')
16
- let inCode = false
17
- return lines.map((line, index) => {
18
- const fenced = /^\s{0,3}```/.test(line)
19
- const wasInCode = inCode
20
- if (fenced) inCode = !inCode
21
- if (index === lines.length - 1) return line
22
- if (wasInCode || fenced || inCode || !line || !lines[index + 1]) return `${line}\n`
23
- if (/^\s{0,3}(?:[-*+] |\d+[.)] |#{1,6} |\||> )/.test(lines[index + 1] ?? '')) return `${line}\n`
24
- return `${line}<br>`
25
- }).join('')
26
- }
27
-
28
- function cardData(text: string, flowStatus: string) {
29
- return {
30
- cardParamMap: {
31
- flowStatus,
32
- msgContent: normalizeDingtalkCardMarkdown(text),
33
- staticMsgContent: '',
34
- sys_full_json_obj: JSON.stringify({ order: ['msgContent'] }),
35
- config: JSON.stringify({ autoLayout: true }),
36
- },
37
- }
38
- }
39
-
40
- function deliverBody(cardInstanceId: string, target: CardTarget, robotCode: string) {
41
- if (target.type === 'group') {
42
- return {
43
- outTrackId: cardInstanceId,
44
- userIdType: 1,
45
- openSpaceId: `dtv1.card//IM_GROUP.${target.openConversationId}`,
46
- imGroupOpenDeliverModel: { robotCode },
47
- }
48
- }
49
- return {
50
- outTrackId: cardInstanceId,
51
- userIdType: 1,
52
- openSpaceId: `dtv1.card//IM_ROBOT.${target.userId}`,
53
- imRobotOpenDeliverModel: {
54
- spaceType: 'IM_ROBOT',
55
- robotCode,
56
- extension: { dynamicSummary: 'true' },
57
- },
58
- }
59
- }
60
-
61
- export class DingtalkCardClient {
62
- private token = ''
63
- private tokenExpiresAt = 0
64
-
65
- constructor(
66
- private readonly clientId: string,
67
- private readonly clientSecret: string,
68
- private readonly log: (line: string) => void = () => undefined,
69
- ) {}
70
-
71
- async create(target: CardTarget, initialText: string): Promise<string> {
72
- const token = await this.accessToken()
73
- const cardInstanceId = `imc_${randomUUID()}`
74
- const headers = { 'x-acs-dingtalk-access-token': token }
75
- await this.request('v1.0/card/instances', {
76
- cardTemplateId: TEMPLATE_ID,
77
- outTrackId: cardInstanceId,
78
- cardData: { cardParamMap: { config: JSON.stringify({ autoLayout: true }) } },
79
- callbackType: 'STREAM',
80
- imGroupOpenSpaceModel: { supportForward: true },
81
- imRobotOpenSpaceModel: { supportForward: true },
82
- }, headers)
83
- await this.request('v1.0/card/instances/deliver', deliverBody(cardInstanceId, target, this.clientId), headers)
84
- await this.request('v1.0/card/instances', {
85
- outTrackId: cardInstanceId,
86
- cardData: cardData(initialText, '2'),
87
- }, headers, 'PUT')
88
- await this.stream(cardInstanceId, initialText, false, headers)
89
- return cardInstanceId
90
- }
91
-
92
- async update(cardInstanceId: string, text: string): Promise<void> {
93
- const token = await this.accessToken()
94
- await this.stream(cardInstanceId, text, false, { 'x-acs-dingtalk-access-token': token })
95
- }
96
-
97
- async finish(cardInstanceId: string, text: string): Promise<void> {
98
- const token = await this.accessToken()
99
- const headers = { 'x-acs-dingtalk-access-token': token }
100
- await this.stream(cardInstanceId, text, true, headers)
101
- try {
102
- await this.request('v1.0/card/instances', {
103
- outTrackId: cardInstanceId,
104
- cardData: cardData(text, '3'),
105
- }, headers, 'PUT')
106
- } catch (error) {
107
- // 流式已经把全文写进卡片,收口 PUT 失败不再抛,避免上层再 webhook 发一条;但要留日志便于排障
108
- this.log(`[dingtalk-card] 收口 PUT 失败(卡片仍以流式全文收尾): ${error instanceof Error ? error.message : String(error)}`)
109
- }
110
- }
111
-
112
- private async stream(cardInstanceId: string, text: string, finalize: boolean, headers: Record<string, string>): Promise<void> {
113
- await this.request('v1.0/card/streaming', {
114
- outTrackId: cardInstanceId,
115
- guid: randomUUID(),
116
- key: 'msgContent',
117
- content: finalize ? normalizeDingtalkCardMarkdown(text) : normalizeDingtalkCardMarkdown(text).replace(/\n+$/, ''),
118
- isFull: true,
119
- isFinalize: finalize,
120
- isError: false,
121
- }, headers, 'PUT')
122
- }
123
-
124
- private async accessToken(): Promise<string> {
125
- if (this.token && Date.now() < this.tokenExpiresAt) return this.token
126
- const res = await fetch(new URL('v1.0/oauth2/accessToken', API), {
127
- method: 'POST',
4
+
5
+ const API = 'https://api.dingtalk.com/'
6
+ const TEMPLATE_ID = '02fcf2f4-5e02-4a85-b672-46d1f715543e.schema'
7
+ const UPDATE_INTERVAL_MS = 500
8
+
9
+ export type CardTarget =
10
+ | { type: 'user'; userId: string }
11
+ | { type: 'group'; openConversationId: string }
12
+
13
+ export function normalizeDingtalkCardMarkdown(value: string): string {
14
+ const text = value.replace(/\r\n?/g, '\n')
15
+ const lines = text.split('\n')
16
+ let inCode = false
17
+ return lines.map((line, index) => {
18
+ const fenced = /^\s{0,3}```/.test(line)
19
+ const wasInCode = inCode
20
+ if (fenced) inCode = !inCode
21
+ if (index === lines.length - 1) return line
22
+ if (wasInCode || fenced || inCode || !line || !lines[index + 1]) return `${line}\n`
23
+ if (/^\s{0,3}(?:[-*+] |\d+[.)] |#{1,6} |\||> )/.test(lines[index + 1] ?? '')) return `${line}\n`
24
+ return `${line}<br>`
25
+ }).join('')
26
+ }
27
+
28
+ function cardData(text: string, flowStatus: string) {
29
+ return {
30
+ cardParamMap: {
31
+ flowStatus,
32
+ msgContent: normalizeDingtalkCardMarkdown(text),
33
+ staticMsgContent: '',
34
+ sys_full_json_obj: JSON.stringify({ order: ['msgContent'] }),
35
+ config: JSON.stringify({ autoLayout: true }),
36
+ },
37
+ }
38
+ }
39
+
40
+ function deliverBody(cardInstanceId: string, target: CardTarget, robotCode: string) {
41
+ if (target.type === 'group') {
42
+ return {
43
+ outTrackId: cardInstanceId,
44
+ userIdType: 1,
45
+ openSpaceId: `dtv1.card//IM_GROUP.${target.openConversationId}`,
46
+ imGroupOpenDeliverModel: { robotCode },
47
+ }
48
+ }
49
+ return {
50
+ outTrackId: cardInstanceId,
51
+ userIdType: 1,
52
+ openSpaceId: `dtv1.card//IM_ROBOT.${target.userId}`,
53
+ imRobotOpenDeliverModel: {
54
+ spaceType: 'IM_ROBOT',
55
+ robotCode,
56
+ extension: { dynamicSummary: 'true' },
57
+ },
58
+ }
59
+ }
60
+
61
+ export class DingtalkCardClient {
62
+ private token = ''
63
+ private tokenExpiresAt = 0
64
+
65
+ constructor(
66
+ private readonly clientId: string,
67
+ private readonly clientSecret: string,
68
+ private readonly log: (line: string) => void = () => undefined,
69
+ ) {}
70
+
71
+ async create(target: CardTarget, initialText: string): Promise<string> {
72
+ const token = await this.accessToken()
73
+ const cardInstanceId = `imc_${randomUUID()}`
74
+ const headers = { 'x-acs-dingtalk-access-token': token }
75
+ await this.request('v1.0/card/instances', {
76
+ cardTemplateId: TEMPLATE_ID,
77
+ outTrackId: cardInstanceId,
78
+ cardData: { cardParamMap: { config: JSON.stringify({ autoLayout: true }) } },
79
+ callbackType: 'STREAM',
80
+ imGroupOpenSpaceModel: { supportForward: true },
81
+ imRobotOpenSpaceModel: { supportForward: true },
82
+ }, headers)
83
+ await this.request('v1.0/card/instances/deliver', deliverBody(cardInstanceId, target, this.clientId), headers)
84
+ await this.request('v1.0/card/instances', {
85
+ outTrackId: cardInstanceId,
86
+ cardData: cardData(initialText, '2'),
87
+ }, headers, 'PUT')
88
+ await this.stream(cardInstanceId, initialText, false, headers)
89
+ return cardInstanceId
90
+ }
91
+
92
+ async update(cardInstanceId: string, text: string): Promise<void> {
93
+ const token = await this.accessToken()
94
+ await this.stream(cardInstanceId, text, false, { 'x-acs-dingtalk-access-token': token })
95
+ }
96
+
97
+ async finish(cardInstanceId: string, text: string): Promise<void> {
98
+ const token = await this.accessToken()
99
+ const headers = { 'x-acs-dingtalk-access-token': token }
100
+ await this.stream(cardInstanceId, text, true, headers)
101
+ try {
102
+ await this.request('v1.0/card/instances', {
103
+ outTrackId: cardInstanceId,
104
+ cardData: cardData(text, '3'),
105
+ }, headers, 'PUT')
106
+ } catch (error) {
107
+ // 流式已经把全文写进卡片,收口 PUT 失败不再抛,避免上层再 webhook 发一条;但要留日志便于排障
108
+ this.log(`[dingtalk-card] 收口 PUT 失败(卡片仍以流式全文收尾): ${error instanceof Error ? error.message : String(error)}`)
109
+ }
110
+ }
111
+
112
+ private async stream(cardInstanceId: string, text: string, finalize: boolean, headers: Record<string, string>): Promise<void> {
113
+ await this.request('v1.0/card/streaming', {
114
+ outTrackId: cardInstanceId,
115
+ guid: randomUUID(),
116
+ key: 'msgContent',
117
+ content: finalize ? normalizeDingtalkCardMarkdown(text) : normalizeDingtalkCardMarkdown(text).replace(/\n+$/, ''),
118
+ isFull: true,
119
+ isFinalize: finalize,
120
+ isError: false,
121
+ }, headers, 'PUT')
122
+ }
123
+
124
+ private async accessToken(): Promise<string> {
125
+ if (this.token && Date.now() < this.tokenExpiresAt) return this.token
126
+ const res = await fetch(new URL('v1.0/oauth2/accessToken', API), {
127
+ method: 'POST',
128
128
  headers: { 'content-type': 'application/json' },
129
129
  body: JSON.stringify({ appKey: this.clientId, appSecret: this.clientSecret }),
130
130
  signal: timeoutSignal(30_000),
131
- })
132
- const data = await res.json() as { accessToken?: string; expireIn?: number }
133
- if (!data.accessToken) throw new Error('钉钉没有返回 accessToken')
134
- this.token = data.accessToken
135
- this.tokenExpiresAt = Date.now() + Math.max(1000, ((data.expireIn ?? 7200) - 60) * 1000)
136
- return this.token
137
- }
138
-
139
- private async request(path: string, body: unknown, headers: Record<string, string>, method = 'POST'): Promise<void> {
140
- const res = await fetch(new URL(path, API), {
141
- method,
131
+ })
132
+ const data = await res.json() as { accessToken?: string; expireIn?: number }
133
+ if (!data.accessToken) throw new Error('钉钉没有返回 accessToken')
134
+ this.token = data.accessToken
135
+ this.tokenExpiresAt = Date.now() + Math.max(1000, ((data.expireIn ?? 7200) - 60) * 1000)
136
+ return this.token
137
+ }
138
+
139
+ private async request(path: string, body: unknown, headers: Record<string, string>, method = 'POST'): Promise<void> {
140
+ const res = await fetch(new URL(path, API), {
141
+ method,
142
142
  headers: { 'content-type': 'application/json', ...headers },
143
143
  body: JSON.stringify(body),
144
144
  signal: timeoutSignal(30_000),
145
- })
146
- if (!res.ok) {
147
- const text = await res.text().catch(() => '')
148
- throw new Error(`钉钉 ${path} HTTP ${res.status} ${text.slice(0, 200)}`)
149
- }
150
- }
151
- }
152
-
153
- export async function openDingtalkCardStream(
154
- client: DingtalkCardClient,
155
- target: CardTarget,
156
- log: (line: string) => void,
157
- ): Promise<ReplyStream> {
158
- const cardInstanceId = await client.create(target, '正在思考…')
159
- let pending: string | null = null
160
- let timer: NodeJS.Timeout | null = null
161
- let last = 0
162
- let closed = false
163
-
164
- const flush = async (text: string) => {
165
- if (closed) return
166
- pending = null
167
- await client.update(cardInstanceId, text)
168
- last = Date.now()
169
- }
170
-
171
- return {
172
- async update(text) {
173
- if (closed || !text.trim()) return
174
- pending = text
175
- const wait = Math.max(0, last + UPDATE_INTERVAL_MS - Date.now())
176
- if (timer) return
177
- timer = setTimeout(() => {
178
- timer = null
179
- const next = pending
180
- if (next) void flush(next).catch((error) => {
181
- log(`[dingtalk] AI Card 更新失败: ${error instanceof Error ? error.message : String(error)}`)
182
- })
183
- }, wait)
184
- timer.unref?.()
185
- },
186
- async finish(text) {
187
- if (closed) return
188
- closed = true
189
- if (timer) clearTimeout(timer)
190
- timer = null
191
- try {
192
- await client.finish(cardInstanceId, text || '(无文本回复)')
193
- } catch (error) {
194
- log(`[dingtalk] AI Card 收口失败: ${error instanceof Error ? error.message : String(error)}`)
195
- throw error
196
- }
197
- },
198
- }
199
- }
200
-
201
-
145
+ })
146
+ if (!res.ok) {
147
+ const text = await res.text().catch(() => '')
148
+ throw new Error(`钉钉 ${path} HTTP ${res.status} ${text.slice(0, 200)}`)
149
+ }
150
+ }
151
+ }
152
+
153
+ export async function openDingtalkCardStream(
154
+ client: DingtalkCardClient,
155
+ target: CardTarget,
156
+ log: (line: string) => void,
157
+ ): Promise<ReplyStream> {
158
+ const cardInstanceId = await client.create(target, '正在思考…')
159
+ let pending: string | null = null
160
+ let timer: NodeJS.Timeout | null = null
161
+ let last = 0
162
+ let closed = false
163
+
164
+ const flush = async (text: string) => {
165
+ if (closed) return
166
+ pending = null
167
+ await client.update(cardInstanceId, text)
168
+ last = Date.now()
169
+ }
170
+
171
+ return {
172
+ async update(text) {
173
+ if (closed || !text.trim()) return
174
+ pending = text
175
+ const wait = Math.max(0, last + UPDATE_INTERVAL_MS - Date.now())
176
+ if (timer) return
177
+ timer = setTimeout(() => {
178
+ timer = null
179
+ const next = pending
180
+ if (next) void flush(next).catch((error) => {
181
+ log(`[dingtalk] AI Card 更新失败: ${error instanceof Error ? error.message : String(error)}`)
182
+ })
183
+ }, wait)
184
+ timer.unref?.()
185
+ },
186
+ async finish(text) {
187
+ if (closed) return
188
+ closed = true
189
+ if (timer) clearTimeout(timer)
190
+ timer = null
191
+ try {
192
+ await client.finish(cardInstanceId, text || '(无文本回复)')
193
+ } catch (error) {
194
+ log(`[dingtalk] AI Card 收口失败: ${error instanceof Error ? error.message : String(error)}`)
195
+ throw error
196
+ }
197
+ },
198
+ }
199
+ }
200
+
201
+