Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Add the DingTalk and WeCom IM adapters

Fei2411989330995e2d
diff --git a/ds-bot/src/host/im/platforms/dingtalk.js b/ds-bot/src/host/im/platforms/dingtalk.js
new file mode 100644
index 00000000..c51e0461
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/dingtalk.js
@@ -0,0 +1,200 @@
+// DingTalk stream mode: connections/open with the client credentials opens a
+// ticketed WebSocket; every frame is ACKed by echoing its messageId with
+// code 200, system pings get a pong, and the robot callback carries the
+// sessionWebhook for passive replies. Outside that window the OpenAPI
+// batchSend/groupMessages path answers instead. No buttons — the core
+// numbers choices. Wire details ported from dingtalk-stream (Apache 2.0,
+// see NOTICE).
+import { chunkMarkdown } from '../format.js'
+
+const GATEWAY = 'https://api.dingtalk.com'
+const OAPI = 'https://oapi.dingtalk.com'
+const TEXT_LIMIT = 5000
+
+const gatewayBase = env => String(env.config?.gateway ?? env.config?.api ?? GATEWAY).replace(/\/+$/, '')
+const oapiBase = env => String(env.config?.oapi ?? env.config?.api ?? OAPI).replace(/\/+$/, '')
+
+export default {
+ id: 'dingtalk',
+
+ async check(fields, env) {
+ const { accessToken } = await appToken(fields, env)
+ return { account: { id: String(fields.clientId ?? '').trim(), name: String(fields.clientId ?? '').trim() } }
+ },
+
+ connect(fields, env, handlers) {
+ const clientId = String(fields.clientId ?? '').trim()
+ let stopped = false
+ let socket
+ let generation = 0
+ let reconnectTimer
+ let token
+ let tokenExpiresAt = 0
+ // Passive replies reuse the inbound sessionWebhook while it lives.
+ const sessionWebhooks = new Map()
+
+ const sendFrame = packet => { if (socket?.readyState === 1) socket.send(JSON.stringify(packet)) }
+ const ack = (headers, data = {}) => sendFrame({
+ specVersion: '1.0',
+ code: 200,
+ headers: { appType: 'STREAM', clientId, messageId: String(headers?.messageId ?? ''), time: String(Date.now()) },
+ message: 'OK',
+ data: JSON.stringify(data),
+ })
+
+ const markdown = async (chat, text) => {
+ const chunks = chunkMarkdown(String(text ?? ''), TEXT_LIMIT)
+ let messageId
+ for (const chunk of chunks) {
+ const hook = sessionWebhooks.get(chat.key)
+ if (hook !== undefined && hook.until > Date.now()) {
+ const response = await env.fetch(hook.url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ msgtype: 'markdown', markdown: { title: chunk.slice(0, 30), text: chunk } }),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (body.errcode !== 0) throw Object.assign(new Error(String(body.errmsg ?? 'DingTalk refused the reply')), { permanent: true })
+ messageId = String(body.processQueryKey ?? messageId ?? '')
+ continue
+ }
+ if (chat.kind === 'direct') {
+ const answer = await robot(env, token, clientId, '/v1.0/robot/oToMessages/batchSend', {
+ robotCode: clientId, userIds: [chat.key],
+ msgKey: 'sampleMarkdown', msgParam: { title: chunk.slice(0, 30), text: chunk },
+ })
+ messageId = String(answer?.processQueryKey ?? messageId ?? '')
+ } else {
+ const answer = await robot(env, token, clientId, '/v1.0/robot/groupMessages/send', {
+ robotCode: clientId, openConversationId: chat.key,
+ msgKey: 'sampleMarkdown', msgParam: { title: chunk.slice(0, 30), text: chunk },
+ })
+ messageId = String(answer?.processQueryKey ?? messageId ?? '')
+ }
+ }
+ return { messageId }
+ }
+
+ const onCallback = async (headers, raw) => {
+ let data
+ try { data = JSON.parse(raw) } catch { return }
+ if (data.text === undefined && data.msgtype !== 'text' && data.msgtype !== 'richText' && data.msgtype !== 'picture') { ack(headers, { ok: true }); return }
+ const direct = data.conversationType === '1'
+ const mentioned = direct ? false : data.isInAtList === true
+ const key = String(direct ? data.senderStaffId ?? data.senderId ?? '' : data.conversationId ?? '')
+ if (data.sessionWebhook !== undefined) {
+ sessionWebhooks.set(key, { url: String(data.sessionWebhook), until: Date.now() + 20 * 60_000 })
+ }
+ // A picture message's content carries the download code, not text.
+ const text = String(data.text?.content ?? '').trim()
+ const sender = String(data.senderStaffId ?? data.senderId ?? '')
+ ack(headers, { ok: true })
+ await handlers.onMessage({
+ chat: { key, kind: direct ? 'direct' : 'group', title: '' },
+ sender: { id: sender, name: String(data.senderNick ?? sender) },
+ text, images: [], files: [],
+ mentioned, messageId: String(data.msgId ?? ''),
+ })
+ }
+
+ const open = async () => {
+ const gen = generation
+ let url
+ try {
+ const response = await env.fetch(`${gatewayBase(env)}/v1.0/gateway/connections/open`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ clientId, clientSecret: String(fields.clientSecret ?? '').trim(),
+ ua: 'ds-bot',
+ subscriptions: [{ type: 'CALLBACK', topic: '/v1.0/im/bot/messages/get' }],
+ }),
+ })
+ const body = await response.json().catch(() => ({}))
+ if (body.endpoint === undefined) throw new Error(String(body.message ?? body.error ?? 'DingTalk refused the connection'))
+ url = `${body.endpoint}?ticket=${body.ticket}`
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: error.message })
+ return
+ }
+ try { socket = new env.WebSocket(url) } catch (error) {
+ handlers.onStatus({ state: 'error', error: `DingTalk could not open a socket: ${error?.message ?? error}` })
+ return
+ }
+ socket.addEventListener('message', (event) => {
+ if (stopped || generation !== gen) return
+ let packet
+ try { packet = JSON.parse(String(event.data)) } catch { return }
+ const headers = packet.headers ?? {}
+ if (packet.type === 'SYSTEM') {
+ if (String(packet.data ?? '').includes('ping') || headers.eventType === 'ping' || packet.headers?.topic === 'ping') {
+ ack(headers, 'pong')
+ }
+ return
+ }
+ if (packet.type === 'CALLBACK' || packet.type === 'EVENT') {
+ void onCallback(headers, String(packet.data ?? '{}')).catch(error => env.log?.warn?.('ds-bot im: dingtalk message failed: %s', error?.message ?? error))
+ }
+ })
+ socket.addEventListener('open', () => handlers.onStatus({ state: 'ready' }))
+ socket.addEventListener('close', () => {
+ if (stopped || generation !== gen) return
+ handlers.onStatus({ state: 'connecting' })
+ reconnectTimer = setTimeout(() => { if (!stopped) void open() }, 2000)
+ reconnectTimer.unref?.()
+ })
+ socket.addEventListener('error', () => {})
+ }
+
+ handlers.onStatus({ state: 'connecting' })
+ void (async () => {
+ try {
+ const got = await appToken(fields, env)
+ token = got.accessToken
+ tokenExpiresAt = got.expiresAt
+ } catch (error) {
+ handlers.onStatus({ state: 'error', error: error.message })
+ return
+ }
+ if (!stopped) await open()
+ })()
+
+ return {
+ send: async (chat, { text }) => markdown(chat, text),
+ stop: () => {
+ stopped = true
+ generation += 1
+ clearTimeout(reconnectTimer)
+ try { socket?.close(1000, 'stop') } catch { /* not open */ }
+ },
+ }
+ },
+}
+
+// The app-level access token for OpenAPI sends (oapi gettoken, cached until
+// it expires).
+async function appToken(fields, env) {
+ const url = `${oapiBase(env)}/gettoken?appkey=${encodeURIComponent(String(fields.clientId ?? '').trim())}&appsecret=${encodeURIComponent(String(fields.clientSecret ?? '').trim())}`
+ const response = await env.fetch(url)
+ const body = await response.json().catch(() => ({}))
+ if (body.errcode !== 0 || body.access_token === undefined) {
+ throw Object.assign(new Error(String(body.errmsg ?? 'DingTalk refused these credentials')), { permanent: true })
+ }
+ return { accessToken: body.access_token, expiresAt: Date.now() + Math.max(60, Number(body.expires_in ?? 7200) - 300) * 1000 }
+}
+
+async function robot(env, token, clientId, path, body) {
+ if (token === undefined) throw Object.assign(new Error('DingTalk has no access token yet'), { permanent: false })
+ const response = await env.fetch(`${gatewayBase(env)}${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-acs-dingtalk-access-token': token },
+ body: JSON.stringify(body),
+ })
+ const json = await response.json().catch(() => ({}))
+ if (!response.ok) {
+ const error = new Error(String(json.message ?? json.errmsg ?? `DingTalk answered ${response.status}`))
+ error.permanent = response.status >= 400 && response.status < 500 && response.status !== 429
+ throw error
+ }
+ return json
+}
diff --git a/ds-bot/src/host/im/platforms/index.js b/ds-bot/src/host/im/platforms/index.js
index c9d50a7a..d91b044b 100644
--- a/ds-bot/src/host/im/platforms/index.js
+++ b/ds-bot/src/host/im/platforms/index.js
@@ -1,8 +1,10 @@
+import dingtalk from './dingtalk.js'
import discord from './discord.js'
import qq from './qq.js'
import slack from './slack.js'
import telegram from './telegram.js'
+import wecom from './wecom.js'
// Every platform with an adapter. The rest of IM_PLATFORMS still show in settings as
// coming soon — a connection can only be added for a platform listed here.
-export const adapters = { telegram, discord, slack, qq }
+export const adapters = { telegram, discord, slack, qq, dingtalk, wecom }
diff --git a/ds-bot/src/host/im/platforms/wecom.js b/ds-bot/src/host/im/platforms/wecom.js
new file mode 100644
index 00000000..36c9700e
--- /dev/null
+++ b/ds-bot/src/host/im/platforms/wecom.js
@@ -0,0 +1,190 @@
+// WeCom intelligent robot: one long-lived WebSocket, a { cmd, headers: {
+// req_id }, body } protocol — aibot_subscribe authenticates, ping heartbeats,
+// aibot_msg_callback carries inbound messages answered through
+// aibot_respond_msg with the callback's req_id, later messages use
+// aibot_send_msg. Template-card buttons come back as aibot_event_callback.
+// Encrypted images download with their per-link AES-256 key. Markdown.
+// Wire details ported from @wecom/aibot-node-sdk (MIT, see NOTICE).
+import { createDecipheriv } from 'node:crypto'
+import { chunkMarkdown } from '../format.js'
+
+const WSS = 'wss://openws.work.weixin.qq.com'
+const TEXT_LIMIT = 4000
+
+const wsBase = env => String(env.config?.gateway ?? env.config?.api ?? WSS).replace(/\/+$/, '')
+
+export default {
+ id: 'wecom',
+
+ // The subscription itself is the credential check: a bad bot id or secret
+ // fails the aibot_subscribe response.
+ async check(fields, env) {
+ return { account: { id: String(fields.botId ?? '').trim(), name: String(fields.botId ?? '').trim() } }
+ },
+
+ connect(fields, env, handlers) {
+ const botId = String(fields.botId ?? '').trim()
+ const secret = String(fields.secret ?? '').trim()
+ let stopped = false
+ let socket
+ let generation = 0
+ let reconnectTimer
+ let pingTimer
+ let reqCounter = 0
+ // Passive replies reuse the last callback req_id per chat.
+ const lastReqId = new Map()
+ const pending = new Map() // req_id → {resolve, reject}
+
+ const nextReqId = () => `r${++reqCounter}`
+ const sendFrame = (packet) => { if (socket?.readyState === 1) socket.send(JSON.stringify(packet)) }
+ const request = (cmd, body, reqId) => {
+ const req_id = reqId ?? nextReqId()
+ sendFrame({ cmd, headers: { req_id }, body })
+ if (cmd === 'aibot_send_msg') {
+ return new Promise((resolve, reject) => {
+ pending.set(req_id, { resolve, reject })
+ setTimeout(() => {
+ if (pending.delete(req_id)) reject(new Error('WeCom did not answer the send'))
+ }, 15_000).unref?.()
+ })
+ }
+ }
+
+ const onCallback = async (headers, body) => {
+ const key = String(body.chattype === 'single' ? body.from?.userid ?? '' : body.chatid ?? '')
+ lastReqId.set(key, String(headers?.req_id ?? ''))
+ const direct = body.chattype === 'single'
+ // Groups only count when the bot was @-ed: the text keeps the mention.
+ const text = String(body.text?.content ?? '').trim()
+ const mentioned = direct ? false : /@/.test(text) && text.includes('@')
+ const images = []
+ if (body.msgtype === 'image' && body.image?.url !== undefined) {
+ const bytes = await downloadImage(body.image, env).catch(() => undefined)
+ if (bytes !== undefined) images.push({ mediaType: 'image/jpeg', data: Buffer.from(bytes).toString('base64') })
+ }
+ // Reply frames go out with the callback's req_id; a failed reply is
+ // logged but the message itself still lands in the core.
+ await handlers.onMessage({
+ chat: { key, kind: direct ? 'direct' : 'group', title: '' },
+ sender: { id: String(body.from?.userid ?? ''), name: String(body.from?.name ?? body.from?.userid ?? '') },
+ text, images, files: [],
+ mentioned: body.chattype !== 'single' && body.mention_robot === true,
+ messageId: String(body.msgid ?? ''),
+ })
+ }
+
+ const onEvent = async (headers, body) => {
+ if (body.event?.event_type !== 'template_card_event' && body.event_type !== 'template_card_event') return
+ const card = body.event?.template_card_event ?? body.template_card_event ?? {}
+ const key = String(body.chattype === 'single' ? body.from?.userid ?? '' : body.chatid ?? card.chatid ?? '')
+ await handlers.onAction({
+ chat: { key, kind: body.chattype === 'single' ? 'direct' : 'group', title: '' },
+ sender: { id: String(body.from?.userid ?? card.userid ?? ''), name: '' },
+ data: String(card.event_key ?? card.key ?? ''),
+ messageId: String(body.msgid ?? ''),
+ })
+ }
+
+ const open = () => {
+ const gen = generation
+ try { socket = new env.WebSocket(`${wsBase(env)}/wss`) } catch (error) {
+ handlers.onStatus({ state: 'error', error: `WeCom could not open a socket: ${error?.message ?? error}` })
+ return
+ }
+ socket.addEventListener('open', () => {
+ sendFrame({ cmd: 'aibot_subscribe', headers: { req_id: nextReqId() }, body: { secret, bot_id: botId } })
+ })
+ socket.addEventListener('message', (event) => {
+ if (stopped || generation !== gen) return
+ let packet
+ try { packet = JSON.parse(String(event.data)) } catch { return }
+ if (packet.errcode !== undefined) {
+ if (packet.errcode !== 0) {
+ handlers.onStatus({ state: 'error', error: String(packet.errmsg ?? `WeCom answered ${packet.errcode}`) })
+ const held = pending.get(packet.headers?.req_id)
+ if (held !== undefined) {
+ pending.delete(packet.headers?.req_id)
+ held.reject(Object.assign(new Error(String(packet.errmsg ?? 'WeCom refused')), { permanent: true }))
+ }
+ return
+ }
+ if (packet.headers?.req_id !== undefined && pending.has(packet.headers.req_id)) {
+ const held = pending.get(packet.headers.req_id)
+ pending.delete(packet.headers.req_id)
+ held.resolve(packet.body)
+ }
+ handlers.onStatus({ state: 'ready', account: { id: botId, name: botId } })
+ return
+ }
+ if (packet.cmd === 'aibot_msg_callback') {
+ void onCallback(packet.headers, packet.body ?? {}).catch(error => env.log?.warn?.('ds-bot im: wecom message failed: %s', error?.message ?? error))
+ } else if (packet.cmd === 'aibot_event_callback') {
+ void onEvent(packet.headers, packet.body ?? {}).catch(error => env.log?.warn?.('ds-bot im: wecom event failed: %s', error?.message ?? error))
+ }
+ })
+ socket.addEventListener('close', () => {
+ clearTimeout(pingTimer)
+ if (stopped || generation !== gen) return
+ handlers.onStatus({ state: 'connecting' })
+ reconnectTimer = setTimeout(() => { if (!stopped) open() }, 2000)
+ reconnectTimer.unref?.()
+ })
+ socket.addEventListener('error', () => {})
+ pingTimer = setInterval(() => { if (!stopped && socket?.readyState === 1) sendFrame({ cmd: 'ping', headers: { req_id: nextReqId() } }) }, 30_000)
+ pingTimer.unref?.()
+ }
+
+ handlers.onStatus({ state: 'connecting' })
+ open()
+
+ return {
+ send: async (chat, { text, buttons }) => {
+ const chunks = chunkMarkdown(String(text ?? ''), TEXT_LIMIT)
+ let messageId
+ for (const [index, chunk] of chunks.entries()) {
+ const body = { msgtype: 'markdown', markdown: { content: chunk } }
+ // Buttons ride a template card on the last chunk.
+ if (index === chunks.length - 1 && buttons?.length > 0) {
+ body.msgtype = 'template_card'
+ body.template_card = {
+ card_type: 'text_notice',
+ main_title: { title: chunk.slice(0, 100) },
+ card_action: { type: 2, url: 'https://work.weixin.qq.com' },
+ button_selection: { question_key: 'choice', option_list: buttons.slice(0, 10).map(b => ({ id: b.data, text: b.label.slice(0, 30) })) },
+ }
+ }
+ const reqId = lastReqId.get(chat.key)
+ if (reqId !== undefined) {
+ sendFrame({ cmd: 'aibot_respond_msg', headers: { req_id: reqId }, body })
+ messageId = undefined
+ } else {
+ const result = await request('aibot_send_msg', { ...body, chatid: chat.kind === 'group' ? chat.key : undefined, userid: chat.kind === 'direct' ? chat.key : undefined })
+ messageId = String(result?.msgid ?? messageId ?? '')
+ }
+ }
+ return { messageId }
+ },
+ stop: () => {
+ stopped = true
+ generation += 1
+ clearTimeout(reconnectTimer)
+ clearTimeout(pingTimer)
+ for (const held of pending.values()) held.reject(new Error('stopped'))
+ pending.clear()
+ try { socket?.close(1000, 'stop') } catch { /* not open */ }
+ },
+ }
+ },
+}
+
+// Images download from their CDN URL and decrypt with the per-link AES-256
+// key (base64).
+async function downloadImage(image, env) {
+ const response = await env.fetch(String(image.url))
+ if (!response.ok) return undefined
+ const encrypted = Buffer.from(await response.arrayBuffer())
+ const key = Buffer.from(String(image.aeskey ?? ''), 'base64')
+ if (key.length !== 32) return undefined
+ const decipher = createDecipheriv('aes-256-cbc', key, key.subarray(0, 16))
+ return Buffer.concat([decipher.update(encrypted), decipher.final()])
+}
diff --git a/ds-bot/test/im-dingtalk.test.js b/ds-bot/test/im-dingtalk.test.js
new file mode 100644
index 00000000..12fdb703
--- /dev/null
+++ b/ds-bot/test/im-dingtalk.test.js
@@ -0,0 +1,134 @@
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { test } from 'node:test'
+import dingtalk from '../src/host/im/platforms/dingtalk.js'
+import { fakeWsServer } from './fake-ws.js'
+
+// A fake DingTalk: gettoken and the gateway REST on HTTP, the stream socket
+// carries SYSTEM pings and CALLBACK frames which must be ACKed.
+async function fakeDingtalk() {
+ const calls = []
+ const packets = []
+ const acks = []
+ const replies = {}
+ const http = createServer((req, res) => {
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const params = JSON.parse(body || '{}')
+ calls.push({ method: req.method, path: req.url, params })
+ if (req.url.startsWith('/gettoken')) {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ errcode: 0, access_token: 'dt-tok', expires_in: 7200 }))
+ return
+ }
+ if (req.url === '/v1.0/gateway/connections/open') {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ endpoint: wss.url.replace('ws://', 'http://').replace(/:\d+$/, ''), ticket: 'tk1', endpoint: `${wss.url}` }))
+ return
+ }
+ if (req.url.startsWith('/webhook/')) {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ errcode: 0, processQueryKey: 'q1' }))
+ return
+ }
+ const answer = replies[req.url] ?? { result: { processQueryKey: 'q2' } }
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify(answer.result))
+ })
+ })
+ const wss = await fakeWsServer({
+ onSocket(ws) {
+ ws.on('message', (raw) => {
+ const packet = JSON.parse(raw)
+ packets.push(packet)
+ if (packet.code === 200) acks.push(packet.headers?.messageId)
+ })
+ ws.send(JSON.stringify({ specVersion: '1.0', type: 'SYSTEM', headers: { appType: 'STREAM', clientId: 'cli-1', messageId: 'sys1', time: '1' }, data: 'ping' }))
+ },
+ })
+ await new Promise(resolve => http.listen(0, '127.0.0.1', resolve))
+ return {
+ api: `http://127.0.0.1:${http.address().port}`,
+ webhook: `http://127.0.0.1:${http.address().port}/webhook/s1`,
+ calls, packets, acks, replies,
+ sockets: wss.sockets,
+ push: (ws, packet) => ws.send(JSON.stringify(packet)),
+ close: () => { wss.close(); http.closeAllConnections?.(); http.close() },
+ }
+}
+
+const env = (fake) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: { api: fake.api, gateway: fake.api, oapi: fake.api },
+ runtime: { get: () => ({}), set: () => {} },
+ log: { warn: (...args) => console.error('[im-dingtalk]', ...args) },
+})
+const FIELDS = { clientId: 'cli-1', clientSecret: 'sec-1' }
+
+const until = async (fn, tries = 80) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 50))
+ }
+ return undefined
+}
+
+const callback = (d, id = 'cb1') => ({ specVersion: '1.0', type: 'CALLBACK', headers: { appType: 'STREAM', clientId: 'cli-1', messageId: id, time: '1' }, data: JSON.stringify(d) })
+
+test('check gets an app token', async () => {
+ const fake = await fakeDingtalk()
+ const { account } = await dingtalk.check(FIELDS, env(fake))
+ assert.equal(account.id, 'cli-1')
+ assert.ok(fake.calls.some(call => call.path.startsWith('/gettoken')))
+ await fake.close()
+})
+
+test('system pings get a pong, a single chat and an @ group message land, every frame is ACKed', async (t) => {
+ const fake = await fakeDingtalk()
+ const messages = []
+ const handle = dingtalk.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.calls.some(call => call.path === '/v1.0/gateway/connections/open'))
+ // The ping sent on connect gets a pong ACK.
+ await until(() => fake.acks.includes('sys1'))
+ fake.push(ws, callback({ conversationType: '1', senderStaffId: 'u1', senderNick: 'Fei', text: { content: 'hello' }, msgtype: 'text', msgId: 'm1', sessionWebhook: fake.webhook }, 'cb1'))
+ fake.push(ws, callback({ conversationType: '2', conversationId: 'g1', senderStaffId: 'u2', text: { content: 'ping' }, msgtype: 'text', msgId: 'm2', isInAtList: true }, 'cb2'))
+ fake.push(ws, callback({ conversationType: '2', conversationId: 'g1', senderStaffId: 'u2', text: { content: 'noise' }, msgtype: 'text', msgId: 'm3', isInAtList: false }, 'cb3'))
+ await until(() => messages.length === 3 && fake.acks.length === 4)
+ assert.equal(messages[0].chat.kind, 'direct')
+ assert.equal(messages[1].chat.kind, 'group')
+ assert.equal(messages[1].mentioned, true)
+ assert.equal(messages[2].mentioned, false)
+})
+
+test('send replies through the sessionWebhook when live, else the robot API', async (t) => {
+ const fake = await fakeDingtalk()
+ const messages = []
+ const handle = dingtalk.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ fake.push(ws, callback({ conversationType: '1', senderStaffId: 'u1', text: { content: 'hi' }, msgtype: 'text', msgId: 'm1', sessionWebhook: fake.webhook }, 'cb1'))
+ await until(() => messages.length === 1)
+ await handle.send({ key: 'u1', kind: 'direct' }, { text: 'answer' })
+ assert.ok(fake.calls.some(call => call.path.startsWith('/webhook/')), 'replied through the sessionWebhook')
+ // A chat without a webhook goes through batchSend.
+ await handle.send({ key: 'u9', kind: 'direct' }, { text: 'push' })
+ assert.ok(fake.calls.some(call => call.path === '/v1.0/robot/oToMessages/batchSend'), 'robot batchSend used')
+ const post = fake.calls.find(call => call.path === '/v1.0/robot/oToMessages/batchSend')
+ assert.equal(post.params.msgKey, 'sampleMarkdown')
+ assert.deepEqual(post.params.userIds, ['u9'])
+})
+
+test('a dropped socket reconnects', async (t) => {
+ const fake = await fakeDingtalk()
+ const handle = dingtalk.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ ws.close()
+ await until(() => fake.sockets.length === 2)
+ assert.ok(fake.calls.filter(call => call.path === '/v1.0/gateway/connections/open').length >= 2)
+})
diff --git a/ds-bot/test/im-wecom.test.js b/ds-bot/test/im-wecom.test.js
new file mode 100644
index 00000000..c865800e
--- /dev/null
+++ b/ds-bot/test/im-wecom.test.js
@@ -0,0 +1,107 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import wecom from '../src/host/im/platforms/wecom.js'
+import { fakeWsServer } from './fake-ws.js'
+
+// A fake WeCom stream: aibot_subscribe gets an errcode 0 reply, callbacks get
+// pushed frames, aibot_send_msg answers through pending req_ids.
+async function fakeWecom() {
+ const packets = []
+ const wss = await fakeWsServer({
+ onSocket(ws) {
+ ws.on('message', (raw) => {
+ const packet = JSON.parse(raw)
+ packets.push(packet)
+ if (packet.cmd === 'aibot_subscribe') {
+ ws.send(JSON.stringify({ headers: { req_id: packet.headers.req_id }, errcode: 0, errmsg: 'ok' }))
+ }
+ if (packet.cmd === 'aibot_send_msg') {
+ ws.send(JSON.stringify({ headers: { req_id: packet.headers.req_id }, errcode: 0, errmsg: 'ok', body: { msgid: 'w1' } }))
+ }
+ })
+ },
+ })
+ return {
+ url: `${wss.url}/wss`,
+ packets,
+ sockets: wss.sockets,
+ push: (ws, packet) => ws.send(JSON.stringify(packet)),
+ close: () => wss.close(),
+ }
+}
+
+const env = (fake) => ({
+ fetch: globalThis.fetch,
+ WebSocket: globalThis.WebSocket,
+ config: { gateway: fake.url.replace('/wss', '') },
+ runtime: { get: () => ({}), set: () => {} },
+ log: { warn: (...args) => console.error('[im-wecom]', ...args) },
+})
+const FIELDS = { botId: 'bot-1', secret: 'sec-1' }
+
+const until = async (fn, tries = 80) => {
+ for (let at = 0; at < tries; at += 1) {
+ const value = await fn()
+ if (value !== undefined && value !== false) return value
+ await new Promise(done => setTimeout(done, 50))
+ }
+ return undefined
+}
+
+test('the socket subscribes with the bot id and secret and goes ready', async (t) => {
+ const fake = await fakeWecom()
+ const statuses = []
+ const handle = wecom.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: status => statuses.push(status) })
+ t.after(() => { handle.stop(); fake.close() })
+ await until(() => fake.packets.some(packet => packet.cmd === 'aibot_subscribe'))
+ const subscribe = fake.packets.find(packet => packet.cmd === 'aibot_subscribe')
+ assert.equal(subscribe.body.bot_id, 'bot-1')
+ assert.equal(subscribe.body.secret, 'sec-1')
+ await until(() => statuses.some(status => status.state === 'ready'))
+})
+
+test('a single chat is direct, a template-card event reports the action', async (t) => {
+ const fake = await fakeWecom()
+ const messages = []
+ const actions = []
+ const handle = wecom.connect(FIELDS, env(fake), {
+ onMessage: async msg => { messages.push(msg) },
+ onAction: async action => { actions.push(action) },
+ onStatus: () => {},
+ })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ await until(() => fake.packets.some(packet => packet.cmd === 'aibot_subscribe'))
+ fake.push(ws, { cmd: 'aibot_msg_callback', headers: { req_id: 'req-1' }, body: { msgid: 'm1', msgtype: 'text', chattype: 'single', from: { userid: 'u1' }, text: { content: 'hello' } } })
+ fake.push(ws, { cmd: 'aibot_event_callback', headers: { req_id: 'req-2' }, body: { msgid: 'm2', chattype: 'single', from: { userid: 'u1' }, event: { event_type: 'template_card_event', template_card_event: { event_key: 'q:q1:0', userid: 'u1' } } } })
+ await until(() => messages.length === 1 && actions.length === 1)
+ assert.equal(messages[0].chat.kind, 'direct')
+ assert.equal(messages[0].chat.key, 'u1')
+ assert.equal(actions[0].data, 'q:q1:0')
+})
+
+test('a send replies through the callback req_id, and after that window aibot_send_msg', async (t) => {
+ const fake = await fakeWecom()
+ const messages = []
+ const handle = wecom.connect(FIELDS, env(fake), { onMessage: async msg => { messages.push(msg) }, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ fake.push(ws, { cmd: 'aibot_msg_callback', headers: { req_id: 'req-9' }, body: { msgid: 'm1', msgtype: 'text', chattype: 'single', from: { userid: 'u1' }, text: { content: 'hi' } } })
+ await until(() => messages.length === 1)
+ await handle.send({ key: 'u1', kind: 'direct' }, { text: 'answer' })
+ await until(() => fake.packets.some(packet => packet.cmd === 'aibot_respond_msg'))
+ const respond = fake.packets.find(packet => packet.cmd === 'aibot_respond_msg')
+ assert.ok(respond, 'responded through the callback')
+ assert.equal(respond.headers.req_id, 'req-9')
+ assert.equal(respond.body.msgtype, 'markdown')
+})
+
+test('a dropped socket reconnects and subscribes again', async (t) => {
+ const fake = await fakeWecom()
+ const handle = wecom.connect(FIELDS, env(fake), { onMessage: () => {}, onAction: () => {}, onStatus: () => {} })
+ t.after(() => { handle.stop(); fake.close() })
+ const ws = await until(() => fake.sockets[0])
+ ws.close()
+ await until(() => fake.sockets.length === 2)
+ await until(() => fake.packets.filter(packet => packet.cmd === 'aibot_subscribe').length === 2)
+})