🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(bot): add DingTalk (钉钉) as an IM bot channel (#22336)
Rdmclin2512559fbb700
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex af347e02ae9..1b3d176ab43 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -39,6 +39,12 @@ export const RedisKeyNamespace = {* silent-wake budget and the per-channel wake scheduler.*/BOT_WAKE: 'bot-wake',+ /**+ * Short-lived reply routes an IM platform hands out with an inbound message+ * (DingTalk's `sessionWebhook`), kept so the process that posts the reply+ * can use them even when another one received the message.+ */+ BOT_REPLY: 'bot-reply',/*** AI generation related keys (agent welcome, placeholders, etc.)*/@@ -102,6 +108,15 @@ export const RedisKeys = {nightlyTopics: (userId: string, localDate: string): string =>`nightly_topics:v1:${userId}:${localDate}`,},+ /** Bot reply-route scope — see {@link RedisKeyNamespace.BOT_REPLY}. */+ botReply: {+ /**+ * Latest DingTalk `sessionWebhook` for one conversation of one bot.+ * Full key: bot-reply:dingtalk_session_webhook:v1:{applicationId}:{threadId}+ */+ dingtalkSessionWebhook: (applicationId: string, threadId: string): string =>+ `dingtalk_session_webhook:v1:${applicationId}:${threadId}`,+ },/*** Bot-wake scope — see {@link RedisKeyNamespace.BOT_WAKE}. `{key}` is a channel or thread key* built by the bot-wake scenario (`platform:applicationId:channel[:thread]`).@@ -303,6 +318,7 @@ export const RedisKeyScopeNamespace = {agentSignal: RedisKeyNamespace.AGENT_SIGNAL,agentSteer: RedisKeyNamespace.AGENT_STEER,aiGeneration: RedisKeyNamespace.AI_GENERATION,+ botReply: RedisKeyNamespace.BOT_REPLY,botWake: RedisKeyNamespace.BOT_WAKE,integrations: RedisKeyNamespace.INTEGRATIONS,lobechat: RedisKeyNamespace.LOBEHUB,diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.tsindex 067e451d7f7..8d53b7902e9 100644--- a/apps/server/src/routers/lambda/agentBotProvider.ts+++ b/apps/server/src/routers/lambda/agentBotProvider.ts@@ -31,6 +31,7 @@ import {formatFieldFormatViolations,mergeWithDefaults,platformRegistry,+ restrictPlatformToWebhook,withResolvedConcurrencySettings,} from '@/server/services/bot/platforms';import {@@ -39,6 +40,7 @@ import {} from '@/server/services/bot/platforms/feishu/registration';import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';import { GatewayService } from '@/server/services/gateway';+import { isMessageGatewayHostingUnavailable } from '@/server/services/gateway/nodeGatewayOnly';import { getReplyConnectionUnavailableReason } from '@/server/services/gateway/replyConnectionHost';import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';@@ -172,14 +174,20 @@ const withFormSettings = (platform: string, settings?: Record<string, unknown>)export const agentBotProviderRouter = router({listPlatforms: authedProcedure.query(async ({ ctx }) => {+ const { useMessageGateway } = new GatewayService();+// A platform that replies over its own connection only runs where something here can hold// that connection (see `resolveReplyConnectionHost`). Elsewhere it is marked, not dropped, so// a bot configured before the deployment changed can still be opened and removed.return Promise.all(platformRegistry.listSerializedPlatforms().map((platform) => {- const unavailableReason = getReplyConnectionUnavailableReason(platform);+ const offered =+ useMessageGateway && isMessageGatewayHostingUnavailable(platform)+ ? restrictPlatformToWebhook(platform)+ : platform;+ const unavailableReason = getReplyConnectionUnavailableReason(offered);return withBotPlatformAccessMeta(- unavailableReason ? { ...platform, unavailableReason } : platform,+ unavailableReason ? { ...offered, unavailableReason } : offered,{userId: ctx.userId,workspaceId: ctx.workspaceId ?? undefined,diff --git a/apps/server/src/services/bot/AgentBridgeService/index.dingtalk.test.ts b/apps/server/src/services/bot/AgentBridgeService/index.dingtalk.test.tsnew file mode 100644index 00000000000..ddfec7611f3--- /dev/null+++ b/apps/server/src/services/bot/AgentBridgeService/index.dingtalk.test.ts@@ -0,0 +1,198 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createClient, createMessage, createThread, FAKE_DB, USER_ID } from './testUtils';++const mockGetUserSettings = vi.hoisted(() => vi.fn());+const mockExecAgent = vi.hoisted(() => vi.fn());+const mockFormatPrompt = vi.hoisted(() => vi.fn());+const mockGetPlatform = vi.hoisted(() => vi.fn());+const mockIsQueueAgentRuntimeEnabled = vi.hoisted(() => vi.fn());+const mockTopicFindById = vi.hoisted(() => vi.fn());+const mockIsRunningOperationAlive = vi.hoisted(() => vi.fn());+const mockDeferBotMessages = vi.hoisted(() => vi.fn());+const mockIsDeferredMessagesAvailable = vi.hoisted(() => vi.fn());++const mockReplayBot = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const mockReplayMessenger = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('../BotMessageRouter', () => ({+ getBotMessageRouter: () => ({ replayDeferredMessages: mockReplayBot }),+}));+vi.mock('@/server/services/messenger/MessengerRouter', () => ({+ getMessengerRouter: () => ({ replayDeferredMessages: mockReplayMessenger }),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return {+ findById: mockTopicFindById,+ isRunningOperationAlive: mockIsRunningOperationAlive,+ };+ }),+}));++vi.mock('@/server/services/bot/deferredMessages', () => ({+ deferBotMessages: mockDeferBotMessages,+ isDeferredMessagesAvailable: mockIsDeferredMessagesAvailable,+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function () {+ return {+ getUserSettings: mockGetUserSettings,+ };+ }),+}));++vi.mock('@/envs/app', () => ({+ appEnv: {+ APP_URL: '',+ INTERNAL_APP_URL: '',+ },+}));++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(function () {+ return {+ execAgent: mockExecAgent,+ };+ }),+}));++vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({+ getMessageGatewayClient: vi.fn().mockReturnValue({ isConfigured: false, isEnabled: false }),+}));++vi.mock('@/server/services/queue/impls', () => ({+ isQueueAgentRuntimeEnabled: mockIsQueueAgentRuntimeEnabled,+}));++vi.mock('@/server/services/systemAgent', () => ({+ SystemAgentService: vi.fn(),+}));++vi.mock('@/server/services/bot/formatPrompt', () => ({+ buildBotSender: vi.fn((message: any, platform: string) => ({+ fullName: message?.author?.fullName,+ id: message?.author?.userId,+ platform,+ })),+ formatPrompt: mockFormatPrompt,+}));++vi.mock('@/server/services/bot/platforms', async (importOriginal) => {+ const actual = (await importOriginal()) as Record<string, unknown>;+ return {+ ...actual,+ platformRegistry: {+ getPlatform: mockGetPlatform,+ },+ };+});++const { AgentBridgeService } = await import('./index');++/**+ * DingTalk conversations through the shared bridge: a single chat or a group+ * @-mention starts a topic, the topic id is kept in the chat SDK thread state,+ * and the next message in the same conversation continues that topic. The+ * completion hooks carry the DingTalk thread id, which is what the bot+ * callback uses to post the reply back into the same chat.+ */+const SINGLE_THREAD = 'dingtalk:single:manager1234';+const GROUP_THREAD = 'dingtalk:group:cidMockGroup==';++const dingtalkThread = (id: string, state?: Record<string, unknown>) => ({+ ...createThread(state),+ id,+ isDM: id.startsWith('dingtalk:single:'),+});++describe('AgentBridgeService with DingTalk conversations', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockExecAgent.mockResolvedValue({+ assistantMessageId: 'assistant-msg-1',+ createdAt: new Date().toISOString(),+ operationId: 'op-1',+ topicId: 'topic-dingtalk-1',+ });+ mockFormatPrompt.mockReturnValue('formatted prompt');+ mockGetPlatform.mockReturnValue({+ id: 'dingtalk',+ name: 'DingTalk',+ supportsMessageEdit: false,+ });+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });+ mockIsQueueAgentRuntimeEnabled.mockReturnValue(true);+ mockTopicFindById.mockResolvedValue({+ agentId: 'agent-1',+ id: 'topic-dingtalk-1',+ updatedAt: new Date(),+ });+ mockIsRunningOperationAlive.mockResolvedValue(false);+ mockIsDeferredMessagesAvailable.mockReturnValue(true);+ mockDeferBotMessages.mockResolvedValue(true);+ });++ it.each([+ ['single chat', SINGLE_THREAD],+ ['group @-mention', GROUP_THREAD],+ ])(+ 'a %s starts a topic, stores it on the thread, and hooks the reply to that thread',+ async (_label, threadId) => {+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const thread = dingtalkThread(threadId);++ await service.handleMention(thread as any, createMessage(), {+ agentId: 'agent-1',+ botContext: {+ applicationId: 'dingapp',+ platform: 'dingtalk',+ platformThreadId: threadId,+ } as any,+ client: createClient(),+ });++ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ const params = mockExecAgent.mock.calls[0][0];+ // A first message has no topic yet — the run creates one.+ expect(params.appContext?.topicId).toBeUndefined();+ expect(params.hooks).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: 'bot-completion',+ type: 'onComplete',+ webhook: expect.objectContaining({+ body: expect.objectContaining({ platformThreadId: threadId, type: 'completion' }),+ }),+ }),+ ]),+ );+ expect(thread.subscribe).toHaveBeenCalled();+ expect(thread.setState).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic-dingtalk-1' }),+ );+ },+ );++ it.each([+ ['single chat', SINGLE_THREAD],+ ['group', GROUP_THREAD],+ ])('a follow-up in the same %s continues the stored topic', async (_label, threadId) => {+ const service = new AgentBridgeService(FAKE_DB, USER_ID);+ const thread = dingtalkThread(threadId, { topicId: 'topic-dingtalk-1' });++ await service.handleSubscribedMessage(thread as any, createMessage(), {+ agentId: 'agent-1',+ botContext: {+ applicationId: 'dingapp',+ platform: 'dingtalk',+ platformThreadId: threadId,+ } as any,+ client: createClient(),+ });++ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ expect(mockExecAgent.mock.calls[0][0].appContext?.topicId).toBe('topic-dingtalk-1');+ });+});diff --git a/apps/server/src/services/bot/BotMessageRouter/index.mockDingTalk.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.mockDingTalk.test.tsnew file mode 100644index 00000000000..3191d10df56--- /dev/null+++ b/apps/server/src/services/bot/BotMessageRouter/index.mockDingTalk.test.ts@@ -0,0 +1,449 @@+// @vitest-environment node+import { signCallback } from '@lobechat/chat-adapter-dingtalk';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { platformRegistry } from '../platforms';+import { BotMessageRouter } from './index';+import {+ makeProvider,+ mockAgentBridgeServiceCtor,+ mockFindEnabledByPlatform,+ mockGetAgentRuntimeRedisClient,+ mockHandleMention,+ mockHandleSubscribedMessage,+ resetBotMessageRouterMocks,+} from './testUtils';++/**+ * Mock-DingTalk acceptance for the inbound → agent → outbound chain.+ *+ * Real: `chat` SDK, `@lobechat/chat-adapter-dingtalk` (signature check,+ * single / group parsing, thread ids, sessionWebhook-first send), the DingTalk+ * platform definition and client from the shared `platformRegistry`, and+ * `BotMessageRouter` (on-demand bot load, access gates, mention / subscribed+ * routing into `AgentBridgeService`).+ * Faked: DingTalk itself (`globalThis.fetch`), the provider row, and+ * `AgentBridgeService` — its `handleMention` stands in for the agent run and+ * posts the reply the way each runtime does: `thread.post` (local mode) and+ * `PlatformMessenger.createMessage` (gateway mode, what `BotCallbackService`+ * calls when the agent gateway reports completion).+ */++vi.mock('@/database/core/db-adaptor', async () => (await import('./testUtils')).dbAdaptorModule());+vi.mock('@/database/models/agentBotProvider', async () =>+ (await import('./testUtils')).agentBotProviderModule(),+);+vi.mock('../dmPairingStore', async () => (await import('./testUtils')).dmPairingStoreModule());+vi.mock('@/server/modules/KeyVaultsEncrypt', async () =>+ (await import('./testUtils')).keyVaultsEncryptModule(),+);+vi.mock('@/server/modules/AgentRuntime/redis', async () =>+ (await import('./testUtils')).redisModule(),+);+vi.mock('@/business/server/bot/featureAccess', async () =>+ (await import('./testUtils')).featureAccessModule(),+);+vi.mock('@/envs/app', () => ({+ appEnv: { APP_URL: 'http://localhost:3010', INTERNAL_APP_URL: '' },+}));+vi.mock('../AgentBridgeService', async () =>+ (await import('./testUtils')).agentBridgeServiceModule(),+);+vi.mock('@/server/services/aiAgent', async () => (await import('./testUtils')).aiAgentModule());+vi.mock('@/server/services/agentSignal', () => ({ emitAgentSignalSourceEvent: vi.fn() }));+vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function () {+ return { getUserSettings: vi.fn().mockResolvedValue({ general: { timezone: 'UTC' } }) };+ }),+}));+vi.mock('@/server/services/gateway/runtimeStatus', () => ({+ BOT_RUNTIME_STATUSES: {+ connected: 'connected',+ disconnected: 'disconnected',+ failed: 'failed',+ starting: 'starting',+ },+ getRuntimeStatusErrorMessage: (e: any) => String(e?.message ?? e),+ updateBotRuntimeStatus: vi.fn(),+}));++/**+ * The router only builds chat SDK state when a Redis client exists, so the+ * test hands it a placeholder client and swaps the ioredis state for memory.+ */+const chatState = vi.hoisted(() => ({ current: undefined as any }));+vi.mock('@chat-adapter/state-ioredis', () => ({+ createIoRedisState: () => chatState.current,+}));++/** In-memory stand-in for the `bot-reply` Redis scope. */+const replyRoutes = vi.hoisted(() => new Map<string, { expiresAt: number; url: string }>());+vi.mock('@/server/services/redis', () => ({+ redisService: {+ // Bot-wake bookkeeping is best effort and not under test here.+ botWake: new Proxy({}, { get: () => async () => undefined }),+ botReply: {+ forgetDingTalkSessionWebhook: async (app: string, thread: string) => {+ replyRoutes.delete(`${app}:${thread}`);+ },+ getDingTalkSessionWebhook: async (app: string, thread: string) =>+ replyRoutes.get(`${app}:${thread}`),+ rememberDingTalkSessionWebhook: async (+ app: string,+ thread: string,+ webhook: { expiresAt: number; url: string },+ ) => {+ replyRoutes.set(`${app}:${thread}`, webhook);+ },+ },+ },+}));++/** Minimal in-memory `StateAdapter` (same shape as chatSdkContract.test.ts). */+const createMemoryState = ({ exclusiveLocks = false }: { exclusiveLocks?: boolean } = {}) => {+ const heldLocks = new Set<string>();+ const values = new Map<string, unknown>();+ const lists = new Map<string, unknown[]>();+ const subscribed = new Set<string>();+ const queues = new Map<string, unknown[]>();+ return {+ acquireLock: async (threadId: string) => {+ if (exclusiveLocks) {+ if (heldLocks.has(threadId)) return null;+ heldLocks.add(threadId);+ }+ return { expiresAt: Number.MAX_SAFE_INTEGER, threadId, token: 'token' };+ },+ appendToList: async (key: string, value: unknown) => {+ lists.set(key, [...(lists.get(key) ?? []), value]);+ },+ connect: async () => {},+ delete: async (key: string) => {+ values.delete(key);+ },+ dequeue: async (threadId: string) => queues.get(threadId)?.shift() ?? null,+ disconnect: async () => {},+ enqueue: async (threadId: string, entry: unknown) => {+ const queue = queues.get(threadId) ?? [];+ // Redis stores JSON; structuredClone would preserve fields that Message.toJSON drops.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ queue.push(JSON.parse(JSON.stringify(entry)));+ queues.set(threadId, queue);+ return queue.length;+ },+ extendLock: async () => true,+ forceReleaseLock: async () => {},+ get: async (key: string) => values.get(key) ?? null,+ getList: async (key: string) => lists.get(key) ?? [],+ isSubscribed: async (threadId: string) => subscribed.has(threadId),+ queueDepth: async (threadId: string) => queues.get(threadId)?.length ?? 0,+ releaseLock: async (lock?: { threadId: string }) => {+ if (lock) heldLocks.delete(lock.threadId);+ },+ set: async (key: string, value: unknown) => {+ values.set(key, value);+ },+ setIfNotExists: async (key: string, value: unknown) => {+ if (values.has(key)) return false;+ values.set(key, value);+ return true;+ },+ subscribe: async (threadId: string) => {+ subscribed.add(threadId);+ },+ unsubscribe: async (threadId: string) => {+ subscribed.delete(threadId);+ },+ };+};++// ---------------------------------------------------------------- mock DingTalk+const APP_ID = 'dingmockapp';+const SECRET = 'mock-client-secret';+const BOT_ID = '$:LWCP_v1:$bot';+const STAFF = 'manager1234';+const GROUP = 'cidMockGroup==';++interface DingTalkCall {+ body: any;+ url: string;+}++const dingtalk = {+ calls: [] as DingTalkCall[],+ /** sessionWebhook URLs DingTalk will reject (expired session). */+ expiredSessions: new Set<string>(),+};++const installMockDingTalk = () => {+ vi.stubGlobal('fetch', async (input: any, init?: RequestInit) => {+ const url = String(typeof input === 'string' ? input : (input?.url ?? input));+ const body = typeof init?.body === 'string' ? JSON.parse(init.body) : undefined;+ dingtalk.calls.push({ body, url });++ const json = (status: number, payload: unknown) =>+ new Response(JSON.stringify(payload), {+ headers: { 'content-type': 'application/json' },+ status,+ });++ if (url === 'https://api.dingtalk.com/v1.0/oauth2/accessToken') {+ return body?.appKey === APP_ID && body?.appSecret === SECRET+ ? json(200, { accessToken: 'mock-token', expireIn: 7200 })+ : json(400, { code: 'invalidClientSecret', message: 'bad secret' });+ }+ if (url === 'https://api.dingtalk.com/v1.0/robot/groupMessages/send') {+ return json(200, { processQueryKey: `group-${dingtalk.calls.length}` });+ }+ if (url === 'https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend') {+ return json(200, {+ flowControlledStaffIdList: [],+ invalidStaffIdList: [],+ processQueryKey: `single-${dingtalk.calls.length}`,+ });+ }+ if (url.startsWith('https://oapi.dingtalk.com/robot/sendBySession')) {+ return dingtalk.expiredSessions.has(url)+ ? json(200, { errcode: 300_001, errmsg: 'session expired' })+ : json(200, { errcode: 0, errmsg: 'ok' });+ }+ throw new Error(`mock dingtalk: unexpected outbound request ${url}`);+ });+};++let msgSeq = 0;++/** A robot callback, signed the way the Stream gateway forwards it to the webhook. */+const callback = (overrides: Record<string, unknown>) => {+ msgSeq += 1;+ const payload = {+ chatbotCorpId: 'dingCorp',+ chatbotUserId: BOT_ID,+ conversationId: 'cidSingle==',+ conversationType: '1',+ createAt: Date.now(),+ isInAtList: false,+ msgId: `msg-${msgSeq}`,+ msgtype: 'text',+ robotCode: APP_ID,+ senderCorpId: 'dingCorp',+ senderId: '$:LWCP_v1:$user',+ senderNick: '张三',+ senderStaffId: STAFF,+ sessionWebhook: `https://oapi.dingtalk.com/robot/sendBySession?session=s${msgSeq}`,+ sessionWebhookExpiredTime: Date.now() + 90 * 60 * 1000,+ text: { content: '你好' },+ ...overrides,+ };+ const timestamp = String(Date.now());+ return {+ payload,+ request: new Request(`http://localhost:3010/api/agent/webhooks/dingtalk/${APP_ID}`, {+ body: JSON.stringify(payload),+ headers: {+ 'content-type': 'application/json',+ 'sign': signCallback(timestamp, SECRET),+ timestamp,+ },+ method: 'POST',+ }),+ };+};++const waitFor = async (assertion: () => void, timeoutMs = 3000) => {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ try {+ assertion();+ return;+ } catch (error) {+ if (Date.now() > deadline) throw error;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ }+};++/** The reply the gateway-mode bot callback sends: `client.getMessenger(threadId).createMessage`. */+const postGatewayReply = (platformThreadId: string, text: string) =>+ platformRegistry+ .createClient('dingtalk', {+ applicationId: APP_ID,+ credentials: { clientSecret: SECRET },+ platform: 'dingtalk',+ settings: {},+ })+ .getMessenger(platformThreadId)+ .createMessage(text);++const sendsTo = (prefix: string) => dingtalk.calls.filter((c) => c.url.startsWith(prefix));++describe('mock DingTalk callback drives the real router into the agent bridge and back', () => {+ let router: BotMessageRouter;+ let webhook: (req: Request) => Promise<Response>;++ beforeEach(() => {+ resetBotMessageRouterMocks();+ chatState.current = createMemoryState();+ mockGetAgentRuntimeRedisClient.mockReturnValue({+ get: async () => null,+ set: async () => 'OK',+ });+ replyRoutes.clear();+ dingtalk.calls = [];+ dingtalk.expiredSessions.clear();+ installMockDingTalk();+ mockFindEnabledByPlatform.mockResolvedValue([+ makeProvider({+ agentId: 'agent-dingtalk',+ applicationId: APP_ID,+ credentials: { clientSecret: SECRET },+ id: 'provider-dingtalk',+ platform: 'dingtalk',+ settings: { dmPolicy: 'open', groupPolicy: 'open' },+ userId: 'user-dingtalk',+ }),+ ]);+ router = new BotMessageRouter();+ webhook = router.getWebhookHandler('dingtalk', APP_ID);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('rejects an unsigned callback before any agent work', async () => {+ const { payload } = callback({});+ const response = await webhook(+ new Request(`http://localhost:3010/api/agent/webhooks/dingtalk/${APP_ID}`, {+ body: JSON.stringify(payload),+ method: 'POST',+ }),+ );++ expect(response.status).toBe(401);+ expect(mockHandleMention).not.toHaveBeenCalled();+ });++ it('single chat: routes the DM to the agent, then replies into the same chat', async () => {+ mockHandleMention.mockImplementationOnce(async (thread: any) => {+ await thread.subscribe();+ // Local runtime: the bridge posts through the chat SDK thread → adapter.+ await thread.post({ markdown: '**结论**:可以' });+ });++ const { payload, request } = callback({ text: { content: ' 帮我总结一下' } });+ const response = await webhook(request);+ expect(response.status).toBe(200);++ await waitFor(() => expect(mockHandleMention).toHaveBeenCalledTimes(1));+ const [thread, message, options] = mockHandleMention.mock.calls[0];+ expect(mockAgentBridgeServiceCtor).toHaveBeenCalled();+ expect(thread.id).toBe(`dingtalk:single:${STAFF}`);+ expect(thread.isDM).toBe(true);+ expect(message.text).toBe('帮我总结一下');+ expect(message.author).toMatchObject({ userId: STAFF, userName: '张三' });+ expect(options).toMatchObject({+ agentId: 'agent-dingtalk',+ botContext: expect.objectContaining({+ applicationId: APP_ID,+ platform: 'dingtalk',+ platformThreadId: `dingtalk:single:${STAFF}`,+ }),+ });++ // Local-mode reply used the callback's sessionWebhook.+ await waitFor(() => expect(sendsTo(payload.sessionWebhook)).toHaveLength(1));+ expect(sendsTo(payload.sessionWebhook)[0].body).toMatchObject({+ markdown: { text: '**结论**:可以' },+ msgtype: 'markdown',+ });++ // Gateway-mode reply (BotCallbackService → messenger) finds the same route in Redis.+ await postGatewayReply(`dingtalk:single:${STAFF}`, 'done');+ expect(sendsTo(payload.sessionWebhook)).toHaveLength(2);+ expect(sendsTo(payload.sessionWebhook)[1].body).toMatchObject({+ msgtype: 'text',+ text: { content: 'done' },+ });++ // Once the session expires, the reply falls back to oToMessages/batchSend for this staff id.+ dingtalk.expiredSessions.add(payload.sessionWebhook);+ await postGatewayReply(`dingtalk:single:${STAFF}`, 'after expiry');+ const batch = sendsTo('https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend');+ expect(batch).toHaveLength(1);+ expect(batch[0].body).toMatchObject({+ msgKey: 'sampleText',+ robotCode: APP_ID,+ userIds: [STAFF],+ });+ expect(JSON.parse(batch[0].body.msgParam)).toEqual({ content: 'after expiry' });++ // The follow-up in the now-subscribed DM reuses the conversation (no new mention).+ const followUp = callback({ text: { content: '继续' } });+ await webhook(followUp.request);+ await waitFor(() => expect(mockHandleSubscribedMessage).toHaveBeenCalledTimes(1));+ const [sameThread, followUpMessage] = mockHandleSubscribedMessage.mock.calls[0];+ expect(sameThread.id).toBe(`dingtalk:single:${STAFF}`);+ expect(followUpMessage.text).toBe('继续');+ expect(mockHandleMention).toHaveBeenCalledTimes(1);+ });++ it('group chat: routes the @-mention to the agent, then replies into the group', async () => {+ mockHandleMention.mockImplementationOnce(async (thread: any) => {+ await thread.post('收到');+ });++ const { payload, request } = callback({+ atUsers: [{ dingtalkId: BOT_ID }],+ conversationId: GROUP,+ conversationTitle: '研发群',+ conversationType: '2',+ isInAtList: true,+ text: { content: ' 部署好了吗' },+ });+ await webhook(request);++ await waitFor(() => expect(mockHandleMention).toHaveBeenCalledTimes(1));+ const [thread, message, options] = mockHandleMention.mock.calls[0];+ expect(thread.id).toBe(`dingtalk:group:${GROUP}`);+ expect(thread.isDM).toBe(false);+ expect(message.isMention).toBe(true);+ expect(message.text).toBe('部署好了吗');+ expect(options.botContext).toMatchObject({+ platform: 'dingtalk',+ platformThreadId: `dingtalk:group:${GROUP}`,+ });++ await waitFor(() => expect(sendsTo(payload.sessionWebhook)).toHaveLength(1));+ expect(sendsTo(payload.sessionWebhook)[0].body).toMatchObject({+ msgtype: 'text',+ text: { content: '收到' },+ });++ // Without a live session route, the gateway-mode reply goes to groupMessages/send.+ replyRoutes.clear();+ await postGatewayReply(`dingtalk:group:${GROUP}`, '## 部署完成\n- web: ok');+ const group = sendsTo('https://api.dingtalk.com/v1.0/robot/groupMessages/send');+ expect(group).toHaveLength(1);+ expect(group[0].body).toMatchObject({+ msgKey: 'sampleMarkdown',+ openConversationId: GROUP,+ robotCode: APP_ID,+ });+ expect(JSON.parse(group[0].body.msgParam)).toEqual({+ text: '## 部署完成\n- web: ok',+ title: '部署完成',+ });+ expect(+ dingtalk.calls.some((c) => c.url === 'https://api.dingtalk.com/v1.0/oauth2/accessToken'),+ ).toBe(true);+ });++ it('ignores the robot’s own messages', async () => {+ const { request } = callback({ senderId: BOT_ID });+ await webhook(request);+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(mockHandleMention).not.toHaveBeenCalled();+ expect(mockHandleSubscribedMessage).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts b/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.tsindex b1048fb7949..aab96c24521 100644--- a/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts+++ b/apps/server/src/services/bot/__tests__/agentBotProviderSettings.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {assertWatchKeywordsWritable,@@ -362,6 +362,46 @@ describe('mergeBotSettingsForCreate', () => {expect(settings).not.toHaveProperty('reactionMode');});+ describe('DingTalk behind the message gateway', () => {+ afterEach(() => {+ gatewayState.useMessageGateway = true;+ });++ it('defaults a new bot to webhook mode when the gateway cannot host its Stream connection', async () => {+ gatewayState.useMessageGateway = true;++ expect(+ (await mergeBotSettingsForCreate(dbWith({}), 'agt', 'dingtalk', undefined))?.connectionMode,+ ).toBe('webhook');+ expect(+ (await mergeBotSettingsForCreate(dbWith({}), 'agt', 'dingtalk', {}))?.connectionMode,+ ).toBe('webhook');+ });++ it('keeps the mode the caller chose', async () => {+ gatewayState.useMessageGateway = true;+ const settings = await mergeBotSettingsForCreate(dbWith({}), 'agt', 'dingtalk', {+ connectionMode: 'websocket',+ });++ expect(settings?.connectionMode).toBe('websocket');+ });++ it('keeps Stream mode without the gateway', async () => {+ gatewayState.useMessageGateway = false;+ const settings = await mergeBotSettingsForCreate(dbWith({}), 'agt', 'dingtalk', {});++ expect(settings?.connectionMode).toBe('websocket');+ });++ it('leaves platforms the gateway can host on their default', async () => {+ gatewayState.useMessageGateway = true;+ const settings = await mergeBotSettingsForCreate(dbWith({}), 'agt', 'discord', {});++ expect(settings?.connectionMode).not.toBe('webhook');+ });+ });+it('keeps a heterogeneous agent opted in when the caller turned it on', async () => {const db = dbWith({ heterogeneousProvider: { type: 'codex' } });const settings = await mergeBotSettingsForCreate(db, 'agt', 'discord', {diff --git a/apps/server/src/services/bot/agentBotProviderSettings.ts b/apps/server/src/services/bot/agentBotProviderSettings.tsindex f4cc14fe50f..47c6084ae48 100644--- a/apps/server/src/services/bot/agentBotProviderSettings.ts+++ b/apps/server/src/services/bot/agentBotProviderSettings.ts@@ -10,6 +10,7 @@ import {hasPassiveListeningRule,} from '@/server/services/conversationWake/config';import { GatewayService } from '@/server/services/gateway';+import { isMessageGatewayHostingUnavailable } from '@/server/services/gateway/nodeGatewayOnly';import { resolveReplyConnectionHost } from '@/server/services/gateway/replyConnectionHost';import { getBotMessageRouter } from './BotMessageRouter';@@ -61,8 +62,33 @@ function withNewBotReactionMode(return { ...withDefaults, [REACTION_MODE_KEY]: NEW_BOT_REACTION_MODE };}+const CONNECTION_MODE_KEY = 'connectionMode';++/**+ * Webhook mode for a new bot on a platform the external message gateway cannot host, when the+ * gateway is on and the caller did not pick a mode. The settings form gets the same default from+ * `restrictPlatformToWebhook`; this covers callers that skip the form (the Message tool), whose+ * schema-default persistent mode would otherwise be refused on connect.+ */+function withGatewayConnectionMode(+ platform: string | undefined,+ requested: Record<string, unknown> | undefined,+ merged: Record<string, unknown> | undefined,+): Record<string, unknown> | undefined {+ if (!platform || requested?.[CONNECTION_MODE_KEY] !== undefined) return merged;+ if (!isMessageGatewayHostingUnavailable(platformRegistry.getPlatform(platform))) return merged;+ if (!new GatewayService().useMessageGateway) return merged;++ return {+ ...(merged ?? mergeBotSettingsForPersist(platform, {})),+ [CONNECTION_MODE_KEY]: 'webhook',+ };+}+/*** The settings to persist for a bot being created: {@link mergeBotSettingsForPersist}, with+ * - webhook mode when the external message gateway is on and cannot host the platform's+ * persistent connection ({@link withGatewayConnectionMode}), unless the caller chose a mode.* - status reactions off ({@link NEW_BOT_REACTION_MODE}) when the platform offers them and the* caller did not choose. The schema default stays on, since it is also what a bot saved before* the field existed reads as; only a new bot starts quiet.@@ -77,7 +103,11 @@ export async function mergeBotSettingsForCreate(platform: string | undefined,settings: Record<string, unknown> | undefined,): Promise<Record<string, unknown> | undefined> {- const merged = withNewBotReactionMode(platform, settings);+ const merged = withGatewayConnectionMode(+ platform,+ settings,+ withNewBotReactionMode(platform, settings),+ );const key = BOT_WAKE_SETTING_KEYS.disabled;if (settings?.[key] !== undefined) return merged;// Omitted settings persist as `{}`, where an absent switch reads as on: the defaults are writtendiff --git a/apps/server/src/services/bot/messageTarget.ts b/apps/server/src/services/bot/messageTarget.tsindex 0922c2046f4..7c6db0ce533 100644--- a/apps/server/src/services/bot/messageTarget.ts+++ b/apps/server/src/services/bot/messageTarget.ts@@ -1,5 +1,6 @@import type { MessagePlatformType } from '@lobechat/builtin-tool-message';import type { MessageRuntimeService } from '@lobechat/builtin-tool-message/executionRuntime';+import { DingTalkApiClient } from '@lobechat/chat-adapter-dingtalk';import { LarkApiClient } from '@lobechat/chat-adapter-feishu';import { QQApiClient } from '@lobechat/chat-adapter-qq';import { WechatApiClient } from '@lobechat/chat-adapter-wechat';@@ -15,6 +16,7 @@ import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLinimport { MessengerInstallationModel } from '@/database/models/messengerInstallation';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { mergeWithDefaults, platformRegistry } from '@/server/services/bot/platforms';+import { DingTalkMessageService } from '@/server/services/bot/platforms/dingtalk/service';import { DiscordApi } from '@/server/services/bot/platforms/discord/api';import { DiscordMessageService } from '@/server/services/bot/platforms/discord/service';import { FeishuMessageService } from '@/server/services/bot/platforms/feishu/service';@@ -80,6 +82,16 @@ export const createMessageServiceForCredentials = ('lark',);}+ case 'dingtalk': {+ return new DingTalkMessageService(+ new DingTalkApiClient(+ applicationId,+ credentials.clientSecret,+ credentials.robotCode || applicationId,+ ),+ applicationId,+ );+ }case 'qq': {return new QQMessageService(new QQApiClient(applicationId, credentials.appSecret));}diff --git a/apps/server/src/services/bot/platforms/const.ts b/apps/server/src/services/bot/platforms/const.tsindex afdab96290d..915a97273ae 100644--- a/apps/server/src/services/bot/platforms/const.ts+++ b/apps/server/src/services/bot/platforms/const.ts@@ -40,6 +40,7 @@ export const shouldPostProcessingMessage = (settings?: Record<string, unknown>):* Platforms not listed render no tooltip — only the generic description.*/const USER_ID_TOOLTIP_BY_PLATFORM: Record<string, string> = {+ dingtalk: 'channel.userIdHint.dingtalk',discord: 'channel.userIdHint.discord',// Feishu and Lark share `sharedSchema`, which always passes 'feishu' — the// tooltip copy mentions both products so it reads naturally for either.@@ -96,13 +97,14 @@ export function makeUserIdField(platform?: string): FieldSchema {* itself emits.** Picked per-platform since each platform has a primary audience: Chinese- * platforms (Feishu / QQ / WeChat) ship Chinese strings, the rest ship+ * platforms (DingTalk / Feishu / QQ / WeChat) ship Chinese strings, the rest ship* English. Languages without an entry in the system-string dictionary* gracefully fall back to `DEFAULT_LANG` ('en-US') at render time.*/export type BotReplyLocale = Locales;const PLATFORM_REPLY_LOCALES: Record<string, BotReplyLocale> = {+ dingtalk: 'zh-CN',discord: 'en-US',feishu: 'zh-CN',imessage: 'en-US',diff --git a/apps/server/src/services/bot/platforms/dingtalk/client.test.ts b/apps/server/src/services/bot/platforms/dingtalk/client.test.tsnew file mode 100644index 00000000000..2692615cad8--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/client.test.ts@@ -0,0 +1,484 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ adapter: {+ handleWebhook: vi.fn(),+ startGatewayListener: vi.fn(),+ },+ botReply: {+ forgetDingTalkSessionWebhook: vi.fn(),+ getDingTalkSessionWebhook: vi.fn(),+ rememberDingTalkSessionWebhook: vi.fn(),+ },+ chatInstances: [] as any[],+ updateBotRuntimeStatus: vi.fn(),+}));++vi.mock('@lobechat/chat-adapter-dingtalk', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return {+ ...actual,+ createDingTalkAdapter: vi.fn(() => mocks.adapter),+ };+});++vi.mock('chat', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ class FakeChat {+ adapters: Map<string, any>;+ initialize = vi.fn().mockResolvedValue(undefined);+ shutdown = vi.fn().mockResolvedValue(undefined);+ constructor(config: any) {+ this.adapters = new Map(Object.entries(config.adapters));+ mocks.chatInstances.push(this);+ }+ }+ return { ...actual, Chat: FakeChat };+});++vi.mock('@/server/services/redis', () => ({ redisService: { botReply: mocks.botReply } }));++vi.mock('@/server/services/gateway/runtimeStatus', () => ({+ BOT_RUNTIME_STATUSES: {+ connected: 'connected',+ disconnected: 'disconnected',+ failed: 'failed',+ starting: 'starting',+ },+ getRuntimeStatusErrorMessage: (e: any) => (e ? String(e?.message ?? e) : undefined),+ updateBotRuntimeStatus: mocks.updateBotRuntimeStatus,+}));++const { DingTalkApiError } = await import('@lobechat/chat-adapter-dingtalk');+const { classifyDingTalkCredentialError, DingTalkClientFactory, dingtalkExtractFiles } =+ await import('./client');++const TOKEN_URL = 'https://api.dingtalk.com/v1.0/oauth2/accessToken';++const jsonResponse = (status: number, body: unknown) =>+ new Response(JSON.stringify(body), {+ headers: { 'Content-Type': 'application/json' },+ status,+ });++const fetchMock = vi.fn();++const createClient = (settings: Record<string, unknown> = {}) =>+ new DingTalkClientFactory().createClient(+ {+ applicationId: 'dingapp',+ credentials: { clientSecret: 'secret' },+ platform: 'dingtalk',+ settings,+ },+ { appUrl: 'https://app.example.com' },+ );++const statuses = () => mocks.updateBotRuntimeStatus.mock.calls.map(([arg]) => arg.status);++beforeEach(() => {+ vi.clearAllMocks();+ mocks.chatInstances.length = 0;+ mocks.adapter.startGatewayListener.mockResolvedValue(undefined);+ mocks.botReply.getDingTalkSessionWebhook.mockResolvedValue(undefined);+ mocks.updateBotRuntimeStatus.mockResolvedValue(undefined);+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('DingTalkClientFactory.validateCredentials', () => {+ const factory = new DingTalkClientFactory();++ it('reports every missing field before calling DingTalk', async () => {+ const result = await factory.validateCredentials({ clientSecret: '' }, {}, '');++ expect(result.valid).toBe(false);+ expect(result.errors).toEqual([+ { code: 'missing_credentials', field: 'applicationId', message: 'Client ID is required' },+ { code: 'missing_credentials', field: 'clientSecret', message: 'Client Secret is required' },+ ]);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('accepts credentials once the accessToken endpoint issues a token', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'tok', expireIn: 7200 }));++ const result = await factory.validateCredentials({ clientSecret: 'secret' }, {}, 'dingapp');++ expect(result).toEqual({ valid: true });+ expect(fetchMock).toHaveBeenCalledWith(+ TOKEN_URL,+ expect.objectContaining({+ body: JSON.stringify({ appKey: 'dingapp', appSecret: 'secret' }),+ method: 'POST',+ }),+ );+ });++ it('labels a rejected Client ID / Secret as invalid credentials', async () => {+ fetchMock.mockResolvedValueOnce(+ // Body captured from the real endpoint with a wrong Client ID / Secret.+ jsonResponse(400, {+ code: 'invalidClientIdOrSecret',+ message: '无效的clientId或者clientSecret',+ requestid: '01A1ACCF-8F3D-76EF-97BC-6BAC71012EBE',+ }),+ );++ const result = await factory.validateCredentials({ clientSecret: 'bad' }, {}, 'dingapp');++ expect(result.valid).toBe(false);+ expect(result.errors).toHaveLength(1);+ expect(result.errors![0]).toMatchObject({ code: 'invalid_credentials', field: 'credentials' });+ expect(result.errors![0].message).toMatch(/^Invalid DingTalk Client ID or Client Secret: /);+ expect(result.errors![0].message).toContain('invalidClientIdOrSecret');+ });++ it('labels a forbidden app as permission denied', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse(403, { code: 'Forbidden.AccessDenied.IpNotInWhiteList', message: 'ip denied' }),+ );++ const result = await factory.validateCredentials({ clientSecret: 'secret' }, {}, 'dingapp');++ expect(result.errors![0]).toMatchObject({ code: 'permission_denied', field: 'credentials' });+ expect(result.errors![0].message).toMatch(/^DingTalk denied access for this app: /);+ });++ it('labels an unreachable API as a network failure', async () => {+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));++ const result = await factory.validateCredentials({ clientSecret: 'secret' }, {}, 'dingapp');++ expect(result.errors![0]).toEqual({+ code: 'upstream_unavailable',+ field: 'credentials',+ message: 'Could not reach the DingTalk API: fetch failed',+ });+ });++ it('labels a DingTalk outage as upstream unavailable', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(503, { code: 'system.error', message: 'busy' }));++ const result = await factory.validateCredentials({ clientSecret: 'secret' }, {}, 'dingapp');++ expect(result.errors![0].code).toBe('upstream_unavailable');+ });++ it('labels throttling as rate limited', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(429, { code: 'Throttling', message: 'slow' }));++ const result = await factory.validateCredentials({ clientSecret: 'secret' }, {}, 'dingapp');++ expect(result.errors![0].code).toBe('rate_limited');+ });+});++describe('classifyDingTalkCredentialError', () => {+ const apiError = (status: number, code?: string, kind: any = 'auth') =>+ new DingTalkApiError({ code, kind, message: `DingTalk ${status}`, status });++ it.each([+ [apiError(400, 'invalidClientId'), 'invalid_credentials'],+ [apiError(401, 'InvalidAuthentication'), 'invalid_credentials'],+ [apiError(403, 'Forbidden.AccessDenied'), 'permission_denied'],+ [apiError(400, 'Forbidden.AccessDenied.AccessTokenPermissionDenied'), 'permission_denied'],+ [apiError(429), 'rate_limited'],+ [apiError(400, 'send.too.fast'), 'rate_limited'],+ [apiError(500, undefined, 'server'), 'upstream_unavailable'],+ [new Error('getaddrinfo ENOTFOUND api.dingtalk.com'), 'upstream_unavailable'],+ [+ new DOMException('The operation was aborted due to timeout', 'TimeoutError'),+ 'upstream_unavailable',+ ],+ [new Error('something else'), undefined],+ ])('maps %s to %s', (error, code) => {+ expect(classifyDingTalkCredentialError(error)).toBe(code);+ });+});++describe('DingTalkClientFactory.createClient', () => {+ it('defaults to Stream mode and starts a gateway listener on the webhook route', async () => {+ const client = createClient({ connectionMode: 'websocket' });++ await client.start({ durationMs: 60_000 });++ expect(mocks.adapter.startGatewayListener).toHaveBeenCalledWith(+ { waitUntil: expect.any(Function) },+ 60_000,+ expect.any(AbortSignal),+ 'https://app.example.com/api/agent/webhooks/dingtalk/dingapp',+ );+ expect(statuses()).toEqual(['starting', 'connected']);+ });++ it('treats a row without connectionMode as Stream mode', async () => {+ await createClient().start({ durationMs: 1000 });+ expect(mocks.adapter.startGatewayListener).toHaveBeenCalledTimes(1);+ });++ it('only verifies credentials in HTTP callback mode', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'tok', expireIn: 7200 }));+ const client = createClient({ connectionMode: 'webhook' });++ await client.start();++ expect(mocks.adapter.startGatewayListener).not.toHaveBeenCalled();+ expect(fetchMock).toHaveBeenCalledWith(TOKEN_URL, expect.anything());+ expect(statuses()).toEqual(['starting', 'connected']);++ await client.stop();+ expect(statuses()).toEqual(['starting', 'connected', 'disconnected']);+ });++ it('marks the bot failed when HTTP callback credentials are rejected', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse(400, { code: 'invalidClientId', message: 'x' }));+ const client = createClient({ connectionMode: 'webhook' });++ await expect(client.start()).rejects.toThrow();+ expect(statuses()).toEqual(['starting', 'failed']);+ });+});++describe('DingTalk gateway lifecycle', () => {+ it('marks the bot failed and rethrows when the Stream connection cannot open', async () => {+ mocks.adapter.startGatewayListener.mockRejectedValueOnce(new Error('stream open 401'));+ const client = createClient({ connectionMode: 'websocket' });++ await expect(client.start({ durationMs: 1000 })).rejects.toThrow('stream open 401');+ expect(mocks.updateBotRuntimeStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({ errorMessage: 'stream open 401', status: 'failed' }),+ expect.anything(),+ );+ });++ it('aborts the socket and shuts the bot down on stop', async () => {+ const client = createClient({ connectionMode: 'websocket' });+ await client.start({ durationMs: 1000 });+ const signal = mocks.adapter.startGatewayListener.mock.calls[0][2] as AbortSignal;++ await client.stop();++ expect(signal.aborted).toBe(true);+ expect(mocks.chatInstances[0].shutdown).toHaveBeenCalled();+ expect(statuses().at(-1)).toBe('disconnected');+ });++ it('replaces the previous connection when started again (credential change / refresh)', async () => {+ const client = createClient({ connectionMode: 'websocket' });+ await client.start({ durationMs: 1000 });+ const firstSignal = mocks.adapter.startGatewayListener.mock.calls[0][2] as AbortSignal;++ await client.start({ durationMs: 1000 });++ expect(firstSignal.aborted).toBe(true);+ expect(mocks.chatInstances[0].shutdown).toHaveBeenCalled();+ expect(mocks.chatInstances).toHaveLength(2);+ const secondSignal = mocks.adapter.startGatewayListener.mock.calls[1][2] as AbortSignal;+ expect(secondSignal.aborted).toBe(false);+ });++ it('refreshes itself after the duration when started without gateway options', async () => {+ vi.useFakeTimers();+ try {+ const client = createClient({ connectionMode: 'websocket' });+ await client.start();+ expect(mocks.adapter.startGatewayListener).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(8 * 60 * 60 * 1000);+ await vi.waitFor(() => expect(mocks.adapter.startGatewayListener).toHaveBeenCalledTimes(2));+ await client.stop();+ await vi.advanceTimersByTimeAsync(8 * 60 * 60 * 1000);+ expect(mocks.adapter.startGatewayListener).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('DingTalk messenger', () => {+ const tokenThen = (...responses: Response[]) => {+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { accessToken: 'tok', expireIn: 7200 }));+ for (const response of responses) fetchMock.mockResolvedValueOnce(response);+ };++ const bodyOf = (call: number) => JSON.parse(fetchMock.mock.calls[call][1].body);++ it('replies to a group through groupMessages/send', async () => {+ tokenThen(jsonResponse(200, { processQueryKey: 'pqk' }));+ const messenger = createClient().getMessenger('dingtalk:group:cidABC==');++ await messenger.createMessage('done');++ expect(fetchMock.mock.calls[1][0]).toBe(+ 'https://api.dingtalk.com/v1.0/robot/groupMessages/send',+ );+ expect(bodyOf(1)).toEqual({+ msgKey: 'sampleText',+ msgParam: JSON.stringify({ content: 'done' }),+ openConversationId: 'cidABC==',+ robotCode: 'dingapp',+ });+ });++ it('replies to a single chat through oToMessages/batchSend with markdown', async () => {+ tokenThen(jsonResponse(200, { processQueryKey: 'pqk' }));+ const messenger = createClient().getMessenger('dingtalk:single:staff-1');++ await messenger.createMessage('**结论**:可以');++ expect(fetchMock.mock.calls[1][0]).toBe(+ 'https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend',+ );+ const body = bodyOf(1);+ expect(body.userIds).toEqual(['staff-1']);+ expect(body.msgKey).toBe('sampleMarkdown');+ expect(JSON.parse(body.msgParam)).toMatchObject({ text: '**结论**:可以' });+ });++ it('prefers a stored sessionWebhook and needs no access token for it', async () => {+ mocks.botReply.getDingTalkSessionWebhook.mockResolvedValueOnce({+ expiresAt: Date.now() + 3_600_000,+ url: 'https://oapi.dingtalk.com/robot/sendBySession?session=s1',+ });+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { errcode: 0, errmsg: 'ok' }));+ const messenger = createClient().getMessenger('dingtalk:single:$:LWCP_v1:$ext');++ await messenger.createMessage('hi');++ expect(mocks.botReply.getDingTalkSessionWebhook).toHaveBeenCalledWith(+ 'dingapp',+ 'dingtalk:single:$:LWCP_v1:$ext',+ );+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0][0]).toBe(+ 'https://oapi.dingtalk.com/robot/sendBySession?session=s1',+ );+ expect(bodyOf(0)).toMatchObject({ msgtype: 'text', text: { content: 'hi' } });+ });++ it('drops a rejected sessionWebhook and falls back to the OpenAPI', async () => {+ mocks.botReply.getDingTalkSessionWebhook.mockResolvedValueOnce({+ expiresAt: Date.now() + 3_600_000,+ url: 'https://oapi.dingtalk.com/robot/sendBySession?session=old',+ });+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { errcode: 300001, errmsg: 'expired' }));+ tokenThen(jsonResponse(200, { processQueryKey: 'pqk' }));+ const messenger = createClient().getMessenger('dingtalk:group:cid1');++ await messenger.createMessage('fallback');++ expect(mocks.botReply.forgetDingTalkSessionWebhook).toHaveBeenCalledWith(+ 'dingapp',+ 'dingtalk:group:cid1',+ );+ expect(fetchMock.mock.calls[2][0]).toBe(+ 'https://api.dingtalk.com/v1.0/robot/groupMessages/send',+ );+ });++ it('sends an edit as a new message and treats reactions as no-ops', async () => {+ tokenThen(jsonResponse(200, { processQueryKey: 'pqk' }));+ const messenger = createClient().getMessenger('dingtalk:group:cid1');++ await messenger.editMessage('mid', 'updated');+ await messenger.removeReaction('mid', '👀');++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(JSON.parse(bodyOf(1).msgParam)).toEqual({ content: 'updated' });+ });++ it('uses a configured RobotCode for sends', async () => {+ tokenThen(jsonResponse(200, { processQueryKey: 'pqk' }));+ const client = new DingTalkClientFactory().createClient(+ {+ applicationId: 'dingapp',+ credentials: { clientSecret: 'secret', robotCode: 'robot-x' },+ platform: 'dingtalk',+ settings: {},+ },+ {},+ );++ await client.getMessenger('dingtalk:group:cid1').createMessage('x');++ expect(bodyOf(1).robotCode).toBe('robot-x');+ });++ it('extracts the conversation id, keeping colons of encrypted sender ids', () => {+ const client = createClient();+ expect(client.extractChatId('dingtalk:group:cid1==')).toBe('cid1==');+ expect(client.extractChatId('dingtalk:single:$:LWCP_v1:$abc')).toBe('$:LWCP_v1:$abc');+ });++ it('keeps markdown and appends usage stats only when enabled', () => {+ expect(createClient().formatMarkdown!('**a**')).toBe('**a**');+ const stats = { totalCost: 0, totalTokens: 1200 } as any;+ expect(createClient().formatReply!('body', stats)).toBe('body');+ expect(createClient({ showUsageStats: true }).formatReply!('body', stats)).toMatch(/^body\n\n/);+ });+});++describe('dingtalkExtractFiles', () => {+ const api = { getFileDownloadUrl: vi.fn() } as any;++ beforeEach(() => {+ api.getFileDownloadUrl.mockReset();+ api.getFileDownloadUrl.mockImplementation(async (code: string) => `https://dl.example/${code}`);+ });++ const message = (raw: Record<string, unknown>) => ({ raw: { msgId: 'm1', ...raw } }) as any;++ it('returns undefined for plain text', async () => {+ expect(+ await dingtalkExtractFiles(api, message({ msgtype: 'text', text: { content: 'hi' } })),+ ).toBeUndefined();+ expect(api.getFileDownloadUrl).not.toHaveBeenCalled();+ });++ it('resolves every picture of a richText message', async () => {+ const result = await dingtalkExtractFiles(+ api,+ message({+ content: {+ richText: [{ text: 'look' }, { downloadCode: 'a' }, { pictureDownloadCode: 'b' }],+ },+ msgtype: 'richText',+ }),+ );+ expect(result).toEqual([+ { name: undefined, url: 'https://dl.example/a' },+ { name: undefined, url: 'https://dl.example/b' },+ ]);+ });++ it('keeps the file name so the MIME type can be inferred', async () => {+ const result = await dingtalkExtractFiles(+ api,+ message({ content: { downloadCode: 'f', fileName: 'report.pdf' }, msgtype: 'file' }),+ );+ expect(result).toEqual([{ name: 'report.pdf', url: 'https://dl.example/f' }]);+ });++ it.each(['picture', 'audio', 'video'])('resolves a %s download code', async (msgtype) => {+ const result = await dingtalkExtractFiles(+ api,+ message({ content: { downloadCode: 'c' }, msgtype }),+ );+ expect(result).toEqual([{ name: undefined, url: 'https://dl.example/c' }]);+ });++ it('skips codes DingTalk refuses to resolve', async () => {+ api.getFileDownloadUrl.mockRejectedValueOnce(new Error('expired'));+ expect(+ await dingtalkExtractFiles(+ api,+ message({ content: { downloadCode: 'x' }, msgtype: 'picture' }),+ ),+ ).toBeUndefined();+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/client.ts b/apps/server/src/services/bot/platforms/dingtalk/client.tsnew file mode 100644index 00000000000..d4a9b298be0--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/client.ts@@ -0,0 +1,495 @@+import { createIoRedisState } from '@chat-adapter/state-ioredis';+import type { DingTalkAdapter, DingTalkRawMessage } from '@lobechat/chat-adapter-dingtalk';+import {+ createDingTalkAdapter,+ DingTalkApiClient,+ DingTalkApiError,+} from '@lobechat/chat-adapter-dingtalk';+import type { Chat as ChatBot, Message } from 'chat';+import { Chat, ConsoleLogger } from 'chat';+import debug from 'debug';++import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';+import {+ BOT_RUNTIME_STATUSES,+ getRuntimeStatusErrorMessage,+ updateBotRuntimeStatus,+} from '@/server/services/gateway/runtimeStatus';++import { warnAttachmentFailures } from '../attachmentDelivery';+import {+ type BotCredentialErrorCode,+ type BotPlatformRuntimeContext,+ type BotProviderConfig,+ ClientFactory,+ messengerContentText,+ type PlatformClient,+ type PlatformMessenger,+ type UsageStats,+ type ValidationError,+ type ValidationResult,+} from '../types';+import { formatUsageStats } from '../utils';+import { sendDingTalkText } from './send';+import { sendDingTalkAttachments } from './sendAttachments';+import { withSessionWebhookCapture } from './sessionWebhook';+import { parseDingTalkThreadId } from './threadId';++const log = debug('bot-platform:dingtalk:bot');++const CONNECTED_STATUS_TTL_BUFFER_MS = 60 * 1000;+const DEFAULT_DURATION_MS = 8 * 60 * 60 * 1000; // 8 hours++export interface GatewayListenerOptions {+ durationMs?: number;+ waitUntil?: (task: Promise<any>) => void;+}++// ---------- Credential check ----------++/**+ * Map a failed `POST /v1.0/oauth2/accessToken` to a credential error code.+ *+ * The adapter folds every 4xx from the token endpoint into `kind: 'auth'`, but+ * keeps the HTTP status and DingTalk's error `code`, which is what separates+ * "wrong Client ID / Secret" from "the app is not allowed to do this" and+ * from throttling. Anything that never got an answer from DingTalk (DNS,+ * timeout, connection refused) is `upstream_unavailable`.+ */+export function classifyDingTalkCredentialError(+ error: unknown,+): BotCredentialErrorCode | undefined {+ if (error instanceof DingTalkApiError) {+ const code = error.code ?? '';+ if (error.status === 429 || /throttl|too\.?fast|qpslimit|too\.?many/i.test(code))+ return 'rate_limited';+ if (error.status === 403 || /^forbidden/i.test(code)) return 'permission_denied';+ if (error.status >= 500 || code === 'system.error') return 'upstream_unavailable';+ if (error.kind === 'auth' || (error.status >= 400 && error.status < 500))+ return 'invalid_credentials';+ return undefined;+ }++ const detail = getRuntimeStatusErrorMessage(error) ?? '';+ if (+ /fetch failed|ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|timed? ?out|aborted/i.test(+ detail,+ )+ )+ return 'upstream_unavailable';++ return undefined;+}++const CREDENTIAL_ERROR_PREFIX: Partial<Record<BotCredentialErrorCode, string>> = {+ invalid_credentials: 'Invalid DingTalk Client ID or Client Secret',+ permission_denied: 'DingTalk denied access for this app',+ rate_limited: 'DingTalk is rate limiting the access token request',+ upstream_unavailable: 'Could not reach the DingTalk API',+};++/** Resolve the RobotCode the send APIs use: the stored one, else the Client ID. */+const resolveRobotCode = (config: Pick<BotProviderConfig, 'applicationId' | 'credentials'>) =>+ config.credentials.robotCode?.trim() || config.applicationId;++// ---------- Inbound attachments ----------++interface DownloadableItem {+ code: string;+ name?: string;+}++/** The download codes a callback carries, per msgtype (protocol-spec §5.3). */+const collectDownloadCodes = (raw: DingTalkRawMessage): DownloadableItem[] => {+ const content = raw.content;+ switch (raw.msgtype) {+ case 'richText': {+ return (content?.richText ?? [])+ .map((item) => item.downloadCode || item.pictureDownloadCode)+ .filter((code): code is string => !!code)+ .map((code) => ({ code }));+ }+ case 'picture': {+ const code = content?.downloadCode || content?.pictureDownloadCode;+ return code ? [{ code }] : [];+ }+ case 'audio':+ case 'video': {+ return content?.downloadCode ? [{ code: content.downloadCode }] : [];+ }+ case 'file': {+ return content?.downloadCode ? [{ code: content.downloadCode, name: content.fileName }] : [];+ }+ default: {+ return [];+ }+ }+};++/**+ * Resolve the attachments of an inbound DingTalk message.+ *+ * DingTalk ships a `downloadCode`, not a URL, and the adapter's in-memory+ * `fetchData` does not survive the chat SDK's queue serialization — but+ * `message.raw` does. Each code is exchanged for a temporary download URL+ * (`robot/messageFiles/download`); `ingestAttachment` then fetches it and+ * takes the MIME type from the response, which is how images, voice and video+ * get classified (DingTalk sends no MIME type with them).+ */+export async function dingtalkExtractFiles(+ api: DingTalkApiClient,+ message: Message,+): Promise<AttachmentSource[] | undefined> {+ const raw = (message as any).raw as DingTalkRawMessage | undefined;+ if (!raw) return undefined;++ const items = collectDownloadCodes(raw);+ if (items.length === 0) return undefined;++ log('extractFiles: msgId=%s, msgtype=%s, items=%d', raw.msgId, raw.msgtype, items.length);++ const results: AttachmentSource[] = [];+ for (const item of items) {+ try {+ const url = await api.getFileDownloadUrl(item.code);+ if (url) results.push({ name: item.name, url });+ } catch (error) {+ log('extractFiles: failed to resolve downloadCode for msgId=%s: %O', raw.msgId, error);+ }+ }++ return results.length > 0 ? results : undefined;+}++// ---------- Clients ----------++/**+ * Behaviour shared by both connection modes: outbound messaging, inbound+ * attachment resolution and formatting. Only the lifecycle differs.+ */+abstract class DingTalkClientBase implements PlatformClient {+ readonly id = 'dingtalk';+ readonly applicationId: string;++ protected config: BotProviderConfig;+ protected context: BotPlatformRuntimeContext;+ /** Lazy-cached so the access token cache stays hot across sends. */+ private _api?: DingTalkApiClient;++ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {+ this.config = config;+ this.context = context;+ this.applicationId = config.applicationId;+ }++ protected get api(): DingTalkApiClient {+ if (!this._api) {+ this._api = new DingTalkApiClient(+ this.config.applicationId,+ this.config.credentials.clientSecret,+ resolveRobotCode(this.config),+ );+ }+ return this._api;+ }++ abstract start(options?: GatewayListenerOptions): Promise<void>;+ abstract stop(): Promise<void>;++ protected buildAdapter(): DingTalkAdapter {+ return withSessionWebhookCapture(+ createDingTalkAdapter({+ clientId: this.config.applicationId,+ clientSecret: this.config.credentials.clientSecret,+ robotCode: resolveRobotCode(this.config),+ }),+ this.applicationId,+ this.config.credentials.clientSecret,+ );+ }++ createAdapter(): Record<string, any> {+ return { dingtalk: this.buildAdapter() };+ }++ getMessenger(platformThreadId: string): PlatformMessenger {+ const conversation = parseDingTalkThreadId(platformThreadId);+ const send = (text: string) =>+ sendDingTalkText(this.api, this.applicationId, conversation, text).then(() => undefined);++ return {+ createMessage: async (content) => {+ const text = messengerContentText(content);+ const attachments = typeof content === 'string' ? undefined : content.attachments;+ if (attachments?.length) {+ const result = await sendDingTalkAttachments(+ this.api,+ this.applicationId,+ conversation,+ attachments,+ text,+ );+ warnAttachmentFailures('bot-platform:dingtalk:createMessage', result.failures);+ return;+ }+ await send(text);+ },+ // Robot text/markdown messages cannot be edited — send a new message.+ editMessage: (_messageId, content) => send(messengerContentText(content)),+ // DingTalk robots have no reaction or typing API.+ removeReaction: () => Promise.resolve(),+ };+ }++ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {+ return dingtalkExtractFiles(this.api, message);+ }++ extractChatId(platformThreadId: string): string {+ return parseDingTalkThreadId(platformThreadId).id;+ }++ /** DingTalk renders markdown natively (`sampleMarkdown`). */+ formatMarkdown(markdown: string): string {+ return markdown;+ }++ formatReply(body: string, stats?: UsageStats): string {+ if (!stats || !this.config.settings?.showUsageStats) return body;+ return `${body}\n\n${formatUsageStats(stats)}`;+ }++ parseMessageId(compositeId: string): string {+ return compositeId;+ }+}++/**+ * Stream mode: holds an outbound WebSocket to DingTalk. Callbacks are ACKed+ * on the socket and forwarded, signed, to `/api/agent/webhooks/dingtalk/:appId`+ * so they run through the same `handleWebhook()` pipeline as HTTP callbacks.+ *+ * Lifecycle mirrors the Feishu / QQ websocket clients: `start()` replaces any+ * previous connection, marks the runtime status, and — when started without+ * gateway-manager options — refreshes itself after `durationMs`; `stop()`+ * aborts the socket and marks the bot disconnected. A credential change goes+ * through the generic stop → start, which opens a fresh connection with the+ * new secret (each reconnect registers a new single-use ticket).+ */+class DingTalkGatewayClient extends DingTalkClientBase {+ private abort = new AbortController();+ private bot: ChatBot<any> | null = null;+ private refreshTimer: ReturnType<typeof setTimeout> | null = null;+ private stopped = false;++ async start(options?: GatewayListenerOptions): Promise<void> {+ log('Starting DingTalk bot (stream) appId=%s', this.applicationId);++ this.stopped = false;+ this.abort.abort();+ this.abort = new AbortController();+ const durationMs = options?.durationMs ?? DEFAULT_DURATION_MS;+ const runtimeStatusTtlMs = durationMs + CONNECTED_STATUS_TTL_BUFFER_MS;+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );++ try {+ if (this.bot) {+ await this.bot.shutdown().catch(() => {});+ this.bot = null;+ }++ const chatConfig: any = {+ adapters: { dingtalk: this.buildAdapter() },+ userName: `lobehub-gateway-${this.applicationId}`,+ };++ if (this.context.redisClient) {+ chatConfig.state = createIoRedisState({+ client: this.context.redisClient as any,+ logger: new ConsoleLogger(),+ });+ }++ const bot = new Chat(chatConfig);+ this.bot = bot;+ await bot.initialize();++ const adapter = (bot as any).adapters.get('dingtalk') as DingTalkAdapter;+ const waitUntil = options?.waitUntil ?? ((task: Promise<any>) => task.catch(() => {}));+ const webhookUrl = `${(this.context.appUrl || '').trim()}/api/agent/webhooks/dingtalk/${this.applicationId}`;++ await adapter.startGatewayListener({ waitUntil }, durationMs, this.abort.signal, webhookUrl);++ if (!options) {+ this.refreshTimer = setTimeout(() => {+ if (this.abort.signal.aborted || this.stopped) return;++ log(+ 'DingTalk bot appId=%s duration elapsed (%dh), refreshing...',+ this.applicationId,+ durationMs / 3_600_000,+ );+ this.start().catch((err) => {+ log('Failed to refresh DingTalk bot appId=%s: %O', this.applicationId, err);+ });+ }, durationMs);+ }++ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );++ log('DingTalk bot appId=%s started, webhookUrl=%s', this.applicationId, webhookUrl);+ } catch (error) {+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ },+ { redisClient: this.context.redisClient as any, ttlMs: runtimeStatusTtlMs },+ );+ throw error;+ }+ }++ async stop(): Promise<void> {+ log('Stopping DingTalk bot (stream) appId=%s', this.applicationId);+ this.stopped = true;+ if (this.refreshTimer) {+ clearTimeout(this.refreshTimer);+ this.refreshTimer = null;+ }+ this.abort.abort();+ if (this.bot) {+ await this.bot.shutdown().catch(() => {});+ this.bot = null;+ }+ await updateBotRuntimeStatus(+ {+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ },+ { redisClient: this.context.redisClient as any },+ );+ }+}++/**+ * HTTP callback mode: DingTalk POSTs to the webhook URL configured in the+ * developer console. Nothing is held open, so `start()` only proves the+ * credentials work by fetching an access token.+ */+class DingTalkWebhookClient extends DingTalkClientBase {+ async start(): Promise<void> {+ log('Starting DingTalk bot (webhook) appId=%s', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.starting,+ });++ try {+ await this.api.getAccessToken();++ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.connected,+ });++ log('DingTalk bot (webhook) appId=%s credentials verified', this.applicationId);+ } catch (error) {+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ errorMessage: getRuntimeStatusErrorMessage(error),+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.failed,+ });+ throw error;+ }+ }++ async stop(): Promise<void> {+ log('Stopping DingTalk bot (webhook) appId=%s', this.applicationId);+ await updateBotRuntimeStatus({+ applicationId: this.applicationId,+ platform: this.id,+ status: BOT_RUNTIME_STATUSES.disconnected,+ });+ }+}++// ---------- Factory ----------++export class DingTalkClientFactory extends ClientFactory {+ createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {+ // DingTalk shipped with connectionMode in its schema, so every saved row+ // carries one; Stream mode is the default for anything that does not.+ const mode = (config.settings?.connectionMode as string) || 'websocket';+ if (mode === 'webhook') {+ return new DingTalkWebhookClient(config, context);+ }+ return new DingTalkGatewayClient(config, context);+ }++ async validateCredentials(+ credentials: Record<string, string>,+ _settings?: Record<string, unknown>,+ applicationId?: string,+ ): Promise<ValidationResult> {+ const errors: ValidationError[] = [];++ if (!applicationId?.trim())+ errors.push({+ code: 'missing_credentials',+ field: 'applicationId',+ message: 'Client ID is required',+ });+ if (!credentials.clientSecret?.trim())+ errors.push({+ code: 'missing_credentials',+ field: 'clientSecret',+ message: 'Client Secret is required',+ });++ if (errors.length > 0) return { errors, valid: false };++ try {+ const api = new DingTalkApiClient(applicationId!, credentials.clientSecret);+ await api.getAccessToken();+ return { valid: true };+ } catch (error) {+ // Keep DingTalk's own reason next to the readable prefix: the code tells+ // the UI which hint to show, the detail tells the operator what to fix.+ const code = classifyDingTalkCredentialError(error);+ const detail = getRuntimeStatusErrorMessage(error);+ const prefix =+ (code && CREDENTIAL_ERROR_PREFIX[code]) || 'Failed to authenticate with DingTalk API';+ return {+ errors: [+ {+ code,+ field: 'credentials',+ message: detail ? `${prefix}: ${detail}` : prefix,+ },+ ],+ valid: false,+ };+ }+ }+}diff --git a/apps/server/src/services/bot/platforms/dingtalk/const.ts b/apps/server/src/services/bot/platforms/dingtalk/const.tsnew file mode 100644index 00000000000..e4b455be185--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/const.ts@@ -0,0 +1,27 @@+/**+ * Stream mode is the default: DingTalk recommends it and it needs no public+ * callback URL, so self-hosted deployments behind a firewall still receive+ * messages. HTTP callback mode (`webhook`) stays available for operators that+ * already configured a callback URL in the developer console.+ */+export const DEFAULT_DINGTALK_CONNECTION_MODE = 'websocket';++/**+ * Robot `msgParam` text is capped by bytes (15000, see protocol-spec §6.1),+ * and the adapter truncates at 12000 UTF-8 bytes. 4000 characters stays inside+ * that budget even when every character is a 3-byte CJK glyph.+ */+export const DINGTALK_CHAR_LIMIT = 4000;++/**+ * Client ID (formerly AppKey) and RobotCode are ASCII identifiers (`dingxxxx…`).+ * The pattern rejects pasted whitespace, quotes or a URL in the field, without+ * guessing at a prefix DingTalk might change.+ */+export const DINGTALK_IDENTIFIER_PATTERN = '^[A-Za-z0-9_-]+$';++/** Thread id prefix shared with `@lobechat/chat-adapter-dingtalk`. */+export const DINGTALK_THREAD_PREFIX = 'dingtalk';++/** Only DingTalk-issued reply webhooks are ever stored or called. */+export const DINGTALK_SESSION_WEBHOOK_HOST_PATTERN = /(^|\.)dingtalk\.com$/;diff --git a/apps/server/src/services/bot/platforms/dingtalk/definition.test.ts b/apps/server/src/services/bot/platforms/dingtalk/definition.test.tsnew file mode 100644index 00000000000..97563f18c84--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/definition.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import { maskCredentials } from '../../credentialMasking';+import { getBotReplyLocale } from '../const';+import { platformRegistry } from '../index';+import { PLATFORM_UNSUPPORTED_MESSAGE_APIS } from '../messageCapabilities';+import { resolveConnectionMode } from '../utils';+import { DingTalkClientFactory } from './client';+import { dingtalk } from './definition';++describe('dingtalk platform definition', () => {+ it('is registered in the shared platform registry', () => {+ expect(platformRegistry.getPlatform('dingtalk')).toBe(dingtalk);+ expect(platformRegistry.listPlatforms().map((p) => p.id)).toContain('dingtalk');+ });++ it('serializes without the client factory for the channel UI', () => {+ const serialized = platformRegistry.listSerializedPlatforms().find((p) => p.id === 'dingtalk');+ expect(serialized).toBeDefined();+ expect(serialized).not.toHaveProperty('clientFactory');+ expect(serialized).toMatchObject({+ documentation: { setupGuideUrl: expect.stringContaining('/channels/dingtalk') },+ name: 'DingTalk',+ });+ });++ it('declares markdown replies, no message edits and its unsupported message APIs', () => {+ expect(dingtalk.supportsMarkdown).toBe(true);+ expect(dingtalk.supportsMessageEdit).toBe(false);+ expect(dingtalk.unsupportedMessageApis).toBe(PLATFORM_UNSUPPORTED_MESSAGE_APIS.dingtalk);+ expect(dingtalk.unsupportedMessageApis).toEqual(+ expect.arrayContaining(['reactToMessage', 'getReactions', 'readMessages', 'editMessage']),+ );+ expect(dingtalk.unsupportedMessageApis).not.toContain('sendMessage');+ });++ it('uses Stream mode unless the provider picked HTTP callbacks', () => {+ expect(dingtalk.connectionMode).toBe('websocket');+ expect(resolveConnectionMode(dingtalk, {})).toBe('websocket');+ expect(resolveConnectionMode(dingtalk, { connectionMode: 'webhook' })).toBe('webhook');+ });++ it('leaves its Stream connection to the Node message gateway', () => {+ // Only the Node gateway hosts DingTalk Stream; routed elsewhere, gateway+ // deployments keep DingTalk on Webhook (see isMessageGatewayHostingUnavailable).+ expect(dingtalk.nodeMessageGatewayOnly).toBe(true);+ });++ it('creates clients through the DingTalk factory', () => {+ expect(dingtalk.clientFactory).toBeInstanceOf(DingTalkClientFactory);+ const client = platformRegistry.createClient('dingtalk', {+ applicationId: 'dingapp',+ credentials: { clientSecret: 's' },+ platform: 'dingtalk',+ settings: {},+ });+ expect(client.id).toBe('dingtalk');+ expect(client.applicationId).toBe('dingapp');+ });++ it('replies to system strings in Chinese', () => {+ expect(getBotReplyLocale('dingtalk')).toBe('zh-CN');+ });++ it('masks the Client Secret but keeps RobotCode readable', () => {+ expect(+ maskCredentials('dingtalk', { clientSecret: 'real-secret', robotCode: 'dingrobot' }),+ ).toEqual({ clientSecret: expect.not.stringContaining('real-secret'), robotCode: 'dingrobot' });+ expect(maskCredentials('dingtalk', { clientSecret: '' })).toEqual({ clientSecret: '' });+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/definition.ts b/apps/server/src/services/bot/platforms/dingtalk/definition.tsnew file mode 100644index 00000000000..a3451d58b6d--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/definition.ts@@ -0,0 +1,28 @@+import { channelDocUrl } from '@lobechat/const';++import { PLATFORM_UNSUPPORTED_MESSAGE_APIS } from '../messageCapabilities';+import type { PlatformDefinition } from '../types';+import { DingTalkClientFactory } from './client';+import { DEFAULT_DINGTALK_CONNECTION_MODE } from './const';+import { schema } from './schema';++export const dingtalk: PlatformDefinition = {+ id: 'dingtalk',+ name: 'DingTalk',+ connectionMode: DEFAULT_DINGTALK_CONNECTION_MODE,+ description: 'Connect a DingTalk robot',+ // Stream mode is hosted only by the Node message gateway (protocol-spec §11.4).+ nodeMessageGatewayOnly: true,+ documentation: {+ portalUrl: 'https://open-dev.dingtalk.com/',+ setupGuideUrl: channelDocUrl('dingtalk'),+ },+ schema,+ // Replies go out as `sampleMarkdown` whenever they contain markdown.+ supportsMarkdown: true,+ // Robot messages cannot be edited; step progress is skipped and only the+ // final reply is sent (streaming would need AI cards).+ supportsMessageEdit: false,+ unsupportedMessageApis: PLATFORM_UNSUPPORTED_MESSAGE_APIS.dingtalk,+ clientFactory: new DingTalkClientFactory(),+};diff --git a/apps/server/src/services/bot/platforms/dingtalk/protocol-spec.md b/apps/server/src/services/bot/platforms/dingtalk/protocol-spec.mdnew file mode 100644index 00000000000..b702e28d276--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/protocol-spec.md@@ -0,0 +1,508 @@+# 钉钉企业内部应用机器人通信协议规范++> 适用对象:实现钉钉机器人消息收发的 SDK、网关和独立 Bot,以及 `packages/chat-adapter-dingtalk`。+>+> 整理依据(核对日期 2026-11-05):+>+> - 钉钉开放平台文档:[机器人概述](https://open.dingtalk.com/document/orgapp/robot-overview)、[接收消息](https://open.dingtalk.com/document/orgapp/receive-message)、[回复消息](https://open.dingtalk.com/document/orgapp/robot-reply-and-send-messages)、[单聊批量发送](https://open.dingtalk.com/document/orgapp/chatbots-send-one-on-one-chat-messages-in-batches)、[群聊发送](https://open.dingtalk.com/document/orgapp/the-robot-sends-a-group-message)、[消息类型](https://help.dingtalk.io/open/development/robot-message-type)、[获取企业内部应用 accessToken](https://help.dingtalk.io/open/development/obtain-orgapp-token)、[下载机器人接收消息的文件](https://open.dingtalk.com/document/orgapp/download-the-file-content-of-the-robot-receiving-message)。+> - Stream 协议:[Stream 模式介绍](https://open.dingtalk.com/document/resourcedownload/introduction-to-stream-mode)、[developerpedia/stream/protocol.md](https://github.com/open-dingtalk/developerpedia/blob/main/docs/learn/stream/protocol.md)。+> - 官方 SDK 源码:[dingtalk-stream-sdk-nodejs](https://github.com/open-dingtalk/dingtalk-stream-sdk-nodejs)、[dingtalk-stream-sdk-python `chatbot.py`](https://github.com/open-dingtalk/dingtalk-stream-sdk-python/blob/main/dingtalk_stream/chatbot.py)(字段名以 SDK 为准)。+> - 可行性调研:`docs/development/dingtalk-wecom-channel-feasibility.md`(分支 `docs/dingtalk-wecom-feasibility`)。+>+> 标注约定:「工程建议」来自实现经验,不是服务端协议的一部分;「未核实」表示官方文档没写;「未实测」表示还没在真实企业里验证。本文所有内容目前都是「未实测」。++## 1. 概述++钉钉机器人能力挂在「企业内部应用」下:在开发者后台创建应用、开启机器人能力、发布即可使用,**企业内部应用发布无平台审核**。协议特征:++1. **凭证**:应用的 Client ID(原 AppKey)+ Client Secret(原 AppSecret)。OpenAPI 用二者换 `accessToken`(2 小时),请求头 `x-acs-dingtalk-access-token`;Stream 建连直接用 Client ID/Secret。+2. **收消息**:两种模式二选一 ——HTTP 回调(需公网 HTTPS,`timestamp` + `sign` 头签名)或 **Stream 模式**(客户端出站 WebSocket)。群聊只推送 @ 机器人的消息,单聊推送全部消息。+3. **回复**:回调自带临时 `sessionWebhook`(免 token,支持 @);过期后走 OpenAPI:单聊 `oToMessages/batchSend`,群聊 `groupMessages/send`,二者都需要 `robotCode`。+4. **消息模型**:出站消息用「模板 key + JSON 字符串参数」(`msgKey` + `msgParam`),不支持编辑普通消息;流式输出需要 AI 卡片(本包第一版不做)。++**地址列表**++| 用途 | 地址 |+| ------------------- | ------------------------------------------------------------------------------------- |+| OpenAPI 基座 | `https://api.dingtalk.com` |+| accessToken | `POST https://api.dingtalk.com/v1.0/oauth2/accessToken` |+| Stream 注册 | `POST https://api.dingtalk.com/v1.0/gateway/connections/open` |+| Stream WebSocket | 注册返回的 `endpoint` + `?ticket=...` |+| 单聊发送 | `POST https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend` |+| 群聊发送 | `POST https://api.dingtalk.com/v1.0/robot/groupMessages/send` |+| 文件下载码换 URL | `POST https://api.dingtalk.com/v1.0/robot/messageFiles/download` |+| sessionWebhook 回复 | 回调里的 `sessionWebhook`(形如 `https://oapi.dingtalk.com/robot/sendBySession?...`) |++## 2. 方案选择++### 2.1 为什么选 Stream 模式++| 维度 | HTTP 回调 | Stream 模式(选用) |+| ---------------- | ------------------------------------------------- | ------------------------------------------------------ |+| 公网入口 | 需要公网 HTTPS 地址,用户要在钉钉后台填我们的 URL | **不需要**公网服务器、IP、域名(官方原文) |+| 自部署 LobeHub | 内网部署收不到消息 | 只要能出站访问 `api.dingtalk.com` 即可 |+| 用户配置步骤 | 填 URL + 校验签名 | 后台选「Stream 模式」即可 |+| 与现有渠道一致性 | 与 Slack Events / Telegram webhook 一致 | **与飞书长连接、QQ WebSocket、Slack Socket Mode 一致** |+| 官方态度 | 支持 | 官方推荐 |++结论:钉钉接入走 **Stream 模式**,由 message gateway 维持长连接,把机器人回调转成签名 HTTP POST 投递到 `webhookPath`,复用 `handleWebhook()` 管线 —— 与 `feishu/gateway.ts`、`chat-adapter-qq/src/gateway.ts` 的形态完全一致。`handleWebhook()` 同时兼容 HTTP 回调模式(同一签名算法),自部署用户若坚持用 HTTP 回调也能工作。++### 2.2 自研轻量实现 vs 官方 SDK++**选择:自研轻量实现**(`packages/chat-adapter-dingtalk/src/gateway.ts`,约 330 行,无额外依赖)。理由:++1. **协议很小**:一次 HTTP 注册 + WebSocket + 三类帧(`SYSTEM` / `EVENT` / `CALLBACK`)+ 统一 ACK 格式,自研成本低。+2. **运行时一致**:官方 Node SDK `dingtalk-stream` 依赖 `ws` 与 `axios`;仓库其他 adapter(QQ、飞书 gateway)都使用全局 `fetch` / `WebSocket`,可在 Node 22+ 与 Edge-like 运行时复用,且测试可以直接 stub 全局对象。+3. **生命周期可控**:gateway 需要 `abortSignal`、`durationMs`(由 message gateway 周期性重启)、日志注入、转发签名;官方 SDK 的 `autoReconnect` / `keepAlive` 语义与这些参数需要额外适配。+4. **官方 SDK 仍作为协议参照**:帧结构、`ping` 回显、`disconnect` 处理、重连退避都对齐官方 SDK 行为(见 §4)。++## 3. 认证++### 3.1 获取 accessToken++`POST https://api.dingtalk.com/v1.0/oauth2/accessToken`++```json+{ "appKey": "dingxxxxxxxx", "appSecret": "xxxxxxxx" }+```++响应:++```json+{ "accessToken": "fw8ef8we8f76e6f7s8dxxxx", "expireIn": 7200 }+```++| 字段 | 类型 | 说明 |+| ------------- | -------- | -------------------------- |+| `accessToken` | `string` | 调用 v1.0 OpenAPI 的凭证。 |+| `expireIn` | `number` | 有效期,秒,通常 7200。 |++调用方式:请求头 `x-acs-dingtalk-access-token: {accessToken}`。官方提示不要频繁调用 Token 接口,否则可能被限流。++### 3.2 缓存与刷新(实现:`DingTalkApiClient.getAccessToken`)++- **缓存**:按应用缓存在 `DingTalkApiClient` 实例内,过期时间 = `expireIn - 300s`(提前 5 分钟刷新;若 `expireIn` 很短,至少保留一半有效期)。+- **并发去重**:同一时刻多个调用共享一个 in-flight 请求,避免缓存失效瞬间并发打 Token 接口。+- **被动失效**:业务接口返回 `401`,或错误码为 `InvalidAuthentication` / `invalidParameter.token.invalid` / `Forbidden.AccessDenied.AccessTokenInvalid` 时,清空缓存、重新取 token 并**只重试一次**;重试仍失败则抛出 `kind = 'auth'` 错误。+- **凭证错误**:Token 接口返回任意 4xx 统一映射为 `kind = 'auth'`(例如 Client Secret 填错),供上层在渠道配置校验时提示「凭证无效」。+- Stream 注册接口直接使用 Client ID/Secret,不依赖 accessToken。++## 4. Stream 模式++### 4.1 注册连接++`POST https://api.dingtalk.com/v1.0/gateway/connections/open`++```json+{+ "clientId": "dingxxxxxxxx",+ "clientSecret": "xxxxxxxx",+ "subscriptions": [{ "type": "CALLBACK", "topic": "/v1.0/im/bot/messages/get" }],+ "ua": "lobehub-chat-adapter-dingtalk/0.1.0"+}+```++| 字段 | 说明 |+| ---------------- | ------------------------------------------------------------------------- |+| `subscriptions` | `type` 为 `EVENT`(`topic: "*"`)或 `CALLBACK`(机器人消息 topic 见上)。 |+| `ua` / `localIp` | 可选,排障用。 |++响应 `{ "endpoint": "wss://...", "ticket": "..." }`。**ticket 90 秒有效且只能建一条连接,不得复用**,所以每次重连都必须重新注册。本实现只订阅机器人消息回调,不订阅事件。++### 4.2 建立 WebSocket++连接 `{endpoint}?ticket={ticket}`(ticket 做 URL 编码)。握手成功(`open`)即视为连接可用:`connect()` 在首次 `open` 时 resolve;注册失败、首次握手前 socket 关闭或报错时 reject(凭证错、应用未开启 Stream 模式等可被上层感知)。++一个应用默认最多 50 条连接,多连接时服务端**随机**选一条推送 —— 多实例部署不需要全局单 owner(与企业微信不同)。++### 4.3 帧结构++服务端推送:++```json+{+ "data": "{\"msgId\":\"...\",\"conversationType\":\"1\",...}",+ "headers": {+ "messageId": "c0a8...",+ "topic": "/v1.0/im/bot/messages/get",+ "contentType": "application/json",+ "time": "1793898634773"+ },+ "specVersion": "1.0",+ "type": "CALLBACK"+}+```++`type` 取值 `SYSTEM` / `EVENT` / `CALLBACK`;`data` 是 **JSON 字符串**。++客户端 ACK:++```json+{+ "code": 200,+ "data": "{\"response\":null}",+ "headers": { "messageId": "c0a8...", "contentType": "application/json" },+ "message": "OK"+}+```++`code`:`200` 成功、`404` 不支持该 topic、`500` 内部错误。++### 4.4 帧处理(实现:`DingTalkStreamConnection.handleFrame`)++| 帧 | 处理 |+| --------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |+| `SYSTEM` / `ping` | 原样回显 `data`(含 `opaque`),`code: 200`。 |+| `SYSTEM` / `disconnect` | 服务端约 10 秒后断 TCP;本实现**立即**关闭 socket 并走重连(新 ticket),缩短空窗。无需 ACK。 |+| `SYSTEM` / 其他(`CONNECTED`、`REGISTERED`、`KEEPALIVE`) | 仅记录日志。 |+| `CALLBACK` / `/v1.0/im/bot/messages/get` | **先 ACK**(`{"response":null}`),再把 `data` 原文签名后 POST 到 `webhookUrl`;转发失败只记日志。 |+| `CALLBACK` / 其他 topic | ACK `404 topic not supported`,不转发。 |+| `EVENT` | ACK `{"status":"SUCCESS"}`,避免服务端重推(本实现不订阅事件,属兜底)。 |+| 非 JSON 帧 | 丢弃并记录日志。 |++机器人消息是 **fire-and-forget**:网络超时不会重推。所以 ACK 不能等 Agent 执行完,必须在收到帧后立即回;Agent 执行在 webhook 管线中异步进行。++### 4.5 转发签名++转发请求使用与 HTTP 回调模式**完全相同**的签名,因此 `handleWebhook()` 用一套校验同时覆盖两种来源,且伪造请求无法冒充钉钉消息:++```+timestamp: <Unix ms>+sign: Base64( HmacSHA256( key = clientSecret, message = timestamp + "\n" + clientSecret ) )+```++`handleWebhook()` 校验:缺失或不匹配返回 `401`;`|now - timestamp| > 1 小时` 视为过期(与钉钉 HTTP 回调规则一致);比较使用 `timingSafeEqual`。++### 4.6 心跳与存活检测++- **服务端 `ping` 系统帧**:收到时原样回显即可(协议原文)。+- **空闲连接没有任何帧**:实测一条健康的空闲 Stream 连接 5 分钟内没有收到任何帧(包括 `ping`),所以「多久没收到帧」不能用来判断连接死活,否则会把健康连接反复重连。+- **客户端存活检测**:用 `ws` 客户端发协议层 ping(`pingIntervalMs`,默认 30 秒)。一个周期内没收到 pong 即判定为半开连接:先摘下该 socket、`terminate()`,再立即走重连;被摘下的 socket 之后迟到的 `close` 不再触发重连。实测钉钉服务端会正常回 pong。+ - 官方 Node SDK 的 `keepAlive` 选项(默认关闭)也是发协议层 ping、未收到 pong 即断开,思路相同。++### 4.7 重连++| 触发 | 行为 |+| ------------------------------------------------ | ------------------------------ |+| `disconnect` 系统帧 | 立即关闭当前 socket → 重连 |+| socket 意外关闭(网络、服务端负载均衡) | 重连 |+| 一个 ping 周期内未收到 pong(半开连接) | 摘下 socket → 重连 |+| 重连时注册接口失败或握手前关闭 | 继续按退避重试 |+| `close()`、`abortSignal` 触发、`durationMs` 到期 | 不重连(由调用方决定是否重启) |++- **每次重连都重新调用 `connections/open`**(ticket 单次有效)。+- 退避:`1s × 2^(n-1)`,上限 60 秒,**不设重试次数上限**:上层已把连接视为运行中,放弃重试会让机器人静默离线到下次刷新,所以一直按 60 秒间隔重试,直到恢复或被 `close()`;握手成功后计数清零。+- 首次 `connect()` 失败不会进入重连循环,直接 reject,交给上层把运行状态标为错误。+- 旧 socket 的事件在被替换后一律忽略,避免重复重连。++## 5. 接收消息++### 5.1 回调载荷(`/v1.0/im/bot/messages/get` 的 `data`,或 HTTP 回调 body)++```json+{+ "atUsers": [{ "dingtalkId": "$:LWCP_v1:$bot" }],+ "chatbotCorpId": "dingCorp",+ "chatbotUserId": "$:LWCP_v1:$bot",+ "conversationId": "cidXXXX==",+ "conversationTitle": "研发群",+ "conversationType": "2",+ "createAt": 1793898634773,+ "isAdmin": false,+ "isInAtList": true,+ "msgId": "msgXXXX",+ "msgtype": "text",+ "robotCode": "dingxxxxxxxx",+ "senderCorpId": "dingCorp",+ "senderId": "$:LWCP_v1:$user",+ "senderNick": "张三",+ "senderStaffId": "manager1234",+ "sessionWebhook": "https://oapi.dingtalk.com/robot/sendBySession?session=xxx",+ "sessionWebhookExpiredTime": 1793904034773,+ "text": { "content": " 帮我总结一下" }+}+```++| 字段 | 说明 |+| --------------------------- | ------------------------------------------------------------------------------------- |+| `conversationType` | `"1"` 单聊,`"2"` 群聊(字符串)。 |+| `conversationId` | 会话 ID;群聊时即 `openConversationId`,用于 `groupMessages/send`。 |+| `senderStaffId` | 发送者在企业内的 userId,**单聊主动发送的收件人**。机器人发布后才有;外部联系人没有。 |+| `senderId` | 加密的发送者 ID,始终存在。 |+| `chatbotUserId` | 机器人自身 ID,用于过滤自己发出的消息。 |+| `isInAtList` / `atUsers` | 是否 @ 了机器人 / 被 @ 的用户(`dingtalkId`、`staffId`)。 |+| `sessionWebhook` | 本会话的临时回复地址。 |+| `sessionWebhookExpiredTime` | 过期时间(Unix ms)。有效期文档未写(未核实),官方示例推算约 90 分钟。 |+| `content` | 非文本消息的内容(见 §5.3)。 |++### 5.2 单聊 / 群聊 / @ 机器人的识别++| 场景 | 判定 | thread id | `isMention` |+| ------------ | -------------------------- | --------------------------------- | -------------------------- |+| 单聊 | `conversationType === "1"` | `dingtalk:single:{senderStaffId}` | `isInAtList`(通常 false) |+| 群聊 @机器人 | `conversationType === "2"` | `dingtalk:group:{conversationId}` | **true** |++- 群聊**只会推送 @ 机器人的消息**(协议原文),所以群消息一律视为 mention;不需要也无法拿到群内非 @ 消息。+- 单聊 thread 用 `senderStaffId` 编码,因为它正是 `batchSend` 的收件人;外部联系人缺 `senderStaffId` 时回退到 `senderId`(此时只能经 sessionWebhook 回复,见 §6.4)。+- 群聊 `text.content` 中 DingTalk 已去掉 @机器人 本身,但保留前导空白;解析时 `trim`,并把 `U+2005`(钉钉 @ 后的四分之一空格)规范为普通空格。+- `senderId === chatbotUserId` 的消息直接丢弃,防止自激。+- thread id 解析时只按前两个 `:` 切分,其余部分整体作为 id(`senderId` 自带 `:`)。++### 5.3 消息类型映射(入站)++| `msgtype` | 内容字段 | 映射 |+| ---------- | ------------------------------------------------------------------ | ------------------------------------------------------ |+| `text` | `text.content` | `text` |+| `richText` | `content.richText[]`:`{text}` 或 `{type:'picture', downloadCode}` | 文本片段按顺序拼接为 `text`;每张图片一个 `image` 附件 |+| `picture` | `content.downloadCode`(兼容 `pictureDownloadCode`) | `image` 附件,`text` 为空 |+| `audio` | `content.downloadCode`、`duration`、`recognition` | `text` 取语音识别结果 `recognition`;附 `audio` 附件 |+| `video` | `content.downloadCode`、`duration`、`videoType` | `video` 附件 |+| `file` | `content.downloadCode`、`fileName` | `file` 附件,MIME 按文件名推断 |+| 其他 | — | 有 `text.content` 时按文本处理,否则丢弃 |++- 群里 @ 机器人时收不到 audio、video、file(协议原文),单聊才有。+- 文本为空且没有附件的消息不进入管线。++### 5.4 附件下载++入站附件只有 `downloadCode`,没有 URL:++```+POST /v1.0/robot/messageFiles/download+{ "downloadCode": "...", "robotCode": "dingxxxxxxxx" }+→ { "downloadUrl": "https://..." } // 临时地址+```++Adapter 生成的 `Attachment`:`fetchData()` 先换 URL 再下载;`fetchMetadata.downloadCode` 保留下载码,消息经队列序列化后可据此重建 fetcher。下载码的有效期文档未写(未核实)。++## 6. 发送消息++### 6.1 出站消息模板(`msgKey` + `msgParam`)++| 用途 | `msgKey` | `msgParam` | sessionWebhook 对应 body |+| -------- | ---------------- | --------------------------------- | ---------------------------------------------------- |+| 纯文本 | `sampleText` | `{"content": "..."}` | `{"msgtype":"text","text":{"content":"..."}}` |+| Markdown | `sampleMarkdown` | `{"title": "...", "text": "..."}` | `{"msgtype":"markdown","markdown":{"title","text"}}` |+| 图片 | `sampleImageMsg` | `{"photoURL": "url 或 mediaId"}` | 以 markdown `` 发送 |++其他模板(`sampleLink`、`sampleActionCard*`、文件、音视频)本包暂不使用。++**选择规则(`DingTalkFormatConverter.toOutboundMessage`)**:调用方传 `{ markdown }` / `{ ast }`,或文本中出现 markdown 语法(标题、列表、引用、粗体、行内代码、链接)时发 `sampleMarkdown`,否则发 `sampleText`。Markdown 的 `title` 会显示在通知和会话列表里,取首个非空行去掉 markdown 标记,最多 20 字。++**长度**:`groupMessages/send` 的 `msgParam` 上限 15000 字节;正文按 UTF-8 截断到 12000 字节(预留 JSON 转义余量),按字符边界切并追加 `...`。++### 6.2 单聊:`oToMessages/batchSend`++```json+POST /v1.0/robot/oToMessages/batchSend+x-acs-dingtalk-access-token: {accessToken}+{+ "robotCode": "dingxxxxxxxx",+ "userIds": ["manager1234"],+ "msgKey": "sampleMarkdown",+ "msgParam": "{\"title\":\"结论\",\"text\":\"**结论**:可以\"}"+}+→ { "processQueryKey": "...", "invalidStaffIdList": [], "flowControlledStaffIdList": [] }+```++- `userIds` 每次最多 20 个;`msgParam` 是 **JSON 字符串**。+- 该接口对部分失败也返回 200:所有收件人都落在 `invalidStaffIdList`(`kind: 'invalid_request'`)或 `flowControlledStaffIdList`(`kind: 'rate_limit'`)时,本实现抛错。+- 返回的 `processQueryKey` 作为消息 id(可用于查询已读或撤回)。++### 6.3 群聊:`groupMessages/send`++```json+POST /v1.0/robot/groupMessages/send+{+ "robotCode": "dingxxxxxxxx",+ "openConversationId": "cidXXXX==",+ "msgKey": "sampleText",+ "msgParam": "{\"content\":\"done\"}"+}+→ { "processQueryKey": "..." }+```++- 机器人必须已在群内;不支持 @ 人。通过群聊酷应用安装的机器人还需 `coolAppCode`(本包未用)。++### 6.4 sessionWebhook 回复与回退++```json+POST {sessionWebhook}+Content-Type: application/json+{ "msgtype": "text", "text": { "content": "..." }, "at": { "atUserIds": ["manager1234"] } }+→ { "errcode": 0, "errmsg": "ok" }+```++- URL 本身即凭证,不带 accessToken;支持 @(`at.atUserIds`)。第一版回复不主动 @ 发送者,与 OpenAPI 群发行为一致。+- **发送顺序(`DingTalkAdapter.send`)**:+ 1. Adapter 在每次收到回调时按 thread 记住最新的 `sessionWebhook` 与过期时间(内存,最多 1000 个 thread,超出淘汰最旧)。+ 2. 若存在且距过期超过 30 秒,优先经 sessionWebhook 发送 —— 不占 OpenAPI 调用配额(是否计入官方未写,未核实)、群聊也能工作。+ 3. sessionWebhook **缺失、即将过期、HTTP 失败或返回 `errcode != 0`**(会话过期等)时:从缓存删除该地址,回退到 OpenAPI(单聊 `batchSend`,群聊 `groupMessages/send`)。后续同 thread 不再尝试失效的地址。+- sessionWebhook 失败的具体 `errcode` 官方未列(未核实),所以按「任何非 0」判定失效。+- sessionWebhook 发送成功没有消息 id,返回 `session:{timestamp}` 作为占位 id。++### 6.5 编辑、删除、表情、输入中++| 操作 | 处理 |+| -------- | --------------------------------------------------------------------------- |+| 编辑 | 普通机器人消息不可编辑 → 发送一条新消息(与 QQ 一致);流式编辑需 AI 卡片。 |+| 删除 | 未实现(撤回接口需要 `processQueryKey`,sessionWebhook 发送拿不到)。 |+| 表情回复 | 机器人无对应接口,空实现。 |+| 输入中 | 无对应接口,空实现。 |+| 历史消息 | 机器人无历史消息接口,`fetchMessages` 返回空。 |++## 7. 错误映射++v1.0 OpenAPI 错误体:`{ "code": "send.too.fast", "message": "...", "requestid": "..." }`,HTTP 状态多为 400。实现统一抛出 `DingTalkApiError { status, code, kind, requestId }`,`kind` 规则(`classifyDingTalkError`):++| `kind` | 判定 | 典型 code |+| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |+| `auth` | HTTP 401,或 code ∈ {`InvalidAuthentication`, `invalidParameter.token.invalid`, `Forbidden.AccessDenied.AccessTokenInvalid`};Token 接口任意 4xx | 凭证错、token 失效 |+| `rate_limit` | HTTP 429,或 code 匹配 `throttl` / `too.fast` / `qpslimit` / `too.many`;`batchSend` 全部收件人被流控 | `send.too.fast`、`send.byToken.tooFast`、`too.many.people` |+| `permission` | HTTP 403,或 code 以 `Forbidden` 开头,或 ∈ {`send.forbidden`, `bot.forbidden.sendMessage`, `unauthorized`} | 未授权 `qyapi_robot_sendmsg`、IP 白名单、机器人被禁言 |+| `server` | HTTP ≥ 500 或 `system.error` | `system.error` |+| `invalid_request` | 其余 4xx | `invalidParameter.robotCode.*`、`invalid.openConversationId`、`staffId.notExisted` |+| `session_webhook` | sessionWebhook 网络失败、非 2xx 或 `errcode != 0` | —(触发 §6.4 回退,不向上抛) |++Adapter 层:`rate_limit` 转成 chat SDK 的 `RateLimitError`(`cause` 保留原错误),其余原样抛出。++**月度推送配额**:免费标准版组织的 Webhook + Stream 推送合计 5000 次 / 月,超出后机器人只收到错误码 20001、内容为空(见可行性调研)。该载荷的具体形态未核实;当前实现会因缺少有效内容而丢弃,识别并在渠道状态里提示留给平台接入任务。++## 8. 完整消息流程++```mermaid+sequenceDiagram+ participant U as 钉钉用户+ participant D as 钉钉开放平台+ participant G as Message Gateway<br/>(DingTalkStreamConnection)+ participant W as Webhook 管线<br/>(DingTalkAdapter)+ participant A as Agent++ G->>D: POST /v1.0/gateway/connections/open<br/>clientId + clientSecret + subscriptions+ D-->>G: endpoint, ticket(90s, 单次)+ G->>D: WebSocket endpoint?ticket=...+ loop 保活+ D->>G: SYSTEM ping {opaque}+ G->>D: ACK 200 {opaque}+ end++ U->>D: 单聊发消息 / 群里 @机器人+ D->>G: CALLBACK /v1.0/im/bot/messages/get+ G->>D: ACK 200 {"response":null}+ G->>W: POST webhookUrl (timestamp + sign)+ W->>W: 验签、解析、记录 sessionWebhook+ W->>A: chat.processMessage+ A-->>W: 回复内容++ alt sessionWebhook 有效+ W->>D: POST sessionWebhook+ else 过期 / 失败+ W->>D: POST /v1.0/oauth2/accessToken(缓存未命中时)+ alt 单聊+ W->>D: POST /v1.0/robot/oToMessages/batchSend+ else 群聊+ W->>D: POST /v1.0/robot/groupMessages/send+ end+ end+ D-->>U: 用户看到回复++ D->>G: SYSTEM disconnect+ G->>D: 关闭 → 重新注册 → 新 ticket 重连+```++## 9. 附录:与其他平台对比++| 维度 | 飞书 / Lark | QQ 开放平台 | 钉钉 |+| -------- | -------------------------- | ---------------------------------- | --------------------------------------------------- |+| 收消息 | 长连接(SDK)或 HTTP 回调 | WebSocket 或 HTTP 回调 | **Stream(WebSocket)** 或 HTTP 回调 |+| 建连 | SDK 内部完成 | `GET /gateway` → Identify/Resume | `connections/open` → 一次性 ticket,无 session 恢复 |+| 心跳 | SDK 内部 | 客户端按 `heartbeat_interval` 发送 | 服务端发 `ping`,客户端回显 |+| ACK | SDK 内部 | HTTP 回调需回 op 12 | 每个 CALLBACK 帧都要回 ACK 帧 |+| 群聊触发 | @ 或群内全部(取决于权限) | 仅 @ | 仅 @ |+| 回复 | message API(可编辑) | 被动回复需 `msg_id` | `sessionWebhook`(临时)或 OpenAPI 主动发送 |+| 编辑消息 | 支持 | 不支持 | 普通消息不支持(AI 卡片可流式更新) |+| 认证 | app_id + app_secret | appId + clientSecret | Client ID + Client Secret(2h accessToken) |++## 10. 实现与验证记录++### 10.1 代码位置++`packages/chat-adapter-dingtalk/src/`:++| 文件 | 职责 |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `types.ts` | 回调载荷、Stream 帧、OpenAPI 请求 / 响应类型与常量 |+| `api.ts` | `DingTalkApiClient`:token 缓存 / 刷新、Stream 注册、单聊 / 群聊 /sessionWebhook 发送、文件下载;`DingTalkApiError` 与错误分类 |+| `crypto.ts` | 回调签名与校验(HTTP 回调模式 + gateway 转发共用) |+| `gateway.ts` | `DingTalkStreamConnection`:注册、握手、ping/ACK、转发、协议层 ping 存活检测、重连 |+| `format-converter.ts` | mdast ⇄ markdown、出站模板选择、markdown 标题生成 |+| `adapter.ts` | `DingTalkAdapter`(chat SDK `Adapter`):验签、解析、thread 编码、发送与回退 |++### 10.2 单元测试++`bunx vitest run`(包目录)覆盖:gateway 握手 /ping 回显 / CALLBACK ACK 与签名转发 / 404 topic /disconnect 重连 / 退避与计数重置 / 注册长时间失败后持续重试 / 回 pong 的空闲连接不重连 / 未回 pong 的半开连接被替换 /abort/durationMs;入站单聊、群聊 @、外部联系人、richText、picture、audio、video、file、空消息、自身消息、验签失败与过期;出站 sessionWebhook 优先、单聊 batchSend、群聊 groupMessages、sessionWebhook 失效回退、过期跳过、限流映射、token 过期刷新重试、错误分类表、UTF-8 截断。++### 10.3 未实测清单++| # | 项 |+| --- | ------------------------------------------------------------------------------ |+| D1 | 真实企业中 Stream 单聊、群聊 @ 的回复回推(入站已实测:单聊与群聊 @ 均能收到) |+| D2 | `sessionWebhook` 实际有效期与失效时的 `errcode` |+| D4 | 群聊 `text.content` 是否总是去掉 @机器人(含多人 @ 场景) |+| D5 | 20001 配额耗尽载荷形态 |+| D6 | 入站图片下载码有效期、下载后 MIME(当前图片 / 音视频不预设 MIME,由下游嗅探) |++## 11. 服务端平台接入(`apps/server/src/services/bot/platforms/dingtalk/`)++### 11.1 文件++| 文件 | 职责 |+| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `definition.ts` | `PlatformDefinition`:`id: 'dingtalk'`、默认 Stream 模式、`supportsMarkdown: true`、`supportsMessageEdit: false`、不支持的消息 API |+| `schema.ts` | 凭证与设置表单:`applicationId` = Client ID,`credentials.clientSecret`(password),`credentials.robotCode`(可选);复用通用设置字段 |+| `const.ts` | 默认连接模式、字符上限、标识符格式、sessionWebhook 域名白名单 |+| `client.ts` | `DingTalkClientFactory`:Stream / HTTP 回调两种客户端、`validateCredentials`(真实调用 accessToken)、入站附件解析、messenger |+| `send.ts` | 出站:sessionWebhook 优先,失败或缺失时回退 `groupMessages/send` / `oToMessages/batchSend` |+| `sendAttachments.ts` | 出站附件:公网图片走 `sampleImageMsg`,其余降级为链接并上报 `failures` |+| `sessionWebhook.ts` | 验签通过的回调把 `sessionWebhook` 写入 Redis(`bot-reply` scope),供另一个进程发最终回复 |+| `service.ts` | `lobe-message` 运行时:仅 `sendMessage`,其余抛 `PlatformUnsupportedError` |+| `threadId.ts` | `dingtalk:<single\|group>:<id>` 编解码(id 内可含 `:`) |++不加 AgentId 字段:机器人收发接口(`oToMessages/batchSend`、`groupMessages/send`、sessionWebhook、Stream)只认 Client ID / Secret 与 RobotCode,AgentId 只用于工作通知。++### 11.2 凭证校验与错误码++`validateCredentials` 调用 `POST /v1.0/oauth2/accessToken`,错误按 `classifyDingTalkCredentialError` 映射到通用的 `channel.connectionError.<code>` 文案:++| 情况 | code |+| ------------------------------------------------------ | ---------------------- |+| 缺 Client ID / Client Secret | `missing_credentials` |+| 4xx(如真实返回 `400 invalidClientIdOrSecret`) | `invalid_credentials` |+| 403 或 `Forbidden*`(IP 白名单、应用停用等) | `permission_denied` |+| 429 或限流类 code | `rate_limited` |+| 5xx / `system.error` / 网络失败(DNS、超时、连接拒绝) | `upstream_unavailable` |++### 11.3 收发链路++```+钉钉 Stream CALLBACK+ → DingTalkStreamConnection(ACK + 签名转发)+ → POST /api/agent/webhooks/dingtalk/:clientId+ → BotMessageRouter.getWebhookHandler → loadBot → DingTalkClientFactory.createClient → createAdapter+ → withSessionWebhookCapture(验签后把 sessionWebhook 存 Redis)→ DingTalkAdapter.handleWebhook(验签、解析)+ → chat.processMessage → onNewMention / onSubscribedMessage(访问策略、命令)+ → AgentBridgeService.handleMention / handleSubscribedMessage(创建或复用 topic,thread state 存 topicId)+ → AiAgentService.execAgent(server runtime + agent gateway,hooks 带 platformThreadId)+ → BotCallbackService → client.getMessenger(platformThreadId).createMessage+ → sendDingTalkMessage:sessionWebhook → 回退 groupMessages/send(群)/ oToMessages/batchSend(单聊)+```++本地运行时(`localMode`)的回复走 `thread.post` → `DingTalkAdapter.postMessage`,同样 sessionWebhook 优先。++### 11.4 外部 message gateway++启用外部 message gateway 时,Stream 长连接由 Node 版 message gateway 的 `dingtalk` 连接托管(`MESSAGE_GATEWAY_NODE_PLATFORMS` 需包含 `dingtalk`):网关注册 Stream、用协议层 ping 保活、回 ACK,并把机器人回调原文按 HTTP 回调同样的 `timestamp` + `sign` 签名转发到 `/api/agent/webhooks/dingtalk/:clientId`,服务端沿用 Webhook 的验签与处理链路。服务端按部署判断是否开放 Stream(`nodeMessageGatewayOnly` + `isMessageGatewayHostingUnavailable`):启用网关但钉钉未路由到已配置的 Node 网关时,只提供 Webhook,并拒绝持久连接;路由到 Node 网关后自动开放 Stream。因此服务端可以先于网关上线。++### 11.5 未覆盖++- 出站文件 / 语音 / 视频需要旧版媒体上传接口的 `mediaId`,目前降级为链接。diff --git a/apps/server/src/services/bot/platforms/dingtalk/schema.test.ts b/apps/server/src/services/bot/platforms/dingtalk/schema.test.tsnew file mode 100644index 00000000000..b1c35a12947--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/schema.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';++import { validateAccessSettings } from '../const';+import type { FieldSchema } from '../types';+import { mergeWithDefaults } from '../utils';+import { collectFieldFormatViolations } from '../validateFieldFormats';+import { DINGTALK_CHAR_LIMIT } from './const';+import { schema } from './schema';++const section = (key: string): FieldSchema | undefined => schema.find((f) => f.key === key);+const settingKeys = () => section('settings')?.properties?.map((f) => f.key) ?? [];++describe('DingTalk schema', () => {+ it('takes the Client ID as the application id', () => {+ expect(section('applicationId')).toMatchObject({+ label: 'channel.dingtalk.clientId',+ required: true,+ type: 'string',+ });+ });++ it('stores Client Secret as the only secret and RobotCode as an optional identifier', () => {+ const credentials = section('credentials')?.properties ?? [];+ expect(credentials.map((f) => [f.key, f.type, !!f.required])).toEqual([+ ['clientSecret', 'password', true],+ ['robotCode', 'string', false],+ ]);+ });++ it('reuses the shared access, reply and concurrency fields', () => {+ expect(settingKeys()).toEqual(+ expect.arrayContaining([+ 'userId',+ 'connectionMode',+ 'charLimit',+ 'concurrency',+ 'debounceMs',+ 'showUsageStats',+ 'displayToolCalls',+ 'processingMessage',+ 'dmPolicy',+ 'groupPolicy',+ 'groupAllowFrom',+ 'allowFrom',+ 'watchKeywords',+ 'replyStyle',+ ]),+ );+ });++ it('defaults to Stream mode, open policies and the byte-safe char limit', () => {+ const defaults = mergeWithDefaults(schema, {});+ expect(defaults).toMatchObject({+ charLimit: DINGTALK_CHAR_LIMIT,+ connectionMode: 'websocket',+ dmPolicy: 'open',+ groupPolicy: 'open',+ processingMessage: false,+ });+ });++ it('rejects malformed identifiers through the shared format check', () => {+ expect(+ collectFieldFormatViolations(schema, {+ applicationId: 'ding abc',+ credentials: { clientSecret: 'any secret / value', robotCode: 'https://x' },+ }).map((v) => v.field),+ ).toEqual(['applicationId', 'credentials.robotCode']);++ expect(+ collectFieldFormatViolations(schema, {+ applicationId: 'dingabc123',+ credentials: { clientSecret: 'S3cr3t+/=', robotCode: '' },+ }),+ ).toEqual([]);+ });++ it('runs the shared access-settings validation', () => {+ expect(validateAccessSettings({ dmPolicy: 'pairing' }).valid).toBe(false);+ expect(validateAccessSettings({ dmPolicy: 'pairing', userId: 'manager1234' }).valid).toBe(true);+ expect(validateAccessSettings(mergeWithDefaults(schema, {})).valid).toBe(true);+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/schema.ts b/apps/server/src/services/bot/platforms/dingtalk/schema.tsnew file mode 100644index 00000000000..dab65ea8dad--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/schema.ts@@ -0,0 +1,147 @@+import { MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';++import {+ allowFromField,+ displayToolCallsField,+ makeDmPolicyField,+ makeGroupPolicyFields,+ makeUserIdField,+ processingMessageField,+ watchKeywordsField,+} from '../const';+import { deviceAccessFields } from '../deviceAccess';+import { replyStyleFields } from '../replyStyle';+import type { FieldSchema } from '../types';+import {+ DEFAULT_DINGTALK_CONNECTION_MODE,+ DINGTALK_CHAR_LIMIT,+ DINGTALK_IDENTIFIER_PATTERN,+} from './const';++/**+ * DingTalk internal-app robot.+ *+ * - `applicationId` is the app's Client ID (formerly AppKey). It is both the+ * Stream mode client id and the key of the `/api/agent/webhooks/dingtalk/…`+ * route, so it is a plain identifier rather than a credential.+ * - `credentials.clientSecret` (formerly AppSecret) is the only secret: it+ * mints the access token, opens Stream connections and signs callbacks.+ * - `credentials.robotCode` is optional. An internal-app robot's RobotCode is+ * its Client ID, which the adapter uses when the field is blank; it is+ * surfaced for robots whose code differs. No AgentId is needed: the robot+ * send APIs (`oToMessages/batchSend`, `groupMessages/send`) address the+ * robot by RobotCode, and AgentId only matters for work notifications.+ *+ * No `reactionMode` field: DingTalk robots have no reaction API, so the+ * setting would have nothing to drive (see `messageCapabilities.ts`).+ */+export const schema: FieldSchema[] = [+ {+ key: 'applicationId',+ description: 'channel.dingtalk.clientIdHint',+ label: 'channel.dingtalk.clientId',+ pattern: DINGTALK_IDENTIFIER_PATTERN,+ patternMessage: 'channel.dingtalk.identifierInvalid',+ placeholder: 'channel.dingtalk.clientIdPlaceholder',+ required: true,+ type: 'string',+ },+ {+ key: 'credentials',+ label: 'channel.credentials',+ properties: [+ {+ key: 'clientSecret',+ description: 'channel.dingtalk.clientSecretHint',+ label: 'channel.dingtalk.clientSecret',+ required: true,+ type: 'password',+ },+ {+ key: 'robotCode',+ description: 'channel.dingtalk.robotCodeHint',+ label: 'channel.dingtalk.robotCode',+ pattern: DINGTALK_IDENTIFIER_PATTERN,+ patternMessage: 'channel.dingtalk.identifierInvalid',+ type: 'string',+ },+ ],+ type: 'object',+ },+ {+ key: 'settings',+ label: 'channel.settings',+ properties: [+ makeUserIdField('dingtalk'),+ ...deviceAccessFields,+ {+ key: 'connectionMode',+ default: DEFAULT_DINGTALK_CONNECTION_MODE,+ description: 'channel.connectionModeHint',+ enum: ['websocket', 'webhook'],+ enumDescriptions: [+ 'channel.connectionModeWebSocketHint',+ 'channel.connectionModeWebhookHint',+ ],+ enumLabels: ['channel.connectionModeWebSocket', 'channel.connectionModeWebhook'],+ label: 'channel.connectionMode',+ type: 'string',+ },+ {+ key: 'charLimit',+ default: DINGTALK_CHAR_LIMIT,+ description: 'channel.charLimitHint',+ label: 'channel.charLimit',+ maximum: DINGTALK_CHAR_LIMIT,+ minimum: 100,+ type: 'number',+ },+ {+ key: 'concurrency',+ default: 'queue',+ description: 'channel.concurrencyHint',+ enum: ['queue', 'burst', 'debounce'],+ enumDescriptions: [+ 'channel.concurrencyQueueHint',+ 'channel.concurrencyBurstHint',+ 'channel.concurrencyDebounceHint',+ ],+ enumLabels: [+ 'channel.concurrencyQueue',+ 'channel.concurrencyBurst',+ 'channel.concurrencyDebounce',+ ],+ label: 'channel.concurrency',+ type: 'string',+ },+ {+ key: 'debounceMs',+ default: 5000,+ description: 'channel.debounceMsHint',+ label: 'channel.debounceMs',+ maximum: MAX_BOT_DEBOUNCE_MS,+ minimum: 100,+ type: 'number',+ visibleWhen: { field: 'concurrency', value: ['burst', 'debounce'] },+ },+ {+ key: 'showUsageStats',+ default: false,+ description: 'channel.showUsageStatsHint',+ label: 'channel.showUsageStats',+ type: 'boolean',+ },+ displayToolCallsField,+ processingMessageField,+ makeDmPolicyField({ policy: 'open' }),+ // DingTalk only delivers group messages that @-mention the robot, so+ // `requireMention` is effectively always satisfied; the group policy and+ // allowlist still decide which groups the bot answers in.+ ...makeGroupPolicyFields({ policy: 'open' }),+ allowFromField,+ watchKeywordsField,+ ...replyStyleFields,+ ],+ type: 'object',+ },+];diff --git a/apps/server/src/services/bot/platforms/dingtalk/send.ts b/apps/server/src/services/bot/platforms/dingtalk/send.tsnew file mode 100644index 00000000000..f0deabaf107--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/send.ts@@ -0,0 +1,79 @@+import type { DingTalkApiClient, DingTalkOutboundMessage } from '@lobechat/chat-adapter-dingtalk';+import {+ DingTalkFormatConverter,+ MAX_MSG_PARAM_TEXT_BYTES,+ truncateUtf8,+} from '@lobechat/chat-adapter-dingtalk';+import debug from 'debug';++import { redisService } from '@/server/services/redis';++import { type DingTalkConversation, formatDingTalkThreadId } from './threadId';++const log = debug('bot-platform:dingtalk:send');++const formatConverter = new DingTalkFormatConverter();++/**+ * Pick the robot template for a reply. Markdown when the text uses markdown+ * syntax, plain text otherwise; the body is cut to the `msgParam` byte budget.+ */+export const toDingTalkOutbound = (text: string): DingTalkOutboundMessage => {+ const body = truncateUtf8(text.trim(), MAX_MSG_PARAM_TEXT_BYTES);+ return formatConverter.toOutboundMessage(body, body);+};++/**+ * Deliver one robot message to a DingTalk conversation.+ *+ * Order (protocol-spec §6.4): the conversation's latest `sessionWebhook`, when+ * one was captured from an inbound callback and is still valid — it needs no+ * access token or send permission and is the only route to external contacts.+ * When it is missing or DingTalk rejects it, the route is dropped and the+ * robot OpenAPI takes over: `groupMessages/send` for groups,+ * `oToMessages/batchSend` for single chats.+ *+ * Returns the `processQueryKey` of an OpenAPI send, or `undefined` for a+ * sessionWebhook send (DingTalk returns no id for those).+ */+export const sendDingTalkMessage = async (+ api: DingTalkApiClient,+ applicationId: string,+ conversation: DingTalkConversation,+ outbound: DingTalkOutboundMessage,+): Promise<string | undefined> => {+ const threadId = formatDingTalkThreadId(conversation);+ const session = await redisService.botReply.getDingTalkSessionWebhook(applicationId, threadId);++ if (session) {+ try {+ await api.replyViaSessionWebhook(session.url, outbound);+ return undefined;+ } catch (error) {+ // Never serialize the error: it may carry the credential-bearing webhook URL.+ log(+ 'sessionWebhook rejected for %s, falling back to OpenAPI: %s',+ threadId,+ error instanceof Error ? error.name : 'unknown',+ );+ await redisService.botReply.forgetDingTalkSessionWebhook(applicationId, threadId);+ }+ }++ const result =+ conversation.type === 'group'+ ? await api.sendGroupMessage(conversation.id, outbound)+ : await api.sendSingleMessage([conversation.id], outbound);+ return result.processQueryKey;+};++/** Send a text/markdown reply; blank text is a no-op. */+export const sendDingTalkText = async (+ api: DingTalkApiClient,+ applicationId: string,+ conversation: DingTalkConversation,+ text: string,+): Promise<string | undefined> => {+ if (!text.trim()) return undefined;+ return sendDingTalkMessage(api, applicationId, conversation, toDingTalkOutbound(text));+};diff --git a/apps/server/src/services/bot/platforms/dingtalk/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/dingtalk/sendAttachments.test.tsnew file mode 100644index 00000000000..bcb7c88a5ca--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/sendAttachments.test.ts@@ -0,0 +1,106 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const botReply = vi.hoisted(() => ({+ forgetDingTalkSessionWebhook: vi.fn(),+ getDingTalkSessionWebhook: vi.fn(),+}));+vi.mock('@/server/services/redis', () => ({ redisService: { botReply } }));++const { sendDingTalkAttachments } = await import('./sendAttachments');++const group = { id: 'cid1', type: 'group' as const };++const createApi = () => ({+ replyViaSessionWebhook: vi.fn().mockResolvedValue(undefined),+ sendGroupMessage: vi.fn().mockResolvedValue({ processQueryKey: 'k' }),+ sendSingleMessage: vi.fn().mockResolvedValue({ processQueryKey: 'k' }),+});++describe('sendDingTalkAttachments', () => {+ let api: ReturnType<typeof createApi>;++ beforeEach(() => {+ vi.clearAllMocks();+ botReply.getDingTalkSessionWebhook.mockResolvedValue(undefined);+ api = createApi();+ });++ it('sends text first, then each public image as sampleImageMsg', async () => {+ const result = await sendDingTalkAttachments(+ api as any,+ 'dingapp',+ group,+ [{ fetchUrl: 'https://cdn.example/a.png', name: 'a.png', type: 'image' }],+ 'caption',+ );++ expect(api.sendGroupMessage.mock.calls.map(([, msg]) => msg)).toEqual([+ { msgKey: 'sampleText', msgParam: { content: 'caption' } },+ { msgKey: 'sampleImageMsg', msgParam: { photoURL: 'https://cdn.example/a.png' } },+ ]);+ expect(result).toEqual({ delivered: 1, failures: [] });+ });++ it('degrades files and URL-less attachments to links in the text leg', async () => {+ const result = await sendDingTalkAttachments(api as any, 'dingapp', group, [+ { fetchUrl: 'https://cdn.example/r.pdf', name: 'r.pdf', type: 'file' },+ { data: 'aGk=', name: 'b.png', type: 'image' },+ ]);++ expect(api.sendGroupMessage).toHaveBeenCalledTimes(1);+ const text = api.sendGroupMessage.mock.calls[0][1].msgParam.content;+ expect(text).toContain('📎 r.pdf: https://cdn.example/r.pdf');+ expect(text).toContain('📎 b.png (attachment dropped: no public URL)');+ expect(result.delivered).toBe(0);+ expect(result.failures.map((f) => [f.name, f.reason])).toEqual([+ ['r.pdf', 'upload-failed'],+ ['b.png', 'source-unavailable'],+ ]);+ });++ it('still sends the images but fails the call when the text leg is rejected', async () => {+ const textError = new Error('text rejected');+ api.sendGroupMessage.mockImplementation(async (_target: unknown, msg: { msgKey: string }) => {+ if (msg.msgKey === 'sampleText') throw textError;+ return { processQueryKey: 'k' };+ });++ await expect(+ sendDingTalkAttachments(+ api as any,+ 'dingapp',+ group,+ [{ fetchUrl: 'https://cdn.example/a.png', name: 'a.png', type: 'image' }],+ 'the answer',+ ),+ ).rejects.toBe(textError);++ // The image was still attempted (and landed), so a caller must not retry it as success.+ expect(api.sendGroupMessage.mock.calls.map(([, msg]) => msg.msgKey)).toEqual([+ 'sampleText',+ 'sampleImageMsg',+ ]);+ });++ it('falls back to a link when DingTalk rejects an image', async () => {+ api.sendSingleMessage+ .mockRejectedValueOnce(new Error('invalid photoURL'))+ .mockResolvedValue({ processQueryKey: 'k' });++ const result = await sendDingTalkAttachments(+ api as any,+ 'dingapp',+ { id: 'staff1', type: 'single' },+ [{ fetchUrl: 'https://cdn.example/a.png', name: 'a.png', type: 'image' }],+ );++ expect(result.delivered).toBe(0);+ expect(result.failures).toEqual([+ { detail: 'invalid photoURL', name: 'a.png', reason: 'upload-failed', type: 'image' },+ ]);+ expect(api.sendSingleMessage.mock.calls.at(-1)![1]).toEqual({+ msgKey: 'sampleText',+ msgParam: { content: '📎 a.png: https://cdn.example/a.png' },+ });+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/sendAttachments.ts b/apps/server/src/services/bot/platforms/dingtalk/sendAttachments.tsnew file mode 100644index 00000000000..44dc9783595--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/sendAttachments.ts@@ -0,0 +1,112 @@+import type { DingTalkApiClient } from '@lobechat/chat-adapter-dingtalk';+import debug from 'debug';++import type { AttachmentFailure, AttachmentSendResult } from '../attachmentDelivery';+import type { BotMessageAttachment } from '../types';+import { sendDingTalkMessage, sendDingTalkText } from './send';+import type { DingTalkConversation } from './threadId';++const log = debug('bot-platform:dingtalk:send-attachments');++const renderTextLink = (att: BotMessageAttachment): string => {+ const name = att.name ?? att.type;+ if (att.fetchUrl) return `📎 ${name}: ${att.fetchUrl}`;+ return `📎 ${name} (attachment dropped: no public URL)`;+};++/**+ * Deliver attachments alongside an outbound DingTalk reply.+ *+ * - **Images with a public `fetchUrl`** go out as `sampleImageMsg`, whose+ * `photoURL` accepts a URL directly (protocol-spec §6.1).+ * - **Everything else** — files, audio, video, and base64 `data` images —+ * degrades to a text link. Native file/voice/video templates need a+ * `mediaId` from the legacy media upload API, which this integration does not+ * use; a link still reaches the user.+ *+ * The text leg ships first so the conversation reads context → media, matching+ * the other platforms. Every attachment that did not arrive as media is+ * reported in `failures`, even when a link stood in for it, so the agent never+ * claims a file was attached.+ *+ * A failed text leg is re-thrown after the images were attempted, as Feishu and+ * WeChat let it throw: the reply (and any link lines) never reached the user, so+ * the send must not read as delivered even when an image got through.+ */+export const sendDingTalkAttachments = async (+ api: DingTalkApiClient,+ applicationId: string,+ conversation: DingTalkConversation,+ attachments: BotMessageAttachment[],+ leadingText?: string,+): Promise<AttachmentSendResult> => {+ const fallbackLines: string[] = [];+ const failures: AttachmentFailure[] = [];+ const images: BotMessageAttachment[] = [];++ for (const att of attachments) {+ if (att.type === 'image' && att.fetchUrl) {+ images.push(att);+ continue;+ }+ fallbackLines.push(renderTextLink(att));+ failures.push(+ att.fetchUrl+ ? {+ detail: 'DingTalk robots cannot send this type natively; sent as a link',+ name: att.name,+ reason: 'upload-failed',+ type: att.type,+ }+ : {+ detail: 'no public URL to send',+ name: att.name,+ reason: 'source-unavailable',+ type: att.type,+ },+ );+ }++ const combinedText = [leadingText, fallbackLines.join('\n')]+ .filter((s) => s && s.trim())+ .join('\n\n');+ let textError: unknown;+ if (combinedText) {+ try {+ await sendDingTalkText(api, applicationId, conversation, combinedText);+ } catch (error) {+ log('sendDingTalkAttachments: text leg failed: %O', error);+ textError = error;+ }+ }++ let delivered = 0;+ for (const image of images) {+ try {+ await sendDingTalkMessage(api, applicationId, conversation, {+ msgKey: 'sampleImageMsg',+ msgParam: { photoURL: image.fetchUrl! },+ });+ delivered += 1;+ } catch (error) {+ failures.push({+ detail: (error as Error)?.message ?? String(error),+ name: image.name,+ reason: 'upload-failed',+ type: image.type,+ });+ log(+ 'sendDingTalkAttachments: image "%s" failed — degrading to text link: %O',+ image.name ?? '(unnamed)',+ error,+ );+ await sendDingTalkText(api, applicationId, conversation, renderTextLink(image)).catch(+ () => undefined,+ );+ }+ }++ if (textError !== undefined) throw textError;++ return { delivered, failures };+};diff --git a/apps/server/src/services/bot/platforms/dingtalk/service.test.ts b/apps/server/src/services/bot/platforms/dingtalk/service.test.tsnew file mode 100644index 00000000000..b26a84acb5c--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/service.test.ts@@ -0,0 +1,74 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const botReply = vi.hoisted(() => ({+ forgetDingTalkSessionWebhook: vi.fn(),+ getDingTalkSessionWebhook: vi.fn(),+}));+vi.mock('@/server/services/redis', () => ({ redisService: { botReply } }));++const { DingTalkMessageService } = await import('./service');++const createApi = () => ({+ replyViaSessionWebhook: vi.fn().mockResolvedValue(undefined),+ sendGroupMessage: vi.fn().mockResolvedValue({ processQueryKey: 'group-key' }),+ sendSingleMessage: vi.fn().mockResolvedValue({ processQueryKey: 'single-key' }),+});++describe('DingTalkMessageService', () => {+ let api: ReturnType<typeof createApi>;+ let service: InstanceType<typeof DingTalkMessageService>;++ beforeEach(() => {+ vi.clearAllMocks();+ botReply.getDingTalkSessionWebhook.mockResolvedValue(undefined);+ api = createApi();+ service = new DingTalkMessageService(api as any, 'dingapp');+ });++ it.each([+ ['group:cid1==', 'group', 'cid1=='],+ ['dingtalk:group:cid1==', 'group', 'cid1=='],+ ['cid1==', 'group', 'cid1=='],+ ])('sends %s to a group', async (channelId, _type, id) => {+ const result = await service.sendMessage({ channelId, content: 'hello' });++ expect(api.sendGroupMessage).toHaveBeenCalledWith(id, {+ msgKey: 'sampleText',+ msgParam: { content: 'hello' },+ });+ expect(result).toEqual({+ channelId: `dingtalk:group:${id}`,+ messageId: 'group-key',+ platform: 'dingtalk',+ });+ });++ it.each([['single:staff1'], ['dingtalk:single:staff1']])(+ 'sends %s to a single chat',+ async (channelId) => {+ const result = await service.sendMessage({ channelId, content: '# Title\nbody' });++ expect(api.sendSingleMessage).toHaveBeenCalledWith(['staff1'], {+ msgKey: 'sampleMarkdown',+ msgParam: { text: '# Title\nbody', title: 'Title' },+ });+ expect(result.messageId).toBe('single-key');+ },+ );++ it('reports attachments that could not be delivered natively', async () => {+ const result = await service.sendMessage({+ attachments: [+ { fetchUrl: 'https://cdn.example/a.png', name: 'a.png', type: 'image' },+ { fetchUrl: 'https://cdn.example/r.pdf', name: 'r.pdf', type: 'file' },+ ],+ channelId: 'group:cid1',+ content: 'see attached',+ });++ expect(result.attachmentsDelivered).toBe(1);+ expect(result.attachmentFailures).toEqual([+ expect.objectContaining({ name: 'r.pdf', reason: 'upload-failed', type: 'file' }),+ ]);+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/service.ts b/apps/server/src/services/bot/platforms/dingtalk/service.tsnew file mode 100644index 00000000000..5a505feb60b--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/service.ts@@ -0,0 +1,162 @@+import type {+ CreatePollParams,+ CreatePollState,+ CreateThreadParams,+ CreateThreadState,+ DeleteMessageParams,+ DeleteMessageState,+ EditMessageParams,+ EditMessageState,+ GetChannelInfoParams,+ GetChannelInfoState,+ GetMemberInfoParams,+ GetMemberInfoState,+ GetReactionsParams,+ GetReactionsState,+ ListChannelsParams,+ ListChannelsState,+ ListPinsParams,+ ListPinsState,+ ListThreadsParams,+ ListThreadsState,+ PinMessageParams,+ PinMessageState,+ ReactToMessageParams,+ ReactToMessageState,+ ReadMessagesParams,+ ReadMessagesState,+ ReplyToThreadParams,+ ReplyToThreadState,+ SearchMessagesParams,+ SearchMessagesState,+ SendMessageParams,+ SendMessageState,+ UnpinMessageParams,+ UnpinMessageState,+} from '@lobechat/builtin-tool-message/executionRuntime';+import type { DingTalkApiClient } from '@lobechat/chat-adapter-dingtalk';++import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';+import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';++import {+ attachmentDeliveryState,+ type AttachmentSendResult,+ warnAttachmentFailures,+} from '../attachmentDelivery';+import { sendDingTalkText } from './send';+import { sendDingTalkAttachments } from './sendAttachments';+import { formatDingTalkThreadId, parseDingTalkChannelId } from './threadId';++/**+ * `lobe-message` runtime for DingTalk robots.+ *+ * Only `sendMessage` is possible: DingTalk robots have no history, search,+ * edit, reaction, pin, member or channel-listing API (protocol-spec §6.5).+ * Every other op throws `PlatformUnsupportedError`, and+ * `PLATFORM_UNSUPPORTED_MESSAGE_APIS.dingtalk` lists them so the model is+ * never offered them.+ *+ * `channelId` is a DingTalk conversation: `group:<openConversationId>`,+ * `single:<staffId>`, a full `dingtalk:<type>:<id>` thread id, or a bare+ * `openConversationId` (treated as a group).+ */+export class DingTalkMessageService implements MessageRuntimeService {+ constructor(+ private api: DingTalkApiClient,+ private applicationId: string,+ ) {}++ sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {+ const conversation = parseDingTalkChannelId(params.channelId);+ let messageId: string | undefined;+ let attachments: AttachmentSendResult | undefined;+ if (params.attachments?.length) {+ attachments = await sendDingTalkAttachments(+ this.api,+ this.applicationId,+ conversation,+ params.attachments,+ params.content,+ );+ warnAttachmentFailures('bot-platform:dingtalk:sendMessage', attachments.failures);+ } else {+ messageId = await sendDingTalkText(+ this.api,+ this.applicationId,+ conversation,+ params.content,+ );+ }+ return {+ channelId: formatDingTalkThreadId(conversation),+ messageId,+ platform: 'dingtalk',+ ...attachmentDeliveryState(attachments),+ };+ };++ readMessages = async (_params: ReadMessagesParams): Promise<ReadMessagesState> => {+ throw new PlatformUnsupportedError('DingTalk', 'readMessages');+ };++ editMessage = async (_params: EditMessageParams): Promise<EditMessageState> => {+ throw new PlatformUnsupportedError('DingTalk', 'editMessage');+ };++ deleteMessage = async (_params: DeleteMessageParams): Promise<DeleteMessageState> => {+ throw new PlatformUnsupportedError('DingTalk', 'deleteMessage');+ };++ searchMessages = async (_params: SearchMessagesParams): Promise<SearchMessagesState> => {+ throw new PlatformUnsupportedError('DingTalk', 'searchMessages');+ };++ reactToMessage = async (_params: ReactToMessageParams): Promise<ReactToMessageState> => {+ throw new PlatformUnsupportedError('DingTalk', 'reactToMessage');+ };++ getReactions = async (_params: GetReactionsParams): Promise<GetReactionsState> => {+ throw new PlatformUnsupportedError('DingTalk', 'getReactions');+ };++ pinMessage = async (_params: PinMessageParams): Promise<PinMessageState> => {+ throw new PlatformUnsupportedError('DingTalk', 'pinMessage');+ };++ unpinMessage = async (_params: UnpinMessageParams): Promise<UnpinMessageState> => {+ throw new PlatformUnsupportedError('DingTalk', 'unpinMessage');+ };++ listPins = async (_params: ListPinsParams): Promise<ListPinsState> => {+ throw new PlatformUnsupportedError('DingTalk', 'listPins');+ };++ getChannelInfo = async (_params: GetChannelInfoParams): Promise<GetChannelInfoState> => {+ throw new PlatformUnsupportedError('DingTalk', 'getChannelInfo');+ };++ listChannels = async (_params: ListChannelsParams): Promise<ListChannelsState> => {+ throw new PlatformUnsupportedError('DingTalk', 'listChannels');+ };++ getMemberInfo = async (_params: GetMemberInfoParams): Promise<GetMemberInfoState> => {+ throw new PlatformUnsupportedError('DingTalk', 'getMemberInfo');+ };++ createThread = async (_params: CreateThreadParams): Promise<CreateThreadState> => {+ throw new PlatformUnsupportedError('DingTalk', 'createThread');+ };++ listThreads = async (_params: ListThreadsParams): Promise<ListThreadsState> => {+ throw new PlatformUnsupportedError('DingTalk', 'listThreads');+ };++ replyToThread = async (_params: ReplyToThreadParams): Promise<ReplyToThreadState> => {+ throw new PlatformUnsupportedError('DingTalk', 'replyToThread');+ };++ createPoll = async (_params: CreatePollParams): Promise<CreatePollState> => {+ throw new PlatformUnsupportedError('DingTalk', 'createPoll');+ };+}diff --git a/apps/server/src/services/bot/platforms/dingtalk/sessionWebhook.test.ts b/apps/server/src/services/bot/platforms/dingtalk/sessionWebhook.test.tsnew file mode 100644index 00000000000..5cf3defde8e--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/sessionWebhook.test.ts@@ -0,0 +1,124 @@+import { signCallback } from '@lobechat/chat-adapter-dingtalk';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const botReply = vi.hoisted(() => ({ rememberDingTalkSessionWebhook: vi.fn() }));+vi.mock('@/server/services/redis', () => ({ redisService: { botReply } }));++const { captureSessionWebhook, isDingTalkSessionWebhookUrl, withSessionWebhookCapture } =+ await import('./sessionWebhook');++const SECRET = 'client-secret';+const EXPIRES = Date.now() + 60 * 60 * 1000;++const payload = (overrides: Record<string, unknown> = {}) => ({+ conversationId: 'cidGroup==',+ conversationType: '2',+ msgId: 'm1',+ msgtype: 'text',+ senderId: '$:LWCP_v1:$user',+ senderStaffId: 'staff1',+ sessionWebhook: 'https://oapi.dingtalk.com/robot/sendBySession?session=s1',+ sessionWebhookExpiredTime: EXPIRES,+ text: { content: 'hi' },+ ...overrides,+});++const signedRequest = (body: unknown, secret = SECRET) => {+ const timestamp = String(Date.now());+ return new Request('https://app.example.com/api/agent/webhooks/dingtalk/dingapp', {+ body: JSON.stringify(body),+ headers: { sign: signCallback(timestamp, secret), timestamp },+ method: 'POST',+ });+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('captureSessionWebhook', () => {+ it('stores a group route keyed by the adapter thread id', async () => {+ await captureSessionWebhook(signedRequest(payload()), 'dingapp', SECRET);++ expect(botReply.rememberDingTalkSessionWebhook).toHaveBeenCalledWith(+ 'dingapp',+ 'dingtalk:group:cidGroup==',+ { expiresAt: EXPIRES, url: 'https://oapi.dingtalk.com/robot/sendBySession?session=s1' },+ );+ });++ it('keys a single chat by staff id, or by sender id for external contacts', async () => {+ await captureSessionWebhook(+ signedRequest(payload({ conversationType: '1' })),+ 'dingapp',+ SECRET,+ );+ await captureSessionWebhook(+ signedRequest(payload({ conversationType: '1', senderStaffId: undefined })),+ 'dingapp',+ SECRET,+ );++ expect(+ botReply.rememberDingTalkSessionWebhook.mock.calls.map(([, threadId]) => threadId),+ ).toEqual(['dingtalk:single:staff1', 'dingtalk:single:$:LWCP_v1:$user']);+ });++ it('never stores a route from an unsigned or wrongly signed request', async () => {+ await captureSessionWebhook(signedRequest(payload(), 'other-secret'), 'dingapp', SECRET);+ await captureSessionWebhook(+ new Request('https://x', { body: JSON.stringify(payload()), method: 'POST' }),+ 'dingapp',+ SECRET,+ );++ expect(botReply.rememberDingTalkSessionWebhook).not.toHaveBeenCalled();+ });++ it('ignores a route outside dingtalk.com', async () => {+ await captureSessionWebhook(+ signedRequest(payload({ sessionWebhook: 'https://evil.example/hook' })),+ 'dingapp',+ SECRET,+ );+ expect(botReply.rememberDingTalkSessionWebhook).not.toHaveBeenCalled();+ });+});++describe('isDingTalkSessionWebhookUrl', () => {+ it.each([+ ['https://oapi.dingtalk.com/robot/sendBySession?session=1', true],+ ['https://api.dingtalk.com/x', true],+ ['http://oapi.dingtalk.com/x', false],+ ['https://dingtalk.com.evil.example/x', false],+ ['https://evildingtalk.com/x', false],+ ['not a url', false],+ ])('%s → %s', (url, expected) => {+ expect(isDingTalkSessionWebhookUrl(url)).toBe(expected);+ });+});++describe('withSessionWebhookCapture', () => {+ it('captures the route and still hands the untouched request to the adapter', async () => {+ const handleWebhook = vi.fn(async (request: Request) => {+ expect(JSON.parse(await request.text())).toMatchObject({ msgId: 'm1' });+ return Response.json({ ok: true });+ });+ const adapter = withSessionWebhookCapture({ handleWebhook } as any, 'dingapp', SECRET);++ const response = await adapter.handleWebhook(signedRequest(payload()));++ expect(response.status).toBe(200);+ expect(handleWebhook).toHaveBeenCalledTimes(1);+ expect(botReply.rememberDingTalkSessionWebhook).toHaveBeenCalledTimes(1);+ });++ it('does not block the callback when Redis fails', async () => {+ botReply.rememberDingTalkSessionWebhook.mockRejectedValueOnce(new Error('redis down'));+ const handleWebhook = vi.fn(async () => Response.json({ ok: true }));+ const adapter = withSessionWebhookCapture({ handleWebhook } as any, 'dingapp', SECRET);++ await expect(adapter.handleWebhook(signedRequest(payload()))).resolves.toBeInstanceOf(Response);+ expect(handleWebhook).toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/sessionWebhook.ts b/apps/server/src/services/bot/platforms/dingtalk/sessionWebhook.tsnew file mode 100644index 00000000000..52a52caccc6--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/sessionWebhook.ts@@ -0,0 +1,94 @@+import type { DingTalkAdapter, DingTalkRawMessage } from '@lobechat/chat-adapter-dingtalk';+import {+ DINGTALK_CONVERSATION_TYPE,+ verifyCallbackSignature,+} from '@lobechat/chat-adapter-dingtalk';+import debug from 'debug';++import { redisService } from '@/server/services/redis';++import { DINGTALK_SESSION_WEBHOOK_HOST_PATTERN } from './const';+import { formatDingTalkThreadId } from './threadId';++const log = debug('bot-platform:dingtalk:session-webhook');++/** A reply URL is only trusted when DingTalk issued it over HTTPS. */+export const isDingTalkSessionWebhookUrl = (value: string): boolean => {+ try {+ const url = new URL(value);+ return url.protocol === 'https:' && DINGTALK_SESSION_WEBHOOK_HOST_PATTERN.test(url.hostname);+ } catch {+ return false;+ }+};++/** Thread id for a callback payload — same derivation as the adapter's `threadIdFromRaw`. */+export const threadIdFromCallback = (raw: DingTalkRawMessage): string =>+ raw.conversationType === DINGTALK_CONVERSATION_TYPE.GROUP+ ? formatDingTalkThreadId({ id: raw.conversationId, type: 'group' })+ : formatDingTalkThreadId({ id: raw.senderStaffId || raw.senderId, type: 'single' });++/**+ * Remember the callback's `sessionWebhook` for the conversation it came from.+ *+ * Runs before the adapter sees the request, and only for a request whose+ * `timestamp` + `sign` check passes: the stored URL is later POSTed with the+ * agent's reply, so an unsigned request must never be able to plant one. The+ * host is pinned to `*.dingtalk.com` on top of that.+ */+export const captureSessionWebhook = async (+ request: Request,+ applicationId: string,+ clientSecret: string,+): Promise<void> => {+ if (+ !verifyCallbackSignature(+ request.headers.get('timestamp'),+ request.headers.get('sign'),+ clientSecret,+ )+ ) {+ return;+ }++ let raw: DingTalkRawMessage;+ try {+ raw = JSON.parse(await request.text()) as DingTalkRawMessage;+ } catch {+ return;+ }++ if (!raw?.conversationId || !raw.senderId) return;+ if (!raw.sessionWebhook || !raw.sessionWebhookExpiredTime) return;+ if (!isDingTalkSessionWebhookUrl(raw.sessionWebhook)) {+ log('ignoring sessionWebhook outside dingtalk.com for app %s', applicationId);+ return;+ }++ await redisService.botReply.rememberDingTalkSessionWebhook(+ applicationId,+ threadIdFromCallback(raw),+ { expiresAt: Number(raw.sessionWebhookExpiredTime), url: raw.sessionWebhook },+ );+};++/**+ * Make an adapter persist every inbound `sessionWebhook` before handling the+ * callback. The adapter keeps its own in-memory copy for replies it posts+ * itself; this copy is for the bot callback, which posts the agent's final+ * reply from whichever process the agent gateway calls back into.+ */+export const withSessionWebhookCapture = (+ adapter: DingTalkAdapter,+ applicationId: string,+ clientSecret: string,+): DingTalkAdapter => {+ const handleWebhook = adapter.handleWebhook.bind(adapter);+ adapter.handleWebhook = async (request, options) => {+ await captureSessionWebhook(request.clone(), applicationId, clientSecret).catch((error) => {+ log('failed to capture sessionWebhook for app %s: %O', applicationId, error);+ });+ return handleWebhook(request, options);+ };+ return adapter;+};diff --git a/apps/server/src/services/bot/platforms/dingtalk/threadId.test.ts b/apps/server/src/services/bot/platforms/dingtalk/threadId.test.tsnew file mode 100644index 00000000000..c23176167dc--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/threadId.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import { formatDingTalkThreadId, parseDingTalkChannelId, parseDingTalkThreadId } from './threadId';++describe('DingTalk thread ids', () => {+ it.each([+ ['dingtalk:group:cid1==', { id: 'cid1==', type: 'group' }],+ ['dingtalk:single:staff1', { id: 'staff1', type: 'single' }],+ ['dingtalk:single:$:LWCP_v1:$abc', { id: '$:LWCP_v1:$abc', type: 'single' }],+ ['cid1==', { id: 'cid1==', type: 'group' }],+ ['dingtalk:other:x', { id: 'dingtalk:other:x', type: 'group' }],+ ])('parses %s', (threadId, expected) => {+ expect(parseDingTalkThreadId(threadId)).toEqual(expected);+ });++ it('round-trips through format', () => {+ const conversation = { id: '$:LWCP_v1:$abc', type: 'single' as const };+ expect(parseDingTalkThreadId(formatDingTalkThreadId(conversation))).toEqual(conversation);+ });++ it.each([+ ['group:cid1', { id: 'cid1', type: 'group' }],+ ['single:staff1', { id: 'staff1', type: 'single' }],+ ['dingtalk:single:staff1', { id: 'staff1', type: 'single' }],+ ['cid1', { id: 'cid1', type: 'group' }],+ ])('parses channel id %s', (channelId, expected) => {+ expect(parseDingTalkChannelId(channelId)).toEqual(expected);+ });+});diff --git a/apps/server/src/services/bot/platforms/dingtalk/threadId.ts b/apps/server/src/services/bot/platforms/dingtalk/threadId.tsnew file mode 100644index 00000000000..15a97022d93--- /dev/null+++ b/apps/server/src/services/bot/platforms/dingtalk/threadId.ts@@ -0,0 +1,48 @@+import { DINGTALK_THREAD_PREFIX } from './const';++export type DingTalkConversationType = 'single' | 'group';++export interface DingTalkConversation {+ /** `senderStaffId` (or `senderId` for external contacts) for single chats, `openConversationId` for groups. */+ id: string;+ type: DingTalkConversationType;+}++/**+ * Decode `dingtalk:<single|group>:<id>` — the thread id the adapter encodes.+ *+ * Only the first two separators are structural: DingTalk's encrypted+ * `senderId` (`$:LWCP_v1:$…`) contains `:` itself, so the rest is kept whole.+ * Anything that is not a DingTalk thread id is treated as a bare group+ * conversation id, matching the adapter's `decodeThreadId`.+ */+export const parseDingTalkThreadId = (platformThreadId: string): DingTalkConversation => {+ const [prefix, type, ...rest] = platformThreadId.split(':');+ if (+ prefix !== DINGTALK_THREAD_PREFIX ||+ (type !== 'single' && type !== 'group') ||+ rest.length === 0+ ) {+ return { id: platformThreadId, type: 'group' };+ }+ return { id: rest.join(':'), type };+};++export const formatDingTalkThreadId = ({ id, type }: DingTalkConversation): string =>+ `${DINGTALK_THREAD_PREFIX}:${type}:${id}`;++/**+ * Accept the forms a model may hand the `lobe-message` tool as `channelId`:+ * the full thread id (`dingtalk:group:cid…`), a typed id (`single:staff1`,+ * `group:cid…`), or a bare id, which is taken as a group conversation because+ * every `openConversationId` the bot sees comes from a group.+ */+export const parseDingTalkChannelId = (channelId: string): DingTalkConversation => {+ if (channelId.startsWith(`${DINGTALK_THREAD_PREFIX}:`)) return parseDingTalkThreadId(channelId);++ const [type, ...rest] = channelId.split(':');+ if ((type === 'single' || type === 'group') && rest.length > 0) {+ return { id: rest.join(':'), type };+ }+ return { id: channelId, type: 'group' };+};diff --git a/apps/server/src/services/bot/platforms/index.ts b/apps/server/src/services/bot/platforms/index.tsindex 3b3c6dc5343..fb909c35990 100644--- a/apps/server/src/services/bot/platforms/index.ts+++ b/apps/server/src/services/bot/platforms/index.ts@@ -1,5 +1,6 @@// --------------- Core types & utilities ---------------// --------------- Registry singleton ---------------+import { dingtalk } from './dingtalk/definition';import { discord } from './discord/definition';import { feishu } from './feishu/definitions/feishu';import { lark } from './feishu/definitions/lark';@@ -112,12 +113,14 @@ export {resolveBotConcurrency,resolveBotProviderConfig,resolveConnectionMode,+ restrictPlatformToWebhook,withResolvedConcurrencySettings,} from './utils';export type { BotProviderFieldValues, FieldFormatViolation } from './validateFieldFormats';export { collectFieldFormatViolations, formatFieldFormatViolations } from './validateFieldFormats';// --------------- Platform definitions ---------------+export { dingtalk } from './dingtalk/definition';export { discord } from './discord/definition';export { feishu } from './feishu/definitions/feishu';export { lark } from './feishu/definitions/lark';@@ -141,3 +144,4 @@ platformRegistry.register(qq);platformRegistry.register(wechat);platformRegistry.register(line);platformRegistry.register(wecom);+platformRegistry.register(dingtalk);diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts b/apps/server/src/services/bot/platforms/messageCapabilities.test.tsindex 1b4cc5c23c7..8b1801d48b1 100644--- a/apps/server/src/services/bot/platforms/messageCapabilities.test.ts+++ b/apps/server/src/services/bot/platforms/messageCapabilities.test.ts@@ -19,6 +19,7 @@ const MEMBER_THREAD_ID = 'telegram:-100123';// platform id -> service.ts location (lark shares feishu's service)const SERVICE_DIR: Record<string, string> = {+ dingtalk: 'dingtalk',discord: 'discord',feishu: 'feishu',imessage: 'imessage',@@ -63,7 +64,7 @@ describe('PLATFORM_UNSUPPORTED_MESSAGE_APIS', () => {// `linq` is messenger-only (shared iMessage / SMS pool): it has no channel// service behind the message tool at all, so history is pre-injected. `wecom` is the same:// AI bots only answer on their own long connection and have no history API.- expect(noHistory).toEqual(['linq', 'qq', 'telegram', 'wechat', 'wecom']);+ expect(noHistory).toEqual(['dingtalk', 'linq', 'qq', 'telegram', 'wechat', 'wecom']);});});diff --git a/apps/server/src/services/bot/platforms/messageCapabilities.ts b/apps/server/src/services/bot/platforms/messageCapabilities.tsindex 5a2aa07d169..cdc888bbf22 100644--- a/apps/server/src/services/bot/platforms/messageCapabilities.ts+++ b/apps/server/src/services/bot/platforms/messageCapabilities.ts@@ -54,6 +54,28 @@ export const TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS: string[] = [...CHANNEL_MES* `TELEGRAM_GUEST_UNSUPPORTED_MESSAGE_APIS` via `resolveUnsupportedMessageApis`.*/export const PLATFORM_UNSUPPORTED_MESSAGE_APIS: Record<string, string[]> = {+ // DingTalk robots can only send: no history, search, edit, delete, reaction,+ // pin, member or channel-listing API → prompt uses pre-injected history.+ dingtalk: [+ MessageApiName.createPoll,+ MessageApiName.createThread,+ MessageApiName.deleteMessage,+ MessageApiName.editMessage,+ MessageApiName.getChannelInfo,+ MessageApiName.getMemberInfo,+ MessageApiName.getReactions,+ MessageApiName.listChannels,+ MessageApiName.listPins,+ MessageApiName.listThreads,+ MessageApiName.pinMessage,+ MessageApiName.reactToMessage,+ MessageApiName.readDocument,+ MessageApiName.readMessages,+ MessageApiName.replyToThread,+ MessageApiName.searchMessages,+ MessageApiName.sendDirectMessage,+ MessageApiName.unpinMessage,+ ],// Discord implements the full surface — no entry needed, but keep it explicit.// Discord has no document API — `readDocument` is Feishu/Lark only.discord: [MessageApiName.readDocument],diff --git a/apps/server/src/services/bot/platforms/processingMessage.test.ts b/apps/server/src/services/bot/platforms/processingMessage.test.tsindex ea0a4bfcecd..fac44d647dd 100644--- a/apps/server/src/services/bot/platforms/processingMessage.test.ts+++ b/apps/server/src/services/bot/platforms/processingMessage.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { processingMessageField, shouldPostProcessingMessage } from './const';+import { schema as dingtalkSchema } from './dingtalk/schema';import { schema as discordSchema } from './discord/schema';import { sharedSchema as feishuSchema } from './feishu/definitions/schema';import { schema as imessageSchema } from './imessage/schema';@@ -30,6 +31,7 @@ describe('processingMessageField', () => {});it.each([+ ['dingtalk', dingtalkSchema],['discord', discordSchema],['feishu', feishuSchema],['imessage', imessageSchema],diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.tsindex 16b50dee3cd..08434f5fd6d 100644--- a/apps/server/src/services/bot/platforms/types.ts+++ b/apps/server/src/services/bot/platforms/types.ts@@ -686,6 +686,15 @@ export interface PlatformDefinition {/** The name of the platform. */name: string;+ /**+ * Only the Node message gateway has a handler for this platform's persistent connection. With+ * the gateway enabled, persistent modes work only while the platform is routed to the Node host+ * (`MESSAGE_GATEWAY_NODE_PLATFORMS`); otherwise only webhook mode works and persistent modes are+ * refused with an actionable error. See `isMessageGatewayHostingUnavailable`. In-process+ * connections (gateway disabled) are unaffected.+ */+ nodeMessageGatewayOnly?: boolean;+/*** Credential keys that are identifiers rather than secrets, for platforms* whose credentials never come from the form schema and so have nodiff --git a/apps/server/src/services/bot/platforms/utils.test.ts b/apps/server/src/services/bot/platforms/utils.test.tsindex dc50fd7d6b2..fa0dc9e6713 100644--- a/apps/server/src/services/bot/platforms/utils.test.ts+++ b/apps/server/src/services/bot/platforms/utils.test.ts@@ -9,6 +9,7 @@ import {resolveBotConcurrency,resolveBotProviderConfig,resolveConnectionMode,+ restrictPlatformToWebhook,withResolvedConcurrencySettings,} from './utils';@@ -149,6 +150,52 @@ describe('resolveConnectionMode', () => {});});+describe('restrictPlatformToWebhook', () => {+ const platform = {+ connectionMode: 'websocket',+ schema: [+ {+ key: 'settings',+ properties: [+ {+ default: 'websocket',+ enum: ['websocket', 'webhook'],+ enumDescriptions: ['ws hint', 'webhook hint'],+ enumLabels: ['WebSocket', 'Webhook'],+ key: 'connectionMode',+ },+ { default: 5, key: 'charLimit' },+ ],+ },+ { key: 'credentials' },+ ],+ } as unknown as Pick<PlatformDefinition, 'connectionMode' | 'schema'>;++ it('offers webhook as the default and only mode, keeping labels aligned', () => {+ const restricted = restrictPlatformToWebhook(platform);++ expect(restricted.connectionMode).toBe('webhook');+ expect(restricted.schema[0].properties).toEqual([+ {+ default: 'webhook',+ enum: ['webhook'],+ enumDescriptions: ['webhook hint'],+ enumLabels: ['Webhook'],+ key: 'connectionMode',+ },+ { default: 5, key: 'charLimit' },+ ]);+ expect(restricted.schema[1]).toEqual({ key: 'credentials' });+ });++ it('does not mutate the shared registry definition', () => {+ restrictPlatformToWebhook(platform);++ expect(platform.connectionMode).toBe('websocket');+ expect(platform.schema[0].properties?.[0].default).toBe('websocket');+ });+});+describe('resolveBotConcurrency', () => {// WeChat splits one logical turn across several messages, so it collects a// window before the first dispatch. Everything else dispatches at once anddiff --git a/apps/server/src/services/bot/platforms/utils.ts b/apps/server/src/services/bot/platforms/utils.tsindex 388340b121f..01e81f9763c 100644--- a/apps/server/src/services/bot/platforms/utils.ts+++ b/apps/server/src/services/bot/platforms/utils.ts@@ -161,6 +161,37 @@ export function getEffectiveConnectionMode(return platform?.connectionMode ?? 'webhook';}+/**+ * The definition as a deployment that can only run it in webhook mode should+ * present it: webhook is the default and the only connection mode offered, so+ * nobody is steered to a mode that is refused when they connect.+ */+export function restrictPlatformToWebhook<+ T extends { connectionMode: ConnectionMode; schema: FieldSchema[] },+>(platform: T): T {+ const restrictField = (field: FieldSchema): FieldSchema => {+ if (field.key !== 'connectionMode') return field;+ const keep = (field.enum ?? []).map((mode) => mode === 'webhook');+ return {+ ...field,+ default: 'webhook',+ enum: field.enum?.filter((_, index) => keep[index]),+ enumDescriptions: field.enumDescriptions?.filter((_, index) => keep[index]),+ enumLabels: field.enumLabels?.filter((_, index) => keep[index]),+ };+ };++ return {+ ...platform,+ connectionMode: 'webhook',+ schema: platform.schema.map((field) =>+ field.key === 'settings' && field.properties+ ? { ...field, properties: field.properties.map(restrictField) }+ : field,+ ),+ };+}+// --------------- Provider config resolution ---------------/**diff --git a/apps/server/src/services/gateway/gatewayMapping.ts b/apps/server/src/services/gateway/gatewayMapping.tsindex 45d0de9326b..611a17f130b 100644--- a/apps/server/src/services/gateway/gatewayMapping.ts+++ b/apps/server/src/services/gateway/gatewayMapping.ts@@ -6,7 +6,7 @@ import type { DecryptedMessengerAccountLink } from '@/database/models/messengerAimport { gatewayEnv } from '@/envs/gateway';import type { BotRuntimeStatus } from '@/types/botRuntimeStatus';-import { extractWatchKeywordEntries } from '../bot/platforms';+import { extractWatchKeywordEntries, type PlatformDefinition } from '../bot/platforms';import { hasPassiveListeningRule } from '../conversationWake/config';import type {MessageGatewayCapabilities,@@ -38,6 +38,22 @@ export function mapGatewayStatusToRuntimeStatus(}}+/**+ * Runtime status for a provider asking for a persistent connection on a platform+ * the message gateway has no handler for. Shared by the explicit connect and the+ * reconcile, so a bot that never went through connect still explains itself.+ */+export const buildMessageGatewayRefusalStatus = (+ definition: Pick<PlatformDefinition, 'id' | 'name'>,+ applicationId: string,+) => ({+ applicationId,+ errorCode: 'webhook_mode_required',+ errorMessage: `${definition.name} cannot use a persistent connection on this deployment yet. Switch the connection mode to Webhook and set the platform's callback address to the Webhook URL shown here.`,+ platform: definition.id,+ status: BOT_RUNTIME_STATUSES.failed,+});+/*** Derive edge-filtering capabilities for a bot-channel connection from its* settings. Monitoring is enabled by "has any passive-listening rule": watchdiff --git a/apps/server/src/services/gateway/index.clientLifecycle.test.ts b/apps/server/src/services/gateway/index.clientLifecycle.test.tsindex f6adb7e8b25..2c0965e255e 100644--- a/apps/server/src/services/gateway/index.clientLifecycle.test.ts+++ b/apps/server/src/services/gateway/index.clientLifecycle.test.ts@@ -13,6 +13,9 @@ import {mockFindEnabledByPlatformAndAppId,mockGatewayClient,mockGatewayManager,+ mockGetBotRuntimeStatus,+ mockNodeGateway,+ mockNodeGatewayClient,mockResolveConnectionMode,mockUpdateBotRuntimeStatus,resetGatewayServiceMocks,@@ -67,6 +70,68 @@ describe('GatewayService client lifecycle', () => {mockGatewayClient.isEnabled = true;});+ it('refuses a persistent connection the gateway cannot host, with an actionable error', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);+ mockResolveConnectionMode.mockReturnValue('websocket');++ await expect(service.startClient('dingtalk', 'app-1', 'user-1')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringMatching(/switch the connection mode to webhook/i),+ });++ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith({+ applicationId: 'app-1',+ errorCode: 'webhook_mode_required',+ errorMessage: expect.stringMatching(/switch the connection mode to webhook/i),+ platform: 'dingtalk',+ status: 'failed',+ });+ });++ it('still starts webhook mode on a platform the gateway cannot host', async () => {+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);+ mockResolveConnectionMode.mockReturnValue('webhook');++ await expect(service.startClient('dingtalk', 'app-1', 'user-1')).resolves.toBe('started');++ expect(mockGatewayManager.startClient).toHaveBeenCalledWith('dingtalk', 'app-1');+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ });++ it('connects Stream through the Node gateway once DingTalk is routed there', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['dingtalk'];+ mockNodeGatewayClient.isConfigured = true;+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);+ mockResolveConnectionMode.mockReturnValue('websocket');++ await expect(service.startClient('dingtalk', 'app-1', 'user-1')).resolves.toBe('started');++ expect(mockNodeGatewayClient.connect).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionMode: 'websocket',+ platform: 'dingtalk',+ webhookPath: '/api/agent/webhooks/dingtalk/app-1',+ }),+ );+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(+ expect.objectContaining({ errorCode: 'webhook_mode_required' }),+ );+ });++ it('keeps the refusal visible instead of overwriting it with gateway status', async () => {+ const cached = { errorMessage: 'refused', status: 'failed' };+ mockGetBotRuntimeStatus.mockResolvedValue(cached);+ mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);+ mockResolveConnectionMode.mockReturnValue('websocket');++ await expect(service.refreshBotRuntimeStatus('dingtalk', 'app-1')).resolves.toBe(cached);++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ });+it('connects a persistent provider with its capabilities and marks it connected', async () => {mockFindEnabledByPlatformAndAppId.mockResolvedValue(provider);mockResolveConnectionMode.mockReturnValue('websocket');diff --git a/apps/server/src/services/gateway/index.reconcile.test.ts b/apps/server/src/services/gateway/index.reconcile.test.tsindex 01607f5402d..913d1e0e0dc 100644--- a/apps/server/src/services/gateway/index.reconcile.test.ts+++ b/apps/server/src/services/gateway/index.reconcile.test.ts@@ -133,6 +133,19 @@ describe('GatewayService', () => {expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('dormant-stale');});+ it('cleans a leftover connection of a platform the gateway cannot host', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-ding'] });+ mockFindByIds.mockResolvedValue([+ { applicationId: 'ding-app', enabled: true, id: 'prov-ding', platform: 'dingtalk' },+ ]);++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('prov-ding');+ });+it('marks still-existing (disabled) providers as disconnected when stale-cleaned', async () => {mockFindEnabledByPlatform.mockResolvedValue([]);mockGatewayClient.getStats.mockResolvedValue({diff --git a/apps/server/src/services/gateway/index.runtime.test.ts b/apps/server/src/services/gateway/index.runtime.test.tsindex 0ad2c074b2e..312aeced728 100644--- a/apps/server/src/services/gateway/index.runtime.test.ts+++ b/apps/server/src/services/gateway/index.runtime.test.ts@@ -110,6 +110,23 @@ describe('GatewayService', () => {status: 'failed',});});++ it('skips a platform the gateway cannot host', async () => {+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockFindByAgentId.mockResolvedValue([+ {+ applicationId: 'ding-app',+ enabled: true,+ id: 'prov-ding',+ platform: 'dingtalk',+ settings: {},+ },+ ]);++ await service.refreshBotRuntimeStatusesByAgent('agent-1');++ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();+ });});// ─── ensureRunning ───diff --git a/apps/server/src/services/gateway/index.sync.test.ts b/apps/server/src/services/gateway/index.sync.test.tsindex 6f58956a68b..7cb8a58021b 100644--- a/apps/server/src/services/gateway/index.sync.test.ts+++ b/apps/server/src/services/gateway/index.sync.test.ts@@ -84,6 +84,35 @@ describe('GatewayService', () => {expect(mockGatewayClient.connect).not.toHaveBeenCalled();});+ it('never pushes a platform the gateway cannot host', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'dingtalk'+ ? [+ {+ applicationId: 'ding-app',+ credentials: { clientSecret: 'x' },+ id: 'prov-ding',+ settings: {},+ userId: 'u1',+ },+ ]+ : [],+ );+ mockResolveConnectionMode.mockReturnValue('websocket');++ await service.ensureRunning();++ expect(mockGatewayClient.connect).not.toHaveBeenCalled();+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(+ expect.objectContaining({+ applicationId: 'ding-app',+ errorCode: 'webhook_mode_required',+ platform: 'dingtalk',+ status: 'failed',+ }),+ );+ });+it('ensure-wakes a registered-only desired provider without probing status', async () => {// Registered-only (pruned from stats) used to be skipped outright, but a// stranded DO (alarm chain lost) looks exactly like this and sleeps@@ -224,7 +253,9 @@ describe('GatewayService', () => {});it('handles connect failure gracefully', async () => {- mockFindEnabledByPlatform.mockResolvedValue([createGatewayProvider()]);+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord' ? [createGatewayProvider()] : [],+ );mockResolveConnectionMode.mockReturnValue('websocket');mockGatewayClient.connect.mockRejectedValue(new Error('timeout'));diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex 4862a1e3a73..b86c27ad34c 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -10,7 +10,11 @@ import type { BotRuntimeStatusSnapshot } from '@/types/botRuntimeStatus';import { type ConnectionMode, platformRegistry, resolveConnectionMode } from '../bot/platforms';import { BOT_CONNECT_QUEUE_EXPIRE_MS, BotConnectQueue } from './botConnectQueue';import { createGatewayManager, getGatewayManager } from './GatewayManager';-import { mapGatewayStatusToRuntimeStatus, resolveBotGatewayCapabilities } from './gatewayMapping';+import {+ buildMessageGatewayRefusalStatus,+ mapGatewayStatusToRuntimeStatus,+ resolveBotGatewayCapabilities,+} from './gatewayMapping';import {getConfiguredMessageGatewayHosts,getMessageGatewayClient,@@ -18,6 +22,7 @@ import {isAnyMessageGatewayEnabled,type MessageGatewayHost,} from './MessageGatewayClient';+import { isMessageGatewayHostingUnavailable } from './nodeGatewayOnly';import { getReplyConnectionUnavailableReason } from './replyConnectionHost';import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus, updateBotRuntimeStatus } from './runtimeStatus';import { syncGatewayConnections } from './sync';@@ -194,7 +199,7 @@ export class GatewayService {const definition = platformRegistry.getPlatform(provider.platform);const connectionMode = resolveConnectionMode(definition, provider.settings);- if (connectionMode === 'webhook') return;+ if (connectionMode === 'webhook' || isMessageGatewayHostingUnavailable(definition)) return;try {const client = getMessageGatewayClient(provider.platform);@@ -247,8 +252,10 @@ export class GatewayService {// Webhook-mode bots have no persistent gateway connection to query — the// gateway only holds the webhook URL registration, so the local snapshot- // is already the source of truth.- if (connectionMode === 'webhook') return cached;+ // is already the source of truth. The same goes for a platform the gateway+ // cannot host: it holds nothing, and asking would overwrite the refusal.+ if (connectionMode === 'webhook' || isMessageGatewayHostingUnavailable(definition))+ return cached;const client = getMessageGatewayClient(platform);try {@@ -367,6 +374,12 @@ export class GatewayService {return 'started';}+ if (definition && isMessageGatewayHostingUnavailable(definition)) {+ const status = buildMessageGatewayRefusalStatus(definition, applicationId);+ await updateBotRuntimeStatus(status);+ throw new TRPCError({ code: 'PRECONDITION_FAILED', message: status.errorMessage });+ }+const webhookPath = `/api/agent/webhooks/${platform}/${applicationId}`;await client.connect({diff --git a/apps/server/src/services/gateway/nodeGatewayOnly.test.ts b/apps/server/src/services/gateway/nodeGatewayOnly.test.tsnew file mode 100644index 00000000000..bfa35a7e0fe--- /dev/null+++ b/apps/server/src/services/gateway/nodeGatewayOnly.test.ts@@ -0,0 +1,39 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const routing = vi.hoisted(() => ({ host: 'default' as 'default' | 'node', nodeConfigured: true }));++vi.mock('./MessageGatewayClient', () => ({+ isMessageGatewayHostConfigured: (host: string) => host === 'node' && routing.nodeConfigured,+ resolveMessageGatewayHost: () => routing.host,+}));++const { isMessageGatewayHostingUnavailable } = await import('./nodeGatewayOnly');++const dingtalk = { id: 'dingtalk', nodeMessageGatewayOnly: true };++describe('isMessageGatewayHostingUnavailable', () => {+ beforeEach(() => {+ routing.host = 'default';+ routing.nodeConfigured = true;+ });++ it('is unavailable while the platform stays on the default gateway', () => {+ expect(isMessageGatewayHostingUnavailable(dingtalk)).toBe(true);+ });++ it('is available once the platform is routed to a configured Node gateway', () => {+ routing.host = 'node';+ expect(isMessageGatewayHostingUnavailable(dingtalk)).toBe(false);+ });++ it('is unavailable when routed to a Node gateway that is not configured', () => {+ routing.host = 'node';+ routing.nodeConfigured = false;+ expect(isMessageGatewayHostingUnavailable(dingtalk)).toBe(true);+ });++ it('never restricts platforms every gateway can host', () => {+ expect(isMessageGatewayHostingUnavailable({ id: 'discord' })).toBe(false);+ expect(isMessageGatewayHostingUnavailable(undefined)).toBe(false);+ });+});diff --git a/apps/server/src/services/gateway/nodeGatewayOnly.ts b/apps/server/src/services/gateway/nodeGatewayOnly.tsnew file mode 100644index 00000000000..75aeeaf9905--- /dev/null+++ b/apps/server/src/services/gateway/nodeGatewayOnly.ts@@ -0,0 +1,16 @@+import { isMessageGatewayHostConfigured, resolveMessageGatewayHost } from './MessageGatewayClient';++/**+ * Whether the message gateway cannot hold `platform`'s persistent connection on this deployment.+ *+ * A `nodeMessageGatewayOnly` platform (DingTalk Stream) has a handler only on the Node message+ * gateway, so the gateway can host it only when the platform is routed there+ * (`MESSAGE_GATEWAY_NODE_PLATFORMS`) and the Node host is configured. Elsewhere only webhook mode+ * works and persistent modes are refused with an actionable error. Callers check this only with+ * the gateway enabled; in-process connections (gateway disabled) are unaffected.+ */+export const isMessageGatewayHostingUnavailable = (+ platform: { id: string; nodeMessageGatewayOnly?: boolean } | undefined,+): boolean =>+ !!platform?.nodeMessageGatewayOnly &&+ !(resolveMessageGatewayHost(platform.id) === 'node' && isMessageGatewayHostConfigured('node'));diff --git a/apps/server/src/services/gateway/sync/drain.ts b/apps/server/src/services/gateway/sync/drain.tsindex dfdf27839f2..9f0a0308b97 100644--- a/apps/server/src/services/gateway/sync/drain.ts+++ b/apps/server/src/services/gateway/sync/drain.ts@@ -15,6 +15,7 @@ import {type MessageGatewayHost,resolveMessageGatewayHost,} from '../MessageGatewayClient';+import { isMessageGatewayHostingUnavailable } from '../nodeGatewayOnly';import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from '../runtimeStatus';import { GATEWAY_SYNC_CONCURRENCY, GATEWAY_SYNC_STALE_DISCONNECT_LIMIT } from './constants';import { hostDesiredSlice, hostGatedSlice, hostRefusesPlatform } from './state';@@ -164,10 +165,12 @@ export async function disconnectStaleConnections(// An enabled persistent-mode row that shows up in `actual` but not// in `desired` is one of two things, and only one of them is stale.+ const definition = row && platformRegistry.getPlatform(row.platform);const livePersistentRow =row?.enabled &&- resolveConnectionMode(platformRegistry.getPlatform(row.platform), row.settings) !==- 'webhook';+ // Never desired, so "enabled during sync" can't explain it: it is stale.+ !isMessageGatewayHostingUnavailable(definition) &&+ resolveConnectionMode(definition, row.settings) !== 'webhook';if (livePersistentRow) {const owner = resolveMessageGatewayHost(row.platform);diff --git a/apps/server/src/services/gateway/sync/state.ts b/apps/server/src/services/gateway/sync/state.tsindex 979c5312b81..4531694504e 100644--- a/apps/server/src/services/gateway/sync/state.ts+++ b/apps/server/src/services/gateway/sync/state.ts@@ -14,11 +14,13 @@ import { AgentBotProviderModel } from '@/database/models/agentBotProvider';import type { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { platformRegistry, resolveConnectionMode } from '../../bot/platforms';+import { buildMessageGatewayRefusalStatus } from '../gatewayMapping';import {type getMessageGatewayClient,type MessageGatewayHost,resolveMessageGatewayHost,} from '../MessageGatewayClient';+import { isMessageGatewayHostingUnavailable } from '../nodeGatewayOnly';import { resolveReplyConnectionHost } from '../replyConnectionHost';import {BOT_RUNTIME_STATUSES,@@ -170,6 +172,19 @@ export async function buildDesiredConnections(return connectionMode === 'webhook' ? [] : [{ connectionMode, provider }];});+ // No handler on the gateway: a connect can only fail, every round.+ if (isMessageGatewayHostingUnavailable(definition)) {+ await pMap(+ persistent,+ ({ provider }) =>+ updateBotRuntimeStatus(+ buildMessageGatewayRefusalStatus(definition, provider.applicationId),+ ),+ { concurrency: FEATURE_GATE_CONCURRENCY },+ );+ continue;+ }+// Bounded concurrency, not one provider at a time. Regression: each// check is a lookup of its own, and checking a large platform in series// made this build slow enough for a gateway's boot pull to time out ondiff --git a/apps/server/src/services/gateway/testUtils.ts b/apps/server/src/services/gateway/testUtils.tsindex 5fb7073594c..09b67a1d2b1 100644--- a/apps/server/src/services/gateway/testUtils.ts+++ b/apps/server/src/services/gateway/testUtils.ts@@ -171,8 +171,17 @@ export const botPlatformsModule = () => ({? settings.watchKeywords.filter((e: any) => typeof e?.keyword === 'string' && e.keyword): [],platformRegistry: {- getPlatform: (platform: string) => ({ id: platform }),- listPlatforms: () => [{ id: 'discord' }, { id: 'telegram' }, { id: 'wechat' }],+ getPlatform: (platform: string) => ({+ id: platform,+ nodeMessageGatewayOnly: platform === 'dingtalk',+ name: platform,+ }),+ listPlatforms: () => [+ { id: 'dingtalk', name: 'DingTalk', nodeMessageGatewayOnly: true },+ { id: 'discord' },+ { id: 'telegram' },+ { id: 'wechat' },+ ],},resolveConnectionMode: mockResolveConnectionMode,});diff --git a/apps/server/src/services/redis/botReply.test.ts b/apps/server/src/services/redis/botReply.test.tsnew file mode 100644index 00000000000..78709ae66e2--- /dev/null+++ b/apps/server/src/services/redis/botReply.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { botReply } from './botReply';++const store = new Map<string, string>();+const redis = vi.hoisted(() => ({ client: null as any, scope: undefined as string | undefined }));+vi.mock('./client', () => ({+ getRedisServiceClient: async (scope: string) => {+ redis.scope = scope;+ return redis.client;+ },+}));++const memoryClient = {+ del: vi.fn(async (key: string) => (store.delete(key) ? 1 : 0)),+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string) => {+ store.set(key, value);+ return 'OK';+ }),+};++const NOW = 1_800_000_000_000;+const KEY = 'dingtalk_session_webhook:v1:ding-app:dingtalk:group:cid==';++beforeEach(() => {+ store.clear();+ vi.clearAllMocks();+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ redis.client = memoryClient;+});++afterEach(() => {+ vi.useRealTimers();+});++describe('redisService.botReply DingTalk sessionWebhook', () => {+ it('stores the route under the bot-reply scope until shortly before it expires', async () => {+ const webhook = { expiresAt: NOW + 60 * 60 * 1000, url: 'https://oapi.dingtalk.com/x' };+ await botReply.rememberDingTalkSessionWebhook('ding-app', 'dingtalk:group:cid==', webhook);++ expect(redis.scope).toBe('botReply');+ expect(memoryClient.set).toHaveBeenCalledWith(KEY, JSON.stringify(webhook), {+ px: 60 * 60 * 1000 - 30 * 1000,+ });+ expect(await botReply.getDingTalkSessionWebhook('ding-app', 'dingtalk:group:cid==')).toEqual(+ webhook,+ );+ });++ it('skips a route that is already inside the expiry margin', async () => {+ await botReply.rememberDingTalkSessionWebhook('ding-app', 'dingtalk:group:cid==', {+ expiresAt: NOW + 10_000,+ url: 'https://oapi.dingtalk.com/x',+ });+ expect(memoryClient.set).not.toHaveBeenCalled();+ });++ it('does not hand out a stored route past its expiry margin', async () => {+ store.set(KEY, JSON.stringify({ expiresAt: NOW + 5000, url: 'https://oapi.dingtalk.com/x' }));+ expect(+ await botReply.getDingTalkSessionWebhook('ding-app', 'dingtalk:group:cid=='),+ ).toBeUndefined();+ });++ it('ignores malformed values', async () => {+ store.set(KEY, 'not-json');+ expect(+ await botReply.getDingTalkSessionWebhook('ding-app', 'dingtalk:group:cid=='),+ ).toBeUndefined();+ });++ it('forgets a rejected route', async () => {+ store.set(KEY, JSON.stringify({ expiresAt: NOW + 3_600_000, url: 'https://x' }));+ await botReply.forgetDingTalkSessionWebhook('ding-app', 'dingtalk:group:cid==');+ expect(store.has(KEY)).toBe(false);+ });++ it('degrades to a no-op without Redis', async () => {+ redis.client = null;+ await botReply.rememberDingTalkSessionWebhook('ding-app', 't', {+ expiresAt: NOW + 3_600_000,+ url: 'https://x',+ });+ expect(await botReply.getDingTalkSessionWebhook('ding-app', 't')).toBeUndefined();+ await expect(botReply.forgetDingTalkSessionWebhook('ding-app', 't')).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/redis/botReply.ts b/apps/server/src/services/redis/botReply.tsnew file mode 100644index 00000000000..644f1de4afa--- /dev/null+++ b/apps/server/src/services/redis/botReply.ts@@ -0,0 +1,81 @@+import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('botReply');++/**+ * Stop handing out a sessionWebhook this long before DingTalk's stated expiry,+ * so a reply that takes a few seconds to send never races the deadline.+ */+const EXPIRY_MARGIN_MS = 30 * 1000;++export interface DingTalkSessionWebhook {+ /** DingTalk's `sessionWebhookExpiredTime`, Unix ms. */+ expiresAt: number;+ url: string;+}++/**+ * Reply routes an IM platform issues together with an inbound message.+ *+ * DingTalk gives every robot callback a temporary `sessionWebhook` that can+ * answer the conversation without an access token or the robot send+ * permission, and is the only way to reach external contacts. The webhook that+ * receives the message and the callback that posts the agent's reply may run+ * in different processes, so the latest route per conversation lives here.+ * Without Redis every call is a no-op and senders fall back to the OpenAPI.+ */+export const botReply = {+ async rememberDingTalkSessionWebhook(+ applicationId: string,+ threadId: string,+ webhook: DingTalkSessionWebhook,+ ): Promise<void> {+ const ttlMs = webhook.expiresAt - Date.now() - EXPIRY_MARGIN_MS;+ if (ttlMs <= 0) return;++ const redis = await getClient();+ if (!redis) return;++ await redis+ .set(+ RedisKeys.botReply.dingtalkSessionWebhook(applicationId, threadId),+ JSON.stringify(webhook),+ { px: ttlMs },+ )+ .catch(() => undefined);+ },++ async getDingTalkSessionWebhook(+ applicationId: string,+ threadId: string,+ ): Promise<DingTalkSessionWebhook | undefined> {+ const redis = await getClient();+ if (!redis) return undefined;++ const raw = await redis+ .get(RedisKeys.botReply.dingtalkSessionWebhook(applicationId, threadId))+ .catch(() => null);+ if (!raw) return undefined;++ try {+ const parsed = JSON.parse(raw) as DingTalkSessionWebhook;+ if (typeof parsed.url !== 'string' || typeof parsed.expiresAt !== 'number') return undefined;+ if (parsed.expiresAt - EXPIRY_MARGIN_MS <= Date.now()) return undefined;+ return parsed;+ } catch {+ return undefined;+ }+ },++ /** Drop a route DingTalk rejected, so later replies go straight to the OpenAPI. */+ async forgetDingTalkSessionWebhook(applicationId: string, threadId: string): Promise<void> {+ const redis = await getClient();+ if (!redis) return;++ await redis+ .del(RedisKeys.botReply.dingtalkSessionWebhook(applicationId, threadId))+ .catch(() => undefined);+ },+};diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex a7e6c5add44..15974a5cd10 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -2,6 +2,7 @@ import { agentDocumentIndex } from './agentDocumentIndex';import { agentIdentity } from './agentIdentity';import { agentRunSlots } from './agentRunSlots';import { agentSignal } from './agentSignal';+import { botReply } from './botReply';import { botWake } from './botWake';import { deviceSystemInfo } from './deviceSystemInfo';import { linear } from './linear';@@ -18,6 +19,7 @@ export const redisService = {agentIdentity,agentRunSlots,agentSignal,+ botReply,botWake,deviceSystemInfo,linear,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.tsindex 9daf727a74a..1b8bb5eeaed 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts@@ -203,6 +203,7 @@ const resolveCredentials = async (/** Platforms the message tool can reach through a per-agent bot provider. */const PROVIDER_PLATFORMS = [+ 'dingtalk','discord','feishu','imessage',diff --git a/docs/usage/channels/dingtalk.mdx b/docs/usage/channels/dingtalk.mdxnew file mode 100644index 00000000000..413a3851339--- /dev/null+++ b/docs/usage/channels/dingtalk.mdx@@ -0,0 +1,223 @@+---+title: Connect LobeHub to DingTalk (钉钉)+description: >-+ Learn how to create a DingTalk internal app robot and connect it to your+ LobeHub agent as a message channel, enabling your AI assistant to chat with+ team members in DingTalk single chats and group @-mentions.+tags:+ - DingTalk+ - 钉钉+ - Message Channels+ - Bot Setup+ - Integration+---++# Connect LobeHub to DingTalk (钉钉)++By connecting a DingTalk channel to your LobeHub agent, members of your organization can talk to the AI assistant directly in DingTalk, through single (one-on-one) chats and by @-mentioning the robot in group chats.++## Prerequisites++- A LobeHub account with an active subscription+- A DingTalk organization account with permission to create internal apps (企业内部应用) in the DingTalk developer console++## Connection Modes++LobeHub supports two connection modes for DingTalk robots:++- **WebSocket** — Uses DingTalk's **Stream mode** (Stream 模式): LobeHub keeps an outbound long-lived connection to DingTalk, so no public callback URL is required. This is DingTalk's recommended mode and the default for new bots.+- **Webhook** — Uses DingTalk's **HTTP callback** (HTTP 回调) mode: DingTalk posts each message to a LobeHub callback URL. Use this mode if your robot already has a message receiving address configured.++> **Note:** The mode you select in LobeHub must match the **message receiving mode** (消息接收模式) set on the robot in the DingTalk developer console.++## Step 1: Create a DingTalk Internal App Robot++<Steps>+ ### Open the Developer Console++ Visit [open-dev.dingtalk.com](https://open-dev.dingtalk.com/) and sign in with your DingTalk organization account.++ ### Create an Internal App++ Go to **应用开发** (App Development) → **企业内部应用** (Internal Apps) and click **创建应用** (Create App). Fill in the app name (e.g., "LobeHub Assistant"), description, and icon, then save.++ ### Copy App Credentials++ Open the app and go to **凭证与基础信息** (Credentials & Basic Info). Copy:++ - **Client ID** (formerly AppKey, usually starts with `ding`)+ - **Client Secret** (formerly AppSecret)++ > **Important:** Keep your Client Secret confidential. Never share it in a group chat or a public screenshot.++ ### Add the Robot Capability++ In the app, go to **添加应用能力** (Add App Capability) and add **机器人** (Robot). Fill in the robot information, such as its name, avatar, and description.++ ### Set the Message Receiving Mode++ On the robot configuration page, set **消息接收模式** (Message Receiving Mode):++ - **Stream 模式** (Stream mode) — Matches LobeHub's default **WebSocket** connection mode. No callback address is needed.+ - **HTTP 回调** (HTTP callback) — For LobeHub's **Webhook** mode. You will paste the LobeHub callback URL here after Step 2.++ Save the robot configuration.++ ### Grant Permissions++ Go to **权限管理** (Permission Management) and grant:++ - `qyapi_robot_sendmsg` — **企业内机器人发送消息权限** (permission for the internal robot to send messages). Required so the robot can send replies outside the short-lived reply session, such as proactive direct messages and group sends.++ If you want the agent to read files, images, or other attachments that users send, it is also recommended to grant the robot permission for downloading files from messages it receives (机器人接收消息的文件下载).+</Steps>++## Step 2: Configure DingTalk in LobeHub++<Steps>+ ### Open Channel Settings++ In LobeHub, navigate to your agent's settings, then select the **Channels** tab. Click **DingTalk** from the platform list.++ ### Fill in App Credentials++ Enter the following fields:++ - **Client ID (AppKey)** — The Client ID from your DingTalk app+ - **Client Secret (AppSecret)** — The Client Secret from your DingTalk app+ - **RobotCode** (optional) — Leave blank in most cases. An internal-app robot's RobotCode is its Client ID, which LobeHub uses when this field is empty. Fill it in only if the robot page shows a different code.++ ### Select Connection Mode++ In **Advanced Settings**, choose the **Connection Mode**:++ - **WebSocket** (default) — For robots using **Stream 模式**.+ - **Webhook** — For robots using **HTTP 回调**. After saving, copy the callback URL for the next step.++ ### Save Configuration++ Click **Save Configuration**. LobeHub saves the bot, then connects it by checking the credentials against DingTalk's access token endpoint:++ - With an invalid Client ID or Client Secret, the configuration is still saved but the connection fails, and the page shows the error from DingTalk. Fix the credentials and save again to reconnect.+ - Permission, network, and rate-limit problems reported by DingTalk are shown so you can fix them and try again.++ Your credentials are encrypted and stored securely.++ - In **WebSocket mode**, LobeHub connects to DingTalk over Stream mode automatically.+ - In **Webhook mode**, a **Webhook URL** is shown after saving. Go back to the robot configuration in the DingTalk developer console and paste it as the robot's message receiving address (消息接收地址), then save.+</Steps>++### Signature and Encryption in Webhook Mode++With HTTP callbacks, you don't need to configure any extra signature or encryption parameters in LobeHub or DingTalk:++- **Signature:** DingTalk sends a `timestamp` (Unix milliseconds) and a `sign` header with each callback. LobeHub uses your **Client Secret** to compute `Base64(HmacSHA256(timestamp + "\n" + Client Secret))` and compares the result. A request is rejected with `401` if the signature is missing or doesn't match, or if `timestamp` differs from the current time by more than 1 hour.+- **Encryption:** The robot message callback body is plain JSON, so there is no Token or `aes_key` to fill in. Those two values under DingTalk's **Event Subscription** (事件订阅) are not used for this callback. HTTPS protects the callback content, so the **Webhook URL** must be a publicly reachable HTTPS address. LobeHub Cloud already meets this; on a self-hosted deployment, open LobeHub through its public HTTPS domain before copying the URL.++> **After rotating the Client Secret:** Update it in LobeHub as well. Otherwise DingTalk's callbacks are rejected for a signature mismatch and the robot stops replying.++## Step 3: Publish the App++<Steps>+ ### Create and Publish a Version++ In the DingTalk developer console, go to **版本管理与发布** (Version Management & Release), create a new version, and publish it. Internal app releases do not go through a platform review.++ ### Set the Visibility Range++ When publishing, set the **可见范围** (visibility range) to include the members or departments who should use the robot. Members outside the range cannot find or chat with it.+</Steps>++## Step 4: Test the Connection++Back in LobeHub's channel settings, click **Test Connection** to verify the credentials. Then, in DingTalk, search for the robot by name and send it a message in a single chat. The robot should reply through your LobeHub agent.++## Set Your Platform Identity (Recommended)++One optional field under **Advanced Settings** carries a lot of weight in day-to-day use — fill it in once and most surprises go away.++### Your Platform User ID++This is your own DingTalk `userId` (staff ID, 员工 ID) inside your organization — **not** your phone number or DingTalk ID shown on your profile. It is used by:++- **Pairing approval** — required when **DM Policy** is set to **Pairing**, since `/approve <code>` is the owner's command and the runtime checks the sender against this ID.+- **AI tools push** — lets the agent reach you proactively (reminders, notifications) by mapping its internal user reference to your DingTalk account.+- **Anti-lockout** — auto-trusted by **Allowed Users**, so scoping the bot to teammates won't accidentally lock you out.++To get it, either:++- Open the DingTalk admin console → **Contacts** (通讯录) → your member details, and copy the userId; or+- Send `/whoami` to the robot in a single chat.++Paste it into **Your Platform User ID** in LobeHub's Advanced Settings.++## Add the Robot to a Group Chat++To use the robot in a DingTalk group:++1. Open the group's **群设置** (Group Settings) → **机器人** (Robots) → **添加机器人** (Add Robot)+2. Search for your internal app robot by name and add it+3. @-mention the robot in a message to trigger a response++> DingTalk only delivers group messages that @-mention the robot. In single chats, the robot receives every message.++## Access Policies++Two independent policies gate inbound traffic. Both default to **Open**.++### Allowed User IDs (global)++A populated **Allowed Users** list is a global gate — single chats *and* group `@mentions` are restricted to listed DingTalk `userId` values. Empty means "no user-level filter".++### DM Policy++- **Open (default)** — Any member who can see the robot can chat with it one-on-one (subject to the global allowlist when set).+- **Allowlist** — Single chats require the sender to be in **Allowed Users**. Differs from `Open` only when the list is empty: `Allowlist` then fails closed (no single chats).+- **Pairing** — Same gate as `Allowlist`, but a non-listed sender receives a one-time pairing code instead of a flat rejection. Approve via `/approve <code>` and the applicant is auto-appended to **Allowed Users**. Requires **Your Platform User ID** to be set and a configured Redis backend.+- **Disabled** — The robot ignores all single chats and only responds to group `@mentions`.++### Group Policy++Controls which DingTalk groups the robot will respond in.++- **Open (default)** — Respond to `@mentions` in any group the robot has been added to.+- **Allowlist** — Respond only in groups whose conversation ID (`openConversationId`, usually starts with `cid`) is listed in **Allowed Channels**.+- **Disabled** — Ignore all group traffic; the robot only responds to single chats.++See the [Channels overview](/docs/usage/channels/overview#direct-message-policy) for cross-platform details.++## Configuration Reference++| Field | Required | Description |+| ----------------------------- | -------- | ----------------------------------------------------------------------------------------------- |+| **Client ID (AppKey)** | Yes | Your DingTalk internal app's Client ID |+| **Client Secret (AppSecret)** | Yes | Your DingTalk internal app's Client Secret (encrypted at rest) |+| **RobotCode** | No | Defaults to the Client ID. Fill in only if the robot page shows a different code |+| **Connection Mode** | No | `websocket` (default, DingTalk Stream mode) or `webhook` (DingTalk HTTP callback) |+| **Webhook URL** | — | Shown after saving in Webhook mode; paste into the robot's message receiving address |+| **Character Limit** | No | Maximum characters per reply message (default and maximum: 4000) |+| **Concurrency Mode** | No | `queue` (default), `burst`, or `debounce` — how concurrent messages are batched |+| **Allowed Users** | No | DingTalk `userId` values. Global gate — applies to single chats and group @mentions |+| **DM Policy** | No | `open` (default), `allowlist`, `pairing`, or `disabled` — who is allowed to chat with the robot |+| **Group Policy** | No | `open` (default), `allowlist`, or `disabled` — where the robot responds to @mentions |+| **Allowed Channels** | No | DingTalk group conversation IDs. Used when Group Policy is Allowlist |++## Limitations++- **No message editing** — DingTalk robot messages cannot be edited, so intermediate steps are not streamed. Only the final reply is sent.+- **No reactions** — DingTalk robots have no reaction API.+- **Group attachments** — When users @-mention the robot in a group, DingTalk does not deliver audio, video, or file messages; send them in a single chat instead.+- **Outbound files** — Images with a public URL are sent as images; other files the agent sends are delivered as links.++## Troubleshooting++- **Connection fails with invalid credentials:** Copy the Client ID and Client Secret again from **凭证与基础信息** without extra spaces.+- **Connection fails with a permission or network error:** Check that the app is not disabled, that any IP allowlist on the app allows LobeHub, and try again later if DingTalk reports rate limiting.+- **Connecting fails and asks you to switch the connection mode:** WebSocket mode is not available on this deployment. Switch to **Webhook** and set the robot to **HTTP 回调**.+- **Bot not receiving messages (WebSocket mode):** Confirm the robot's message receiving mode is **Stream 模式** and the app version containing the robot has been published.+- **Bot not receiving messages (Webhook mode):** Confirm the robot uses **HTTP 回调** and the message receiving address matches the **Webhook URL** shown in LobeHub.+- **Callbacks return `401 Invalid signature`:** The Client Secret in LobeHub doesn't match the app's current Client Secret (common after rotating it), or the callback's `timestamp` differs from the current time by more than 1 hour. Copy the Client Secret again and save. If requests pass through a proxy, confirm it preserves the `timestamp` and `sign` headers.+- **Robot cannot be found:** Check the app's visibility range (可见范围) includes the user, and that the app has been published.+- **Bot ignores group messages:** Make sure the robot was added to the group and the message @-mentions it. Check **Group Policy** in Advanced Settings.+- **Bot ignores single chats:** Check **DM Policy**. If it is `Allowlist`, confirm the sender's `userId` is listed in **Allowed Users**.+- **Replies stop after a while or proactive messages fail:** Confirm `qyapi_robot_sendmsg` is granted in **权限管理**.diff --git a/docs/usage/channels/dingtalk.zh-CN.mdx b/docs/usage/channels/dingtalk.zh-CN.mdxnew file mode 100644index 00000000000..67d79577534--- /dev/null+++ b/docs/usage/channels/dingtalk.zh-CN.mdx@@ -0,0 +1,220 @@+---+title: 将 LobeHub 连接到钉钉+description: 了解如何创建钉钉企业内部应用机器人并将其连接到您的 LobeHub 代理作为消息渠道,使您的 AI 助手能够在钉钉单聊和群聊 @ 中与团队成员互动。+tags:+ - 钉钉+ - DingTalk+ - 消息渠道+ - 机器人设置+ - 集成+---++# 将 LobeHub 连接到钉钉++通过将钉钉渠道连接到您的 LobeHub 代理,组织内的成员可以直接在钉钉中与 AI 助手对话:既可以单聊,也可以在群聊中 @ 机器人。++## 前置条件++- 一个拥有有效订阅的 LobeHub 账户+- 一个钉钉组织账号,并具备在钉钉开发者后台创建企业内部应用的权限++## 连接模式++LobeHub 支持两种钉钉机器人连接模式:++- **WebSocket** — 对应钉钉的 **Stream 模式**:LobeHub 主动与钉钉建立出站长连接,无需公网回调地址。这是钉钉官方推荐的方式,也是新机器人的默认模式。+- **Webhook** — 对应钉钉的 **HTTP 回调** 模式:钉钉把每条消息推送到 LobeHub 的回调地址。如果您的机器人已经配置了消息接收地址,请使用此模式。++> **注意:** LobeHub 中选择的连接模式必须与钉钉开发者后台中机器人的 **消息接收模式** 一致。++## 第一步:创建钉钉企业内部应用机器人++<Steps>+ ### 打开开发者后台++ 访问 [open-dev.dingtalk.com](https://open-dev.dingtalk.com/),使用您的钉钉组织账号登录。++ ### 创建企业内部应用++ 进入 **应用开发** → **企业内部应用**,点击 **创建应用**。填写应用名称(例如 "LobeHub 助手")、描述和图标,然后保存。++ ### 复制应用凭证++ 打开应用,进入 **凭证与基础信息**,复制以下内容:++ - **Client ID**(原 AppKey,通常以 `ding` 开头)+ - **Client Secret**(原 AppSecret)++ > **重要提示:** 请妥善保管您的 Client Secret,切勿发到群聊或出现在公开截图中。++ ### 添加机器人能力++ 在应用中进入 **添加应用能力**,添加 **机器人**。填写机器人名称、头像、简介等信息。++ ### 设置消息接收模式++ 在机器人配置页设置 **消息接收模式**:++ - **Stream 模式** — 对应 LobeHub 默认的 **WebSocket** 连接模式,无需填写回调地址。+ - **HTTP 回调** — 对应 LobeHub 的 **Webhook** 模式。完成第二步后,再把 LobeHub 的回调地址粘贴到这里。++ 保存机器人配置。++ ### 开通权限++ 进入 **权限管理**,开通:++ - `qyapi_robot_sendmsg` — **企业内机器人发送消息权限**。机器人在临时回复会话之外发送消息(例如主动单聊、群发)时需要此权限。++ 如果希望助手读取用户发送的文件、图片等附件,建议同时开通机器人接收消息的文件下载相关权限。+</Steps>++## 第二步:在 LobeHub 中配置钉钉++<Steps>+ ### 打开渠道设置++ 在 LobeHub 中,导航到您的代理设置,然后选择 **渠道** 标签页。从平台列表中点击 **DingTalk**(钉钉)。++ ### 输入应用凭证++ 填写以下字段:++ - **Client ID(AppKey)** — 钉钉应用的 Client ID+ - **Client Secret(AppSecret)** — 钉钉应用的 Client Secret+ - **RobotCode**(可选)— 大多数情况下留空即可。企业内部应用机器人的 RobotCode 就是 Client ID,留空时自动使用。仅当机器人页面显示的编码不同时填写。++ ### 选择连接模式++ 在 **高级设置** 中,选择 **连接模式**:++ - **WebSocket**(默认)— 适用于使用 **Stream 模式** 的机器人+ - **Webhook** — 适用于使用 **HTTP 回调** 的机器人。保存后复制回调地址用于下一步++ ### 保存配置++ 点击 **保存配置**。LobeHub 会保存机器人,然后通过钉钉的 accessToken 接口校验凭证并建立连接:++ - Client ID 或 Client Secret 无效时,配置仍会保存,但连接失败,页面会显示钉钉返回的错误。修正凭证后再次保存即可重新连接。+ - 钉钉返回的权限、网络或限流问题也会提示出来,修正后重试即可。++ 您的凭证将被加密并安全存储。++ - 在 **WebSocket 模式** 下,LobeHub 会自动通过 Stream 模式连接钉钉。+ - 在 **Webhook 模式** 下,保存后将显示 **Webhook URL**。回到钉钉开发者后台的机器人配置,把它粘贴为机器人的消息接收地址并保存。+</Steps>++### Webhook 模式的签名与加密++使用 HTTP 回调时,无需在 LobeHub 或钉钉中配置额外的签名或加密参数:++- **签名:** 钉钉在每次回调的请求头中携带 `timestamp`(毫秒时间戳)和 `sign`。LobeHub 使用您填写的 **Client Secret** 按 `Base64(HmacSHA256(timestamp + "\n" + Client Secret))` 计算并比对。签名缺失、不匹配,或 `timestamp` 与当前时间相差超过 1 小时,请求都会被拒绝并返回 `401`。+- **加密:** 机器人消息回调的请求体是明文 JSON,因此没有 Token 或 `aes_key` 需要填写。钉钉 **事件订阅** 中的这两项不用于此回调。回调内容由 HTTPS 保护,因此 **Webhook URL** 必须是公网可访问的 HTTPS 地址。LobeHub Cloud 已满足此要求;自托管部署请通过公网 HTTPS 域名访问 LobeHub 后再复制该地址。++> **轮换 Client Secret 后:** 请同时在 LobeHub 中更新。否则钉钉的回调会因签名不匹配而被拒绝,机器人将不再回复。++## 第三步:发布应用++<Steps>+ ### 创建并发布版本++ 在钉钉开发者后台进入 **版本管理与发布**,创建新版本并发布。企业内部应用发布无需平台审核。++ ### 设置可见范围++ 发布时设置 **可见范围**,把需要使用机器人的成员或部门包含进来。不在可见范围内的成员无法搜索到机器人,也无法与它对话。+</Steps>++## 第四步:测试连接++在 LobeHub 的渠道设置中点击 **测试连接** 以验证凭证。然后在钉钉中按名称搜索机器人,单聊发送一条消息。机器人应通过您的 LobeHub 代理进行回复。++## 填写你的平台身份(推荐)++**高级设置**里有一个可选字段影响日常使用体验,建议一开始就填好。++### 你的平台用户 ID++也就是你在组织内的钉钉 `userId`(员工 ID)——**不是**手机号,也不是个人资料里的钉钉号。用于:++- **配对审批** — 当 **私信策略** 为 **配对审批** 时为必填项,`/approve <code>` 是属主命令,runtime 会用这个 ID 校验发起人。+- **AI 工具主动推送** — 让 Agent 能主动联系你(提醒、通知),把内部用户引用映射到你的钉钉账号。+- **防自锁** — 自动被 **允许的用户** 信任,给同事收紧 bot 时不会把自己挡在外面。++获取方式(任选其一):++- 在钉钉管理后台 → **通讯录** → 成员详情中查看 userId;+- 在单聊中给机器人发送 `/whoami`。++把这个 ID 粘贴到 LobeHub 高级设置的 **你的平台用户 ID** 字段。++## 将机器人添加到群聊++要在钉钉群中使用机器人:++1. 打开群的 **群设置** → **机器人** → **添加机器人**+2. 按名称搜索您的企业内部应用机器人并添加+3. 在消息中 @ 机器人以触发回复++> 钉钉只会推送 @ 机器人的群消息;单聊中机器人会收到全部消息。++## 接入策略++两个独立的策略控制入站消息,默认都为 **开放**。++### 允许的用户 ID(全局)++填入 **允许的用户** 后,单聊**和**群聊 `@` 都必须来自列表里的钉钉 `userId`。留空则不做用户级过滤。++### 私信策略++- **开放 (Open)(默认)** — 可见范围内的任何成员都可以与机器人单聊(若设置了全局白名单则受其约束)。+- **白名单 (Allowlist)** — 单聊需要发送者在 **允许的用户** 里。和 `Open` 的差别在白名单为空时:`Allowlist` 模式**全部拒绝**。+- **配对审批 (Pairing)** — 与 `Allowlist` 共享同一份名单,但非名单用户被拒后会收到一次性配对码,由你(属主)通过 `/approve <code>` 审批。审批通过的用户会被自动追加到 **允许的用户**。需先填 **你的平台用户 ID**,并需要部署 Redis。+- **禁用 (Disabled)** — 机器人忽略所有单聊,只在群聊里被 `@` 时回复。++### 群组策略++控制机器人会在哪些钉钉群里响应。++- **开放 (Open)(默认)** — 在机器人加入的任何群里被 `@` 都响应。+- **白名单 (Allowlist)** — 只在 **允许的频道** 列出的群里响应(填写群会话 ID `openConversationId`,通常以 `cid` 开头)。+- **禁用 (Disabled)** — 忽略所有群聊流量,机器人只接受单聊。++跨平台细节见 [渠道概览](/zh/docs/usage/channels/overview#direct-message-policy)。++## 配置参考++| 字段 | 是否必需 | 描述 |+| ---------------------------- | ---- | ----------------------------------------------------------- |+| **Client ID(AppKey)** | 是 | 钉钉企业内部应用的 Client ID |+| **Client Secret(AppSecret)** | 是 | 钉钉企业内部应用的 Client Secret(加密存储) |+| **RobotCode** | 否 | 默认使用 Client ID。仅当机器人页面显示的编码不同时填写 |+| **连接模式** | 否 | `websocket`(默认,钉钉 Stream 模式)或 `webhook`(钉钉 HTTP 回调) |+| **Webhook URL** | — | Webhook 模式保存后显示;粘贴到机器人的消息接收地址 |+| **字符限制** | 否 | 每条回复消息的最大字符数(默认值和上限均为 4000) |+| **并发模式** | 否 | `queue`(默认)、`burst` 或 `debounce` — 并发消息的合并方式 |+| **允许的用户** | 否 | 钉钉 `userId`。全局闸门 — 单聊和群聊 @ 都受其约束 |+| **私信策略** | 否 | `open`(默认)、`allowlist`、`pairing` 或 `disabled` — 控制谁可以与机器人单聊 |+| **群组策略** | 否 | `open`(默认)、`allowlist` 或 `disabled` — 控制机器人在哪些群中响应 |+| **允许的频道** | 否 | 钉钉群会话 ID。仅在群组策略为白名单时使用 |++## 功能限制++- **不支持消息编辑** — 钉钉机器人消息无法编辑,因此不会流式展示中间步骤,只发送最终回复。+- **不支持表情回应** — 钉钉机器人没有表情回应接口。+- **群聊附件** — 在群里 @ 机器人时,钉钉不会推送语音、视频和文件消息;请改在单聊中发送。+- **出站文件** — 有公网地址的图片会以图片形式发送;助手发送的其他文件会以链接形式送达。++## 故障排除++- **连接时提示凭证无效:** 从 **凭证与基础信息** 重新复制 Client ID 和 Client Secret,注意不要带空格。+- **连接时提示权限或网络错误:** 确认应用未被停用、应用的 IP 白名单(如有)允许 LobeHub 访问;如果钉钉提示限流,请稍后重试。+- **连接失败并提示切换连接模式:** 当前部署不支持 WebSocket 模式。请切换到 **Webhook**,并把机器人设置为 **HTTP 回调**。+- **收不到消息(WebSocket 模式):** 确认机器人的消息接收模式为 **Stream 模式**,并且包含机器人能力的应用版本已经发布。+- **收不到消息(Webhook 模式):** 确认机器人使用 **HTTP 回调**,且消息接收地址与 LobeHub 中显示的 **Webhook URL** 一致。+- **回调返回 `401 Invalid signature`:** LobeHub 中的 Client Secret 与该应用当前的 Client Secret 不一致(常见于轮换之后),或回调的 `timestamp` 与当前时间相差超过 1 小时。重新复制 Client Secret 并保存;如果请求经过代理转发,确认 `timestamp` 和 `sign` 请求头被原样保留。+- **搜索不到机器人:** 检查应用的 **可见范围** 是否包含该成员,以及应用是否已发布。+- **群聊不回复:** 确认机器人已加入该群,且消息中 @ 了机器人;同时检查高级设置中的 **群组策略**。+- **单聊不回复:** 检查 **私信策略**。如果是 `Allowlist`,确认发送者的 `userId` 已在 **允许的用户** 中。+- **一段时间后回复失败或无法主动发消息:** 确认已在 **权限管理** 中开通 `qyapi_robot_sendmsg`。diff --git a/docs/usage/channels/overview.mdx b/docs/usage/channels/overview.mdxindex ca1fc0b45cd..65c74096980 100644--- a/docs/usage/channels/overview.mdx+++ b/docs/usage/channels/overview.mdx@@ -2,7 +2,7 @@title: Channels Overviewdescription: >-Connect your LobeHub agents to external messaging platforms like Discord,- Slack, Telegram, LINE, QQ, WeChat, Feishu, and Lark; check the announced+ Slack, Telegram, LINE, QQ, WeChat, Feishu, Lark, and DingTalk; check the announcedstatus of WhatsApp and iMessage; and let users interact with AI assistantsdirectly in their favorite chat apps.tags:@@ -17,6 +17,7 @@ tags:- Feishu- Lark+ - DingTalk- iMessage---@@ -63,6 +64,7 @@ Access policies decide whether a Channel is private or shared. You can restrict| [WeCom](/docs/usage/channels/wecom) | Connect a WeCom AI bot for direct chats and group @-mentions (Cloud, or single-instance self-hosts) || [Feishu (飞书)](/docs/usage/channels/feishu) | Connect to Feishu for team collaboration (Chinese version) || [Lark](/docs/usage/channels/lark) | Connect to Lark for team collaboration (international version) |+| [DingTalk (钉钉)](/docs/usage/channels/dingtalk) | Connect a DingTalk internal app robot for single chats and group @-mentions |### Coming Soon@@ -93,6 +95,7 @@ Each Channel belongs to the current Agent. LobeHub passes incoming platform mess- [WeCom (企业微信)](/docs/usage/channels/wecom)- [Feishu (飞书)](/docs/usage/channels/feishu)- [Lark](/docs/usage/channels/lark)+ - [DingTalk (钉钉)](/docs/usage/channels/dingtalk)WhatsApp and iMessage currently appear as **Coming Soon** and cannot be configured as generally available channels. See the [WhatsApp status page](/docs/usage/channels/whatsapp) and [iMessage preview page](/docs/usage/channels/imessage).@@ -102,13 +105,13 @@ If **WeChat** is absent from the list, check that your personal account meets thText messages are supported across all platforms. Some features vary by platform:-| Feature | Discord | Slack | Telegram | LINE | QQ | WeChat | Feishu | Lark |-| ---------------------- | ------- | ----- | -------- | ------- | --- | ----------- | ------- | ------- |-| Text messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |-| Direct messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |-| Group chats | Yes | Yes | Yes | Yes | Yes | Unconfirmed | Yes | Yes |-| Reactions | Yes | Yes | Yes | No | No | No | Partial | Partial |-| Image/file attachments | Yes | Yes | Yes | Inbound | Yes | Yes | Yes | Yes |+| Feature | Discord | Slack | Telegram | LINE | QQ | WeChat | Feishu | Lark | DingTalk |+| ---------------------- | ------- | ----- | -------- | ------- | --- | ----------- | ------- | ------- | -------- |+| Text messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |+| Direct messages | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |+| Group chats | Yes | Yes | Yes | Yes | Yes | Unconfirmed | Yes | Yes | Yes |+| Reactions | Yes | Yes | Yes | No | No | No | Partial | Partial | No |+| Image/file attachments | Yes | Yes | Yes | Inbound | Yes | Yes | Yes | Yes | Partial |Repository documentation does not confirm WeChat group support. This guide covers direct messages only. The July 8 announcement changes paid access, not group support. See [WeChat](/docs/usage/channels/wechat).@@ -163,6 +166,7 @@ Platforms that expose both policies default to **Open**. To restrict access, sel- **Telegram** — Ask the user to message [@userinfobot](https://t.me/userinfobot), or read `from.id` from the bot's incoming update.- **QQ** — Use the `openid` from the OpenAPI event payload — `user_openid` for private (C2C) messages, `member_openid` for group messages (the public-facing QQ number is not guaranteed to be the platform ID).- **Feishu / Lark** — Use the `open_id` from the event payload, or the **User ID** displayed in the developer portal.+- **DingTalk** — Use the member's `userId` (staff ID) from the DingTalk admin console → **Contacts** → member details, or have them send `/whoami` to the robot in a single chat.### Finding a channel / group ID@@ -170,3 +174,4 @@ Platforms that expose both policies default to **Open**. To restrict access, sel- **Slack** — Open the channel's About panel and copy the channel ID at the bottom (starts with `C`).- **Telegram** — Forward a message from the group to [@userinfobot](https://t.me/userinfobot), or read `chat.id` from the bot's incoming update (group IDs are negative).- **Feishu / Lark** — Use the `chat_id` from the event payload.+- **DingTalk** — Use the group's `openConversationId` (usually starts with `cid`) from the event payload.diff --git a/docs/usage/channels/overview.zh-CN.mdx b/docs/usage/channels/overview.zh-CN.mdxindex 18a3f1e4b1e..ad3dbfabd6c 100644--- a/docs/usage/channels/overview.zh-CN.mdx+++ b/docs/usage/channels/overview.zh-CN.mdx@@ -1,8 +1,8 @@---title: 渠道概览description: >-- 将 LobeHub 代理连接到外部消息平台,如 Discord、Slack、Telegram、LINE、QQ、微信、飞书和- Lark;查看 WhatsApp 与 iMessage 的预告状态,让用户可以直接在他们喜欢的聊天应用中与 AI 助手互动。+ 将 LobeHub 代理连接到外部消息平台,如 Discord、Slack、Telegram、LINE、QQ、微信、飞书、+ Lark 和钉钉;查看 WhatsApp 与 iMessage 的预告状态,让用户可以直接在他们喜欢的聊天应用中与 AI 助手互动。tags:- 渠道- 消息渠道@@ -15,6 +15,7 @@ tags:- 微信- 飞书- Lark+ - 钉钉- iMessage---@@ -61,6 +62,7 @@ tags:| [企业微信](/zh/docs/usage/channels/wecom) | 智能机器人长连接,支持单聊和内部群 @(Cloud,或单实例长驻自部署) || [飞书](/zh/docs/usage/channels/feishu) | 连接到飞书,用于团队协作(中国版) || [Lark](/zh/docs/usage/channels/lark) | 连接到 Lark,用于团队协作(国际版) |+| [钉钉](/zh/docs/usage/channels/dingtalk) | 连接钉钉企业内部应用机器人,用于单聊和群聊 @ |### 即将上线@@ -91,6 +93,7 @@ tags:- [企业微信](/zh/docs/usage/channels/wecom)- [飞书](/zh/docs/usage/channels/feishu)- [Lark](/zh/docs/usage/channels/lark)+ - [钉钉](/zh/docs/usage/channels/dingtalk)WhatsApp 与 iMessage 当前显示为**即将上线**,不能按已开放渠道进行配置。可分别查看 [WhatsApp 状态页](/zh/docs/usage/channels/whatsapp)和 [iMessage 预告页](/zh/docs/usage/channels/imessage)。@@ -100,13 +103,13 @@ WhatsApp 与 iMessage 当前显示为**即将上线**,不能按已开放渠道所有平台均支持文本消息。某些功能因平台而异:-| 功能 | Discord | Slack | Telegram | LINE | QQ | 微信 | 飞书 | Lark |-| --------- | ------- | ----- | -------- | ---- | -- | --- | ---- | ---- |-| 文本消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |-| 私人消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |-| 群组聊天 | 是 | 是 | 是 | 是 | 是 | 未确认 | 是 | 是 |-| 表情反应 | 是 | 是 | 是 | 否 | 否 | 否 | 部分支持 | 部分支持 |-| 图片 / 文件附件 | 是 | 是 | 是 | 仅入站 | 是 | 是 | 是 | 是 |+| 功能 | Discord | Slack | Telegram | LINE | QQ | 微信 | 飞书 | Lark | 钉钉 |+| --------- | ------- | ----- | -------- | ---- | -- | --- | ---- | ---- | ---- |+| 文本消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |+| 私人消息 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |+| 群组聊天 | 是 | 是 | 是 | 是 | 是 | 未确认 | 是 | 是 | 是 |+| 表情反应 | 是 | 是 | 是 | 否 | 否 | 否 | 部分支持 | 部分支持 | 否 |+| 图片 / 文件附件 | 是 | 是 | 是 | 仅入站 | 是 | 是 | 是 | 是 | 部分支持 |微信群聊支持尚未从仓库资料中确认,本指南仅说明私聊接入。2026-07-08 公告说明的是付费访问调整,未宣布群聊支持。详见[微信渠道](/zh/docs/usage/channels/wechat)。@@ -161,6 +164,7 @@ WhatsApp 与 iMessage 当前显示为**即将上线**,不能按已开放渠道- **Telegram** — 让用户私信 [@userinfobot](https://t.me/userinfobot),或者从机器人收到的 update 里读 `from.id`。- **QQ** — 使用 OpenAPI 事件 payload 里的 `openid` —— 私聊(C2C)消息用 `user_openid`,群聊消息用 `member_openid`(用户对外可见的 QQ 号不一定就是平台 ID)。- **飞书 / Lark** — 使用事件 payload 里的 `open_id`,或开发者后台显示的 **User ID**。+- **钉钉** — 使用成员的 `userId`(员工 ID),可在钉钉管理后台 → **通讯录** → 成员详情中查看,或让对方在单聊中给机器人发送 `/whoami`。### 如何获取频道 / 群组 ID@@ -168,3 +172,4 @@ WhatsApp 与 iMessage 当前显示为**即将上线**,不能按已开放渠道- **Slack** — 打开频道详情面板,底部能看到频道 ID(以 `C` 开头)。- **Telegram** — 把群里的一条消息转发给 [@userinfobot](https://t.me/userinfobot),或者从机器人收到的 update 里读 `chat.id`(群组是负数)。- **飞书 / Lark** — 使用事件 payload 里的 `chat_id`。+- **钉钉** — 使用事件 payload 里群的 `openConversationId`(通常以 `cid` 开头)。diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 243d2bc4fac..feca825632b 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -163,6 +163,7 @@"channel.connectionError.rate_limited": "The platform is rate limiting this bot. Wait a moment and try again.","channel.connectionError.session_expired": "The bot session has expired. Save the bot again to reconnect it.","channel.connectionError.upstream_unavailable": "The platform service is temporarily unavailable. LobeHub will try again later.",+ "channel.connectionError.webhook_mode_required": "This deployment can only connect this platform in Webhook mode. Switch the connection mode to Webhook and update the callback address in the platform console.","channel.connectionMode": "Connection Mode","channel.connectionModeHint": "How the platform delivers events to the bot","channel.connectionModeWebSocket": "WebSocket",@@ -187,6 +188,15 @@"channel.deviceAllowFromHint": "Listed people can read and write files and run commands on your devices through the bot.","channel.devicePolicy": "Device Access","channel.devicePolicyHint": "Who may operate your devices through the bot.",+ "channel.dingtalk.clientId": "Client ID (AppKey)",+ "channel.dingtalk.clientIdHint": "From the DingTalk developer console → your internal app → Credentials & Basic Info. Formerly called AppKey.",+ "channel.dingtalk.clientIdPlaceholder": "e.g. dingxxxxxxxxxxxxxxxx",+ "channel.dingtalk.clientSecret": "Client Secret (AppSecret)",+ "channel.dingtalk.clientSecretHint": "Shown next to the Client ID. Formerly called AppSecret. It will be encrypted and stored securely.",+ "channel.dingtalk.description": "Connect this agent to a DingTalk robot for single chats and group @-mentions.",+ "channel.dingtalk.identifierInvalid": "Use only letters, digits, hyphens and underscores. Copy the value from the DingTalk developer console without spaces.",+ "channel.dingtalk.robotCode": "RobotCode",+ "channel.dingtalk.robotCodeHint": "Optional. An internal-app robot's RobotCode is its Client ID, which is used when this is blank. Fill it in only if the robot page shows a different code.","channel.discard": "Discard","channel.discord.description": "Connect this agent to Discord server for channel chat and direct messages.","channel.displayToolCalls": "Display Tool Calls",@@ -336,6 +346,7 @@"channel.paidFeature.noticeBadge": "Pro soon","channel.paidFeature.title": "Paid plan required","channel.platform.default.description": "Let people reach this agent from {{name}} without switching apps—ideal for anyone who wants help close at hand.",+ "channel.platform.dingtalk.description": "Answer questions and assist work in single chats and group @-mentions—ideal for teams that collaborate in DingTalk.","channel.platform.discord.description": "Support communities in servers and DMs—ideal for moderators, member support, and always-on help.","channel.platform.feishu.description": "Answer questions and assist work directly in chats—ideal for teams that collaborate in Feishu.","channel.platform.imessage.description": "Chat with the agent from Messages through your own Mac—ideal for private, personal assistance.",@@ -360,6 +371,16 @@"channel.qq.webhookMigrationTitle": "Consider migrating to WebSocket mode","channel.quickSetup.connect.desc": "Saves what you filled in above and brings the bot online. Everything else can be changed later.","channel.quickSetup.connect.title": "Save and connect",+ "channel.quickSetup.dingtalk.create.desc": "In the DingTalk developer console, create an internal app, then copy the Client ID and Client Secret from Credentials & Basic Info.",+ "channel.quickSetup.dingtalk.create.title": "Create an internal app",+ "channel.quickSetup.dingtalk.permissions.desc": "Under Permissions, request qyapi_robot_sendmsg so the bot can reply in single and group chats.",+ "channel.quickSetup.dingtalk.permissions.title": "Grant the robot send permission",+ "channel.quickSetup.dingtalk.publish.desc": "Under Version Management, publish and choose who can see the robot. Internal apps go live without review.",+ "channel.quickSetup.dingtalk.publish.title": "Publish a version",+ "channel.quickSetup.dingtalk.robot.desc": "Under App Capabilities, add Robot, fill in its details and set the message receiving mode to Stream mode.",+ "channel.quickSetup.dingtalk.robot.title": "Add the robot and choose Stream mode",+ "channel.quickSetup.dingtalk.robotWebhook.desc": "Under App Capabilities, add Robot, fill in its details, set the message receiving mode to HTTP callback, and paste the Webhook URL shown here after saving as the message receiving address.",+ "channel.quickSetup.dingtalk.robotWebhook.title": "Add the robot and choose HTTP callback","channel.quickSetup.discord.bot.desc": "On the Bot page, click Reset Token and copy it.","channel.quickSetup.discord.bot.title": "Get the bot token","channel.quickSetup.discord.create.desc": "In the Developer Portal, click New Application and name it.",@@ -606,6 +627,7 @@"channel.updateFailed": "Failed to update status","channel.userId": "Your Platform User ID","channel.userIdHint": "Lets AI tools reach you proactively (e.g. reminders); auto-trusted by the global allowlist",+ "channel.userIdHint.dingtalk": "Your DingTalk user ID (staff ID). Find it in the DingTalk admin console → Contacts → member details, or send /whoami to the bot in a direct message.","channel.userIdHint.discord": "Enable Developer Mode (Settings → Advanced), then right-click your avatar → Copy User ID.","channel.userIdHint.feishu": "Feishu Open IDs are per-app, so no console page shows you your own. Once the credentials are in, the app owner's is filled in for you; if nothing appears, use the button below or send /whoami to the bot in a direct message.","channel.userIdHint.imessage": "Use your iMessage handle as seen in BlueBubbles, usually an email address or E.164 phone number.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex bce06279231..b4ce4524d3a 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -163,6 +163,7 @@"channel.connectionError.rate_limited": "平台正在限制该机器人的请求频率,请稍后重试。","channel.connectionError.session_expired": "机器人会话已过期,请重新保存 Bot 配置以建立连接。","channel.connectionError.upstream_unavailable": "平台服务暂时不可用,LobeHub 稍后会自动重试。",+ "channel.connectionError.webhook_mode_required": "当前部署只能以 Webhook 模式连接该平台。请把连接模式切换为 Webhook,并在平台后台更新回调地址。","channel.connectionMode": "连接模式","channel.connectionModeHint": "平台向机器人推送事件的方式","channel.connectionModeWebSocket": "WebSocket",@@ -187,6 +188,15 @@"channel.deviceAllowFromHint": "名单中的成员可以通过机器人在你的设备上读写文件、执行命令。","channel.devicePolicy": "设备权限","channel.devicePolicyHint": "谁可以通过机器人操作你的设备。",+ "channel.dingtalk.clientId": "Client ID(AppKey)",+ "channel.dingtalk.clientIdHint": "在钉钉开发者后台 → 你的企业内部应用 → 凭证与基础信息中获取,原名 AppKey。",+ "channel.dingtalk.clientIdPlaceholder": "例如 dingxxxxxxxxxxxxxxxx",+ "channel.dingtalk.clientSecret": "Client Secret(AppSecret)",+ "channel.dingtalk.clientSecretHint": "与 Client ID 显示在同一页面,原名 AppSecret。将被加密安全存储。",+ "channel.dingtalk.description": "将助手接入钉钉机器人,支持单聊和群聊 @ 机器人。",+ "channel.dingtalk.identifierInvalid": "只能包含字母、数字、连字符和下划线。请从钉钉开发者后台复制,不要带空格。",+ "channel.dingtalk.robotCode": "RobotCode",+ "channel.dingtalk.robotCodeHint": "可选。企业内部应用机器人的 RobotCode 就是 Client ID,留空时自动使用。仅当机器人页面显示的编码不同时填写。","channel.discard": "放弃更改","channel.discord.description": "将助手连接到 Discord 服务器,支持频道聊天和私信。","channel.displayToolCalls": "展示工具调用",@@ -336,6 +346,7 @@"channel.paidFeature.noticeBadge": "即将付费","channel.paidFeature.title": "需要付费套餐","channel.platform.default.description": "无需切换应用即可在 {{name}} 联系智能体,适合希望随时获得帮助的人。",+ "channel.platform.dingtalk.description": "在单聊和群聊 @ 中答疑、协助工作,适合在钉钉协作的团队。","channel.platform.discord.description": "在服务器和私信中提供社区支持,适合需要成员答疑、运营协助和全天候服务的团队。","channel.platform.feishu.description": "直接在飞书聊天中答疑并协助工作,适合日常协作都在飞书完成的团队。","channel.platform.imessage.description": "通过自己的 Mac 在“信息”中与智能体聊天,适合注重私密性的个人助理场景。",@@ -360,6 +371,16 @@"channel.qq.webhookMigrationTitle": "建议迁移至 WebSocket 模式","channel.quickSetup.connect.desc": "保存上面填好的信息,机器人随即上线。其他设置之后随时可以改。","channel.quickSetup.connect.title": "保存并连接",+ "channel.quickSetup.dingtalk.create.desc": "在钉钉开发者后台创建企业内部应用,然后在「凭证与基础信息」中复制 Client ID 和 Client Secret。",+ "channel.quickSetup.dingtalk.create.title": "创建企业内部应用",+ "channel.quickSetup.dingtalk.permissions.desc": "在「权限管理」中申请 qyapi_robot_sendmsg,机器人才能在单聊和群聊中回复。",+ "channel.quickSetup.dingtalk.permissions.title": "开通机器人发消息权限",+ "channel.quickSetup.dingtalk.publish.desc": "在「版本管理与发布」中发布,并设置机器人的可见范围。企业内部应用发布无需审核。",+ "channel.quickSetup.dingtalk.publish.title": "发布版本",+ "channel.quickSetup.dingtalk.robot.desc": "在「添加应用能力」中添加机器人,填写机器人信息,并将消息接收模式设为 Stream 模式。",+ "channel.quickSetup.dingtalk.robot.title": "添加机器人并选择 Stream 模式",+ "channel.quickSetup.dingtalk.robotWebhook.desc": "在“添加应用能力”中添加机器人并填写信息,把消息接收模式设置为 HTTP 回调,再把保存后这里显示的 Webhook URL 填为消息接收地址。",+ "channel.quickSetup.dingtalk.robotWebhook.title": "添加机器人并选择 HTTP 回调","channel.quickSetup.discord.bot.desc": "在 Bot 页面点 Reset Token 并复制。","channel.quickSetup.discord.bot.title": "获取 Bot Token","channel.quickSetup.discord.create.desc": "在开发者后台点 New Application 并命名。",@@ -606,6 +627,7 @@"channel.updateFailed": "更新状态失败","channel.userId": "你的平台用户 ID","channel.userIdHint": "供 AI 工具主动联系你(如提醒、通知),并自动加入全局白名单",+ "channel.userIdHint.dingtalk": "你的钉钉用户 ID(userId / 员工 ID)。可在钉钉管理后台 → 通讯录 → 成员详情中查看,或在单聊中给机器人发送 /whoami 获取。","channel.userIdHint.discord": "在 Discord 设置 → 高级中开启开发者模式,然后右键你的头像 → 复制用户 ID。","channel.userIdHint.feishu": "飞书 Open ID 按应用区分,后台没有任何页面能查到你自己的。填好凭据后会自动读取应用所有者的 ID;若没有填上,可点下方按钮重试,或在私聊里给机器人发送 /whoami。","channel.userIdHint.imessage": "使用 BlueBubbles 中显示的 iMessage handle,通常是邮箱或 E.164 手机号。",diff --git a/package.json b/package.jsonindex 65009402668..f28609b8a27 100644--- a/package.json+++ b/package.json@@ -289,6 +289,7 @@"@lobechat/business-model-bank": "workspace:*","@lobechat/business-model-runtime": "workspace:*","@lobechat/canvas": "workspace:*",+ "@lobechat/chat-adapter-dingtalk": "workspace:*","@lobechat/chat-adapter-feishu": "workspace:*","@lobechat/chat-adapter-imessage": "workspace:*","@lobechat/chat-adapter-line": "workspace:*",diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.tsindex 7bcde274905..ee523e0d329 100644--- a/packages/builtin-tool-message/src/manifest.ts+++ b/packages/builtin-tool-message/src/manifest.ts@@ -4,7 +4,7 @@ import type { BuiltinToolManifest } from '@lobechat/types';import { systemPrompt } from './systemRole';import { MessageApiName, MessageToolIdentifier, MESSENGER_PUSH_CONTENT_MAX_LENGTH } from './types';-const platformEnum = ['discord', 'telegram', 'slack', 'feishu', 'lark', 'qq', 'wechat'];+const platformEnum = ['discord', 'telegram', 'slack', 'feishu', 'lark', 'qq', 'wechat', 'dingtalk'];/*** Shared schema fragment for the outbound `attachments` array on message-diff --git a/packages/builtin-tool-message/src/systemRole.ts b/packages/builtin-tool-message/src/systemRole.tsindex f0dde785bd4..5540c5f5e20 100644--- a/packages/builtin-tool-message/src/systemRole.ts+++ b/packages/builtin-tool-message/src/systemRole.ts@@ -10,6 +10,7 @@ export const systemPrompt = `You have access to a Message tool that provides uni- **lark** — Lark (international Feishu) chats, groups, message replies, reactions- **qq** — QQ groups, guild channels, direct messages- **wechat** — WeChat (微信) iLink Bot conversations+- **dingtalk** — DingTalk (钉钉) robot single chats and groups (send only; channelId \`group:<openConversationId>\` or \`single:<staffId>\`)</supported_platforms><bot_management>diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.tsindex 41ca94e5d4e..e53fa47161c 100644--- a/packages/builtin-tool-message/src/types.ts+++ b/packages/builtin-tool-message/src/types.ts@@ -5,6 +5,7 @@ export const MessageToolIdentifier = 'lobe-message';// ==================== Supported Platforms ====================export const MessagePlatform = {+ dingtalk: 'dingtalk',discord: 'discord',feishu: 'feishu',imessage: 'imessage',diff --git a/packages/chat-adapter-dingtalk/package.json b/packages/chat-adapter-dingtalk/package.jsonnew file mode 100644index 00000000000..cb3bca0d392--- /dev/null+++ b/packages/chat-adapter-dingtalk/package.json@@ -0,0 +1,29 @@+{+ "name": "@lobechat/chat-adapter-dingtalk",+ "version": "0.1.0",+ "description": "DingTalk (钉钉) bot adapter for chat SDK",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "tsup",+ "clean": "rm -rf dist",+ "dev": "tsup --watch",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "chat": "~4.38.0",+ "mime": "^4.1.0",+ "ws": "^8.21.0"+ },+ "devDependencies": {+ "@types/node": "^24.13.2",+ "@types/ws": "^8.18.1",+ "tsup": "^8.5.1",+ "typescript": "^6.0.3"+ }+}diff --git a/packages/chat-adapter-dingtalk/src/adapter.test.ts b/packages/chat-adapter-dingtalk/src/adapter.test.tsnew file mode 100644index 00000000000..f8064e1000c--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/adapter.test.ts@@ -0,0 +1,467 @@+import type { AddressInfo } from 'node:net';++import { RateLimitError } from 'chat';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { type WebSocket as ServerSocket, WebSocketServer } from 'ws';++import { createDingTalkAdapter, DingTalkAdapter } from './adapter';+import { DingTalkApiError } from './api';+import { signCallback } from './crypto';+import type { DingTalkRawMessage } from './types';++// ---- fixtures (shapes from the robot receive-message callback) ----++const SECRET = 'test_secret';+const BOT_ID = '$:LWCP_v1:$bot';++function singleText(overrides: Partial<DingTalkRawMessage> = {}): DingTalkRawMessage {+ return {+ chatbotCorpId: 'ding_corp',+ chatbotUserId: BOT_ID,+ conversationId: 'cid_single==',+ conversationType: '1',+ createAt: 1_793_000_000_000,+ isAdmin: false,+ msgId: 'msg_single_1',+ msgtype: 'text',+ robotCode: 'ding_client',+ senderCorpId: 'ding_corp',+ senderId: '$:LWCP_v1:$user',+ senderNick: '张三',+ senderStaffId: 'staff_1',+ sessionWebhook: 'https://oapi.dingtalk.com/robot/sendBySession?session=s1',+ sessionWebhookExpiredTime: Date.now() + 90 * 60 * 1000,+ text: { content: ' 你好 ' },+ ...overrides,+ };+}++function groupAt(overrides: Partial<DingTalkRawMessage> = {}): DingTalkRawMessage {+ return singleText({+ atUsers: [{ dingtalkId: BOT_ID }],+ conversationId: 'cidGroupABC+/=',+ conversationTitle: '研发群',+ conversationType: '2',+ isInAtList: true,+ msgId: 'msg_group_1',+ sessionWebhook: 'https://oapi.dingtalk.com/robot/sendBySession?session=g1',+ text: { content: ' 帮我总结一下' },+ ...overrides,+ });+}++function signedRequest(body: unknown, secret = SECRET, timestamp = String(Date.now())): Request {+ return new Request('http://localhost/api/agent/webhooks/dingtalk/app', {+ body: typeof body === 'string' ? body : JSON.stringify(body),+ headers: {+ 'Content-Type': 'application/json',+ 'sign': signCallback(timestamp, secret),+ 'timestamp': timestamp,+ },+ method: 'POST',+ });+}++describe('DingTalkAdapter', () => {+ let adapter: DingTalkAdapter;+ let api: any;++ const mockChat = {+ getLogger: vi.fn(() => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() })),+ getUserName: vi.fn(() => 'TestBot'),+ processMessage: vi.fn(),+ };++ beforeEach(async () => {+ vi.clearAllMocks();+ adapter = new DingTalkAdapter({ clientId: 'ding_client', clientSecret: SECRET });+ api = adapter.apiClient;+ vi.spyOn(api, 'getAccessToken').mockResolvedValue('tok');+ await adapter.initialize(mockChat as any);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ async function receive(raw: DingTalkRawMessage) {+ const res = await adapter.handleWebhook(signedRequest(raw));+ expect(res.status).toBe(200);+ const call = mockChat.processMessage.mock.calls.at(-1);+ return { message: call ? await call[2]() : undefined, res, threadId: call?.[1] };+ }++ describe('basics', () => {+ it('defaults userName and robotCode', () => {+ const a = createDingTalkAdapter({ clientId: 'cid', clientSecret: 's' });+ expect(a.userName).toBe('dingtalk-bot');+ expect(a.apiClient.robotCode).toBe('cid');+ expect(+ new DingTalkAdapter({ clientId: 'c', clientSecret: 's', robotCode: 'r' }).apiClient+ .robotCode,+ ).toBe('r');+ });++ it('validates credentials on initialize', () => {+ expect(api.getAccessToken).toHaveBeenCalled();+ expect(adapter.userName).toBe('TestBot');+ });++ it('round-trips thread ids, keeping ":" inside the id', () => {+ expect(adapter.encodeThreadId({ id: 'staff_1', type: 'single' })).toBe(+ 'dingtalk:single:staff_1',+ );+ expect(adapter.decodeThreadId('dingtalk:group:cid:with:colon')).toEqual({+ id: 'cid:with:colon',+ type: 'group',+ });+ expect(adapter.isDM('dingtalk:single:staff_1')).toBe(true);+ expect(adapter.isDM('dingtalk:group:cid')).toBe(false);+ });+ });++ describe('inbound: webhook authentication', () => {+ it('rejects an unsigned request', async () => {+ const req = new Request('http://localhost/x', {+ body: JSON.stringify(singleText()),+ method: 'POST',+ });+ const res = await adapter.handleWebhook(req);+ expect(res.status).toBe(401);+ expect(mockChat.processMessage).not.toHaveBeenCalled();+ });++ it('rejects a request signed with another secret', async () => {+ const res = await adapter.handleWebhook(signedRequest(singleText(), 'other'));+ expect(res.status).toBe(401);+ });++ it('rejects a stale timestamp (> 1 hour)', async () => {+ const old = String(Date.now() - 2 * 60 * 60 * 1000);+ const res = await adapter.handleWebhook(signedRequest(singleText(), SECRET, old));+ expect(res.status).toBe(401);+ });++ it('returns 400 for invalid JSON with a valid signature', async () => {+ const res = await adapter.handleWebhook(signedRequest('{oops'));+ expect(res.status).toBe(400);+ });+ });++ describe('inbound: message parsing', () => {+ it('parses a single-chat text message', async () => {+ const { message, threadId } = await receive(singleText());++ expect(threadId).toBe('dingtalk:single:staff_1');+ expect(message.text).toBe('你好');+ expect(message.isMention).toBe(false);+ expect(message.author).toMatchObject({+ fullName: '张三',+ isBot: false,+ isMe: false,+ userId: 'staff_1',+ });+ expect(message.id).toBe('msg_single_1');+ expect(message.metadata.dateSent.getTime()).toBe(1_793_000_000_000);+ });++ it('parses a group @robot message as a mention on the conversation thread', async () => {+ const { message, threadId } = await receive(groupAt());++ expect(threadId).toBe('dingtalk:group:cidGroupABC+/=');+ expect(message.text).toBe('帮我总结一下');+ expect(message.isMention).toBe(true);+ expect(adapter.botUserId).toBe(BOT_ID);+ });++ it('falls back to senderId when the sender has no staffId (external user)', async () => {+ const { threadId, message } = await receive(singleText({ senderStaffId: undefined }));+ expect(threadId).toBe('dingtalk:single:$:LWCP_v1:$user');+ expect(message.author.userId).toBe('$:LWCP_v1:$user');+ });++ it('maps richText to text plus image attachments', async () => {+ const { message } = await receive(+ singleText({+ content: {+ richText: [+ { text: '看这张图 ' },+ { downloadCode: 'dc_img', type: 'picture' },+ { text: '是什么?' },+ ],+ },+ msgtype: 'richText',+ text: undefined,+ }),+ );++ expect(message.text).toBe('看这张图 是什么?');+ expect(message.attachments).toHaveLength(1);+ expect(message.attachments[0]).toMatchObject({+ fetchMetadata: { downloadCode: 'dc_img' },+ type: 'image',+ });+ });++ it('maps a picture message to an image attachment that downloads via downloadCode', async () => {+ const download = vi.spyOn(api, 'downloadFile').mockResolvedValue(Buffer.from('img'));+ const { message } = await receive(+ singleText({ content: { downloadCode: 'dc_pic' }, msgtype: 'picture', text: undefined }),+ );++ expect(message.text).toBe('');+ expect(message.attachments[0].type).toBe('image');+ await expect(message.attachments[0].fetchData!()).resolves.toEqual(Buffer.from('img'));+ expect(download).toHaveBeenCalledWith('dc_pic');+ });++ it('uses the speech recognition text for audio messages', async () => {+ const { message } = await receive(+ singleText({+ content: { downloadCode: 'dc_a', duration: 3, recognition: '明天开会' },+ msgtype: 'audio',+ text: undefined,+ }),+ );+ expect(message.text).toBe('明天开会');+ expect(message.attachments[0].type).toBe('audio');+ });++ it('maps file messages with a MIME type from the file name', async () => {+ const { message } = await receive(+ singleText({+ content: { downloadCode: 'dc_f', fileName: 'report.pdf' },+ msgtype: 'file',+ text: undefined,+ }),+ );+ expect(message.attachments[0]).toMatchObject({+ mimeType: 'application/pdf',+ name: 'report.pdf',+ type: 'file',+ });+ });++ it('maps video messages to a video attachment', async () => {+ const { message } = await receive(+ singleText({ content: { downloadCode: 'dc_v' }, msgtype: 'video', text: undefined }),+ );+ expect(message.attachments[0].type).toBe('video');+ });++ it('drops empty messages and unknown types without text', async () => {+ await adapter.handleWebhook(signedRequest(singleText({ text: { content: ' ' } })));+ await adapter.handleWebhook(+ signedRequest(singleText({ msgtype: 'interactiveCard', text: undefined })),+ );+ expect(mockChat.processMessage).not.toHaveBeenCalled();+ });++ it('ignores messages sent by the robot itself and payloads without ids', async () => {+ await adapter.handleWebhook(signedRequest(singleText({ senderId: BOT_ID })));+ await adapter.handleWebhook(signedRequest({ hello: 'world' }));+ expect(mockChat.processMessage).not.toHaveBeenCalled();+ });+ });++ describe('outbound', () => {+ it('replies through the sessionWebhook while it is valid', async () => {+ const reply = vi.spyOn(api, 'replyViaSessionWebhook').mockResolvedValue(undefined);+ const batch = vi.spyOn(api, 'sendSingleMessage');+ await receive(singleText());++ const sent = await adapter.postMessage('dingtalk:single:staff_1', 'hello');++ expect(reply).toHaveBeenCalledWith(+ 'https://oapi.dingtalk.com/robot/sendBySession?session=s1',+ { msgKey: 'sampleText', msgParam: { content: 'hello' } },+ );+ expect(batch).not.toHaveBeenCalled();+ expect(sent.threadId).toBe('dingtalk:single:staff_1');+ });++ it('sends single chat via batchSend when there is no sessionWebhook', async () => {+ const batch = vi+ .spyOn(api, 'sendSingleMessage')+ .mockResolvedValue({ processQueryKey: 'pqk_1' });++ const sent = await adapter.postMessage('dingtalk:single:staff_9', {+ markdown: '**结论**:可以',+ });++ expect(batch).toHaveBeenCalledWith(['staff_9'], {+ msgKey: 'sampleMarkdown',+ msgParam: { text: '**结论**:可以', title: '结论:可以' },+ });+ expect(sent.id).toBe('pqk_1');+ expect(sent.raw.conversationType).toBe('1');+ });++ it('sends group chat via groupMessages/send with the openConversationId', async () => {+ const group = vi+ .spyOn(api, 'sendGroupMessage')+ .mockResolvedValue({ processQueryKey: 'pqk_g' });++ const sent = await adapter.postMessage('dingtalk:group:cidGroupABC+/=', 'done');++ expect(group).toHaveBeenCalledWith('cidGroupABC+/=', {+ msgKey: 'sampleText',+ msgParam: { content: 'done' },+ });+ expect(sent.id).toBe('pqk_g');+ expect(sent.raw.conversationType).toBe('2');+ });++ it('falls back to the OpenAPI when the sessionWebhook is rejected, then stops using it', async () => {+ const reply = vi.spyOn(api, 'replyViaSessionWebhook').mockRejectedValue(+ new DingTalkApiError({+ code: '300001',+ kind: 'session_webhook',+ message: 'expired',+ status: 200,+ }),+ );+ const group = vi.spyOn(api, 'sendGroupMessage').mockResolvedValue({ processQueryKey: 'pqk' });+ await receive(groupAt());++ await adapter.postMessage('dingtalk:group:cidGroupABC+/=', 'first');+ await adapter.postMessage('dingtalk:group:cidGroupABC+/=', 'second');++ expect(reply).toHaveBeenCalledTimes(1);+ expect(group).toHaveBeenCalledTimes(2);+ });++ it('skips a sessionWebhook that has passed sessionWebhookExpiredTime', async () => {+ const reply = vi.spyOn(api, 'replyViaSessionWebhook');+ const batch = vi+ .spyOn(api, 'sendSingleMessage')+ .mockResolvedValue({ processQueryKey: 'pqk' });+ await receive(singleText({ sessionWebhookExpiredTime: Date.now() + 1000 }));++ await adapter.postMessage('dingtalk:single:staff_1', 'late reply');++ expect(reply).not.toHaveBeenCalled();+ expect(batch).toHaveBeenCalledWith(['staff_1'], expect.anything());+ });++ it('maps a DingTalk rate limit to the chat SDK RateLimitError', async () => {+ vi.spyOn(api, 'sendGroupMessage').mockRejectedValue(+ new DingTalkApiError({+ code: 'send.too.fast',+ kind: 'rate_limit',+ message: 'slow down',+ status: 400,+ }),+ );++ const error = await adapter.postMessage('dingtalk:group:cid', 'x').catch((e) => e);+ expect(error).toBeInstanceOf(RateLimitError);+ expect(error.cause).toBeInstanceOf(DingTalkApiError);+ });++ it('surfaces other API errors unchanged', async () => {+ const original = new DingTalkApiError({+ code: 'invalidParameter.robotCode.notExsit',+ kind: 'invalid_request',+ message: 'bad robot',+ status: 400,+ });+ vi.spyOn(api, 'sendGroupMessage').mockRejectedValue(original);++ await expect(adapter.postMessage('dingtalk:group:cid', 'x')).rejects.toBe(original);+ });++ it('edits by posting a new message', async () => {+ const group = vi.spyOn(api, 'sendGroupMessage').mockResolvedValue({ processQueryKey: 'p2' });+ const sent = await adapter.editMessage('dingtalk:group:cid', 'p1', 'updated');+ expect(group).toHaveBeenCalled();+ expect(sent.id).toBe('p2');+ });++ it('sends images by URL', async () => {+ const group = vi.spyOn(api, 'sendGroupMessage').mockResolvedValue({ processQueryKey: 'p' });+ await adapter.postImage('dingtalk:group:cid', 'https://example.com/a.png');+ expect(group).toHaveBeenCalledWith('cid', {+ msgKey: 'sampleImageMsg',+ msgParam: { photoURL: 'https://example.com/a.png' },+ });+ });+ });++ describe('end-to-end over fetch: expired token is refreshed during a send', () => {+ it('retries the group send with a fresh token', async () => {+ vi.mocked(api.getAccessToken).mockRestore();+ const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status });+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(json({ accessToken: 'old', expireIn: 7200 }))+ .mockResolvedValueOnce(json({ code: 'InvalidAuthentication' }, 401))+ .mockResolvedValueOnce(json({ accessToken: 'new', expireIn: 7200 }))+ .mockResolvedValueOnce(json({ processQueryKey: 'pqk_ok' }));+ vi.stubGlobal('fetch', fetchMock);+ api.invalidateAccessToken();++ const sent = await adapter.postMessage('dingtalk:group:cid', 'hi');++ expect(sent.id).toBe('pqk_ok');+ expect(fetchMock.mock.calls[3][1].headers['x-acs-dingtalk-access-token']).toBe('new');+ });+ });++ describe('gateway listener', () => {+ it('forwards callbacks that handleWebhook accepts (shared signature scheme)', async () => {+ // A real local stream endpoint, so the `ws` client is exercised end to end.+ const server = new WebSocketServer({ port: 0 });+ await new Promise<void>((resolve) => server.once('listening', () => resolve()));+ const peer = new Promise<ServerSocket>((resolve) => server.once('connection', resolve));+ const { port } = server.address() as AddressInfo;+ vi.spyOn(api, 'openStreamConnection').mockResolvedValue({+ endpoint: `ws://127.0.0.1:${port}/connect`,+ ticket: 'tk',+ });++ let forwarded: Request | undefined;+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (url: string, init: RequestInit) => {+ forwarded = new Request(url, init);+ return new Response('ok');+ }),+ );++ const controller = new AbortController();+ await adapter.startGatewayListener(+ { waitUntil: vi.fn() },+ 60_000,+ controller.signal,+ 'http://localhost/hook',+ );++ const socket = await peer;+ const ack = new Promise<any>((resolve) =>+ socket.once('message', (raw) => resolve(JSON.parse(raw.toString()))),+ );+ socket.send(+ JSON.stringify({+ data: JSON.stringify(groupAt()),+ headers: { messageId: 'm', topic: '/v1.0/im/bot/messages/get' },+ type: 'CALLBACK',+ }),+ );+ expect(await ack).toMatchObject({ code: 200, headers: { messageId: 'm' } });+ await vi.waitFor(() => expect(forwarded).toBeDefined());++ const res = await adapter.handleWebhook(forwarded!);+ expect(res.status).toBe(200);+ expect(mockChat.processMessage).toHaveBeenCalledWith(+ adapter,+ 'dingtalk:group:cidGroupABC+/=',+ expect.any(Function),+ undefined,+ );+ controller.abort();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ });+ });+});diff --git a/packages/chat-adapter-dingtalk/src/adapter.ts b/packages/chat-adapter-dingtalk/src/adapter.tsnew file mode 100644index 00000000000..eed15f70c91--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/adapter.ts@@ -0,0 +1,451 @@+import type {+ Adapter,+ AdapterPostableMessage,+ Attachment,+ ChatInstance,+ EmojiValue,+ FetchOptions,+ FetchResult,+ FormattedContent,+ Logger,+ RawMessage,+ ThreadInfo,+ WebhookOptions,+} from 'chat';+import { Message, RateLimitError } from 'chat';+import mime from 'mime';++import { DingTalkApiClient, DingTalkApiError, MAX_MSG_PARAM_TEXT_BYTES, truncateUtf8 } from './api';+import { verifyCallbackSignature } from './crypto';+import { DingTalkFormatConverter } from './format-converter';+import { DingTalkStreamConnection } from './gateway';+import type {+ DingTalkAdapterConfig,+ DingTalkOutboundMessage,+ DingTalkRawMessage,+ DingTalkThreadId,+} from './types';+import { DINGTALK_CONVERSATION_TYPE } from './types';++/** Treat a sessionWebhook as expired this long before its stated expiry. */+const SESSION_WEBHOOK_EXPIRY_MARGIN_MS = 30_000;+const MAX_CACHED_SESSION_WEBHOOKS = 1000;++interface SessionWebhookEntry {+ expiresAt: number;+ url: string;+}++export class DingTalkAdapter implements Adapter<DingTalkThreadId, DingTalkRawMessage> {+ readonly name = 'dingtalk';+ private readonly api: DingTalkApiClient;+ private readonly clientSecret: string;+ private readonly formatConverter: DingTalkFormatConverter;+ /** Latest reply webhook per thread, learned from inbound callbacks. */+ private readonly sessionWebhooks = new Map<string, SessionWebhookEntry>();+ private _userName: string;+ private _botUserId?: string;+ private chat!: ChatInstance;+ private logger!: Logger;++ get userName(): string {+ return this._userName;+ }++ get botUserId(): string | undefined {+ return this._botUserId;+ }++ constructor(config: DingTalkAdapterConfig & { userName?: string }) {+ this.api = new DingTalkApiClient(config.clientId, config.clientSecret, config.robotCode);+ this.clientSecret = config.clientSecret;+ this.formatConverter = new DingTalkFormatConverter();+ this._userName = config.userName || 'dingtalk-bot';+ }++ get apiClient(): DingTalkApiClient {+ return this.api;+ }++ async initialize(chat: ChatInstance): Promise<void> {+ this.chat = chat;+ this.logger = chat.getLogger(this.name);+ this._userName = chat.getUserName();++ // Validate credentials+ await this.api.getAccessToken();++ this.logger.info('Initialized DingTalk adapter (robotCode=%s)', this.api.robotCode);+ }++ // ------------------------------------------------------------------+ // Webhook handling+ // ------------------------------------------------------------------++ /**+ * Handle a robot message callback: either forwarded by the Stream gateway or+ * delivered by DingTalk's HTTP callback mode. Both carry `timestamp` + `sign`+ * headers signed with the Client Secret.+ */+ async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {+ const bodyText = await request.text();++ if (+ !verifyCallbackSignature(+ request.headers.get('timestamp'),+ request.headers.get('sign'),+ this.clientSecret,+ )+ ) {+ return new Response('Invalid signature', { status: 401 });+ }++ let payload: DingTalkRawMessage;+ try {+ payload = JSON.parse(bodyText);+ } catch {+ return new Response('Invalid JSON', { status: 400 });+ }++ if (!payload?.msgId || !payload.conversationId || !payload.senderId) {+ return Response.json({ ok: true });+ }++ if (payload.chatbotUserId) this._botUserId = payload.chatbotUserId;+ if (payload.chatbotUserId && payload.senderId === payload.chatbotUserId) {+ return Response.json({ ok: true });+ }++ const threadId = this.threadIdFromRaw(payload);+ this.rememberSessionWebhook(threadId, payload);++ const message = this.parseMessage(payload);+ if (!message.text.trim() && message.attachments.length === 0) {+ return Response.json({ ok: true });+ }++ this.chat.processMessage(this, threadId, () => Promise.resolve(message), options);++ return Response.json({ ok: true });+ }++ // ------------------------------------------------------------------+ // Gateway listener (Stream mode)+ // ------------------------------------------------------------------++ /**+ * Start a Stream mode connection. Robot message callbacks are ACKed on the+ * socket and forwarded to `webhookUrl` as signed HTTP POSTs, reusing the+ * `handleWebhook()` pipeline.+ */+ async startGatewayListener(+ options: { waitUntil: (task: Promise<any>) => void },+ durationMs: number,+ abortSignal: AbortSignal,+ webhookUrl: string,+ ): Promise<void> {+ const gateway = new DingTalkStreamConnection(this.api, {+ abortSignal,+ clientSecret: this.clientSecret,+ durationMs,+ log: (msg: string, ...rest: any[]) => this.logger.info(msg, ...rest),+ webhookUrl,+ });++ const gatewayTask = gateway.connect();+ options.waitUntil(gatewayTask);+ await gatewayTask;+ }++ // ------------------------------------------------------------------+ // Message operations+ // ------------------------------------------------------------------++ async postMessage(+ threadId: string,+ message: AdapterPostableMessage,+ ): Promise<RawMessage<DingTalkRawMessage>> {+ const text = truncateUtf8(+ this.formatConverter.renderPostable(message).trim(),+ MAX_MSG_PARAM_TEXT_BYTES,+ );+ const outbound = this.formatConverter.toOutboundMessage(message, text);+ const id = await this.send(threadId, outbound);++ return {+ id,+ raw: {+ conversationId: this.decodeThreadId(threadId).id,+ conversationType: this.isDM(threadId)+ ? DINGTALK_CONVERSATION_TYPE.SINGLE+ : DINGTALK_CONVERSATION_TYPE.GROUP,+ createAt: Date.now(),+ msgId: id,+ msgtype: outbound.msgKey === 'sampleText' ? 'text' : 'markdown',+ senderId: this._botUserId || '',+ text: { content: text },+ },+ threadId,+ };+ }++ /** Send an image by public URL or media ID. */+ async postImage(threadId: string, photoURL: string): Promise<string> {+ return this.send(threadId, { msgKey: 'sampleImageMsg', msgParam: { photoURL } });+ }++ /**+ * Deliver through the thread's sessionWebhook while it is valid (saves the+ * organisation's API quota), falling back to the robot OpenAPI when it is+ * missing, expired or rejected.+ */+ private async send(threadId: string, outbound: DingTalkOutboundMessage): Promise<string> {+ const session = this.getSessionWebhook(threadId);+ if (session) {+ try {+ await this.api.replyViaSessionWebhook(session.url, outbound);+ return `session:${Date.now()}`;+ } catch (err) {+ this.sessionWebhooks.delete(threadId);+ this.logger?.warn('sessionWebhook failed, falling back to OpenAPI: %s', String(err));+ }+ }++ const { type, id } = this.decodeThreadId(threadId);+ try {+ const result =+ type === 'group'+ ? await this.api.sendGroupMessage(id, outbound)+ : await this.api.sendSingleMessage([id], outbound);+ return result.processQueryKey;+ } catch (err) {+ if (err instanceof DingTalkApiError && err.kind === 'rate_limit') {+ throw new RateLimitError(err.message, undefined, err);+ }+ throw err;+ }+ }++ async editMessage(+ threadId: string,+ _messageId: string,+ message: AdapterPostableMessage,+ ): Promise<RawMessage<DingTalkRawMessage>> {+ // Robot text/markdown messages cannot be edited — post a new message+ return this.postMessage(threadId, message);+ }++ async deleteMessage(_threadId: string, _messageId: string): Promise<void> {+ this.logger.warn('Message deletion not implemented for DingTalk');+ }++ async fetchMessages(+ _threadId: string,+ _options?: FetchOptions,+ ): Promise<FetchResult<DingTalkRawMessage>> {+ // Robots have no message history API+ return { messages: [], nextCursor: undefined };+ }++ async fetchThread(threadId: string): Promise<ThreadInfo> {+ const { type, id } = this.decodeThreadId(threadId);+ return {+ channelId: threadId,+ id: threadId,+ isDM: type === 'single',+ metadata: { id, type },+ };+ }++ // ------------------------------------------------------------------+ // Message parsing+ // ------------------------------------------------------------------++ parseMessage(raw: DingTalkRawMessage): Message<DingTalkRawMessage> {+ const threadId = this.threadIdFromRaw(raw);+ const { text, attachments } = this.extractContent(raw);+ const cleanText = this.formatConverter.cleanText(text);+ const isGroup = raw.conversationType === DINGTALK_CONVERSATION_TYPE.GROUP;+ const userId = raw.senderStaffId || raw.senderId;+ const isMe = !!raw.chatbotUserId && raw.senderId === raw.chatbotUserId;++ return new Message({+ attachments,+ author: {+ fullName: raw.senderNick || userId,+ isBot: isMe,+ isMe,+ userId,+ userName: raw.senderNick || userId,+ },+ formatted: this.formatConverter.toAst(cleanText),+ id: raw.msgId,+ // Group callbacks are only delivered when the robot is @-mentioned.+ isMention: isGroup || !!raw.isInAtList,+ metadata: {+ dateSent: new Date(raw.createAt || Date.now()),+ edited: false,+ },+ raw,+ text: cleanText,+ threadId,+ });+ }++ private extractContent(raw: DingTalkRawMessage): { attachments: Attachment[]; text: string } {+ const content = raw.content;+ switch (raw.msgtype) {+ case 'text': {+ return { attachments: [], text: raw.text?.content ?? '' };+ }+ case 'richText': {+ const attachments: Attachment[] = [];+ const parts: string[] = [];+ for (const item of content?.richText ?? []) {+ if (item.text) parts.push(item.text);+ const code = item.downloadCode || item.pictureDownloadCode;+ if (code) attachments.push(this.buildAttachment('image', code));+ }+ return { attachments, text: parts.join('') };+ }+ case 'picture': {+ const code = content?.downloadCode || content?.pictureDownloadCode;+ return { attachments: code ? [this.buildAttachment('image', code)] : [], text: '' };+ }+ case 'audio': {+ const code = content?.downloadCode;+ return {+ attachments: code ? [this.buildAttachment('audio', code)] : [],+ // DingTalk ships a speech-to-text transcript with voice messages.+ text: content?.recognition ?? '',+ };+ }+ case 'video': {+ const code = content?.downloadCode;+ return { attachments: code ? [this.buildAttachment('video', code)] : [], text: '' };+ }+ case 'file': {+ const code = content?.downloadCode;+ return {+ attachments: code ? [this.buildAttachment('file', code, content?.fileName)] : [],+ text: '',+ };+ }+ default: {+ return { attachments: [], text: raw.text?.content ?? '' };+ }+ }+ }++ /**+ * DingTalk ships a `downloadCode`, not a URL; `fetchData` exchanges it via+ * `robot/messageFiles/download`. `fetchMetadata` keeps the code so the+ * fetcher can be rebuilt after queue serialization.+ */+ private buildAttachment(+ type: Attachment['type'],+ downloadCode: string,+ fileName?: string,+ ): Attachment {+ return {+ fetchData: () => this.api.downloadFile(downloadCode),+ fetchMetadata: { downloadCode },+ mimeType: (fileName && mime.getType(fileName)) || undefined,+ name: fileName,+ type,+ };+ }++ // ------------------------------------------------------------------+ // sessionWebhook cache+ // ------------------------------------------------------------------++ private rememberSessionWebhook(threadId: string, raw: DingTalkRawMessage): void {+ if (!raw.sessionWebhook || !raw.sessionWebhookExpiredTime) return;+ this.sessionWebhooks.delete(threadId);+ this.sessionWebhooks.set(threadId, {+ expiresAt: raw.sessionWebhookExpiredTime,+ url: raw.sessionWebhook,+ });+ if (this.sessionWebhooks.size > MAX_CACHED_SESSION_WEBHOOKS) {+ const oldest = this.sessionWebhooks.keys().next().value;+ if (oldest !== undefined) this.sessionWebhooks.delete(oldest);+ }+ }++ private getSessionWebhook(threadId: string): SessionWebhookEntry | undefined {+ const entry = this.sessionWebhooks.get(threadId);+ if (!entry) return undefined;+ if (Date.now() >= entry.expiresAt - SESSION_WEBHOOK_EXPIRY_MARGIN_MS) {+ this.sessionWebhooks.delete(threadId);+ return undefined;+ }+ return entry;+ }++ // ------------------------------------------------------------------+ // Reactions / typing (not supported for robots)+ // ------------------------------------------------------------------++ async addReaction(+ _threadId: string,+ _messageId: string,+ _emoji: EmojiValue | string,+ ): Promise<void> {}++ async removeReaction(+ _threadId: string,+ _messageId: string,+ _emoji: EmojiValue | string,+ ): Promise<void> {}++ async startTyping(_threadId: string): Promise<void> {}++ // ------------------------------------------------------------------+ // Thread ID encoding+ // ------------------------------------------------------------------++ private threadIdFromRaw(raw: DingTalkRawMessage): string {+ if (raw.conversationType === DINGTALK_CONVERSATION_TYPE.GROUP) {+ return this.encodeThreadId({ id: raw.conversationId, type: 'group' });+ }+ return this.encodeThreadId({ id: raw.senderStaffId || raw.senderId, type: 'single' });+ }++ encodeThreadId(data: DingTalkThreadId): string {+ return `dingtalk:${data.type}:${data.id}`;+ }++ decodeThreadId(threadId: string): DingTalkThreadId {+ const [prefix, type, ...rest] = threadId.split(':');+ if (prefix !== 'dingtalk' || (type !== 'single' && type !== 'group') || rest.length === 0) {+ return { id: threadId, type: 'group' };+ }+ return { id: rest.join(':'), type };+ }++ channelIdFromThreadId(threadId: string): string {+ return threadId;+ }++ isDM(threadId: string): boolean {+ return this.decodeThreadId(threadId).type === 'single';+ }++ // ------------------------------------------------------------------+ // Format rendering+ // ------------------------------------------------------------------++ renderFormatted(content: FormattedContent): string {+ return this.formatConverter.fromAst(content);+ }+}++/**+ * Factory function to create a DingTalkAdapter.+ */+export function createDingTalkAdapter(+ config: DingTalkAdapterConfig & { userName?: string },+): DingTalkAdapter {+ return new DingTalkAdapter(config);+}diff --git a/packages/chat-adapter-dingtalk/src/api.test.ts b/packages/chat-adapter-dingtalk/src/api.test.tsnew file mode 100644index 00000000000..22a53719b59--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/api.test.ts@@ -0,0 +1,310 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ classifyDingTalkError,+ DINGTALK_API_BASE_URL,+ DingTalkApiClient,+ DingTalkApiError,+ truncateUtf8,+} from './api';++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ headers: { 'content-type': 'application/json' },+ status,+ });++const tokenResponse = (token: string, expireIn = 7200) => json({ accessToken: token, expireIn });++describe('DingTalkApiClient', () => {+ let fetchMock: ReturnType<typeof vi.fn>;+ let client: DingTalkApiClient;++ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ vi.useFakeTimers({ shouldAdvanceTime: true });+ client = new DingTalkApiClient('ding_client', 'ding_secret');+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ const body = (call: number) => JSON.parse(fetchMock.mock.calls[call][1].body);+ const url = (call: number) => fetchMock.mock.calls[call][0];++ describe('access token', () => {+ it('exchanges Client ID / Secret at /v1.0/oauth2/accessToken', async () => {+ fetchMock.mockResolvedValueOnce(tokenResponse('tok_1'));++ await expect(client.getAccessToken()).resolves.toBe('tok_1');+ expect(url(0)).toBe(`${DINGTALK_API_BASE_URL}/v1.0/oauth2/accessToken`);+ expect(body(0)).toEqual({ appKey: 'ding_client', appSecret: 'ding_secret' });+ });++ it('caches the token and shares one in-flight request', async () => {+ fetchMock.mockResolvedValueOnce(tokenResponse('tok_1'));++ const [a, b] = await Promise.all([client.getAccessToken(), client.getAccessToken()]);+ await client.getAccessToken();++ expect(a).toBe('tok_1');+ expect(b).toBe('tok_1');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('refreshes 5 minutes before expireIn', async () => {+ fetchMock+ .mockResolvedValueOnce(tokenResponse('tok_1', 7200))+ .mockResolvedValueOnce(tokenResponse('tok_2', 7200));++ await client.getAccessToken();+ vi.advanceTimersByTime((7200 - 300) * 1000 - 1000);+ await expect(client.getAccessToken()).resolves.toBe('tok_1');++ vi.advanceTimersByTime(2000);+ await expect(client.getAccessToken()).resolves.toBe('tok_2');+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('maps any 4xx from the token endpoint to an auth error', async () => {+ fetchMock.mockResolvedValueOnce(+ json({ code: 'invalidClientIdOrSecret', message: '无效的clientId或者clientSecret' }, 400),+ );++ const error = await client.getAccessToken().catch((e) => e);+ expect(error).toBeInstanceOf(DingTalkApiError);+ expect(error).toMatchObject({ code: 'invalidClientIdOrSecret', kind: 'auth', status: 400 });+ });++ it('re-fetches the token and retries once when the API reports it expired', async () => {+ fetchMock+ .mockResolvedValueOnce(tokenResponse('stale'))+ .mockResolvedValueOnce(+ json({ code: 'InvalidAuthentication', message: '不合法的access_token' }, 401),+ )+ .mockResolvedValueOnce(tokenResponse('fresh'))+ .mockResolvedValueOnce(json({ processQueryKey: 'pqk_1' }));++ const result = await client.sendGroupMessage('cid_1', {+ msgKey: 'sampleText',+ msgParam: { content: 'hi' },+ });++ expect(result.processQueryKey).toBe('pqk_1');+ expect(fetchMock.mock.calls[1][1].headers['x-acs-dingtalk-access-token']).toBe('stale');+ expect(fetchMock.mock.calls[3][1].headers['x-acs-dingtalk-access-token']).toBe('fresh');+ });++ it('gives up after one retry when the fresh token is rejected too', async () => {+ const unauthorized = () => json({ code: 'InvalidAuthentication' }, 401);+ fetchMock+ .mockResolvedValueOnce(tokenResponse('a'))+ .mockResolvedValueOnce(unauthorized())+ .mockResolvedValueOnce(tokenResponse('b'))+ .mockResolvedValueOnce(unauthorized());++ await expect(+ client.sendGroupMessage('cid', { msgKey: 'sampleText', msgParam: { content: 'x' } }),+ ).rejects.toMatchObject({ kind: 'auth' });+ expect(fetchMock).toHaveBeenCalledTimes(4);+ });+ });++ describe('stream registration', () => {+ it('posts credentials and subscriptions to /v1.0/gateway/connections/open', async () => {+ fetchMock.mockResolvedValueOnce(json({ endpoint: 'wss://x/connect', ticket: 'tk' }));++ const res = await client.openStreamConnection([+ { topic: '/v1.0/im/bot/messages/get', type: 'CALLBACK' },+ ]);++ expect(res).toEqual({ endpoint: 'wss://x/connect', ticket: 'tk' });+ expect(url(0)).toBe(`${DINGTALK_API_BASE_URL}/v1.0/gateway/connections/open`);+ expect(body(0)).toMatchObject({+ clientId: 'ding_client',+ clientSecret: 'ding_secret',+ subscriptions: [{ topic: '/v1.0/im/bot/messages/get', type: 'CALLBACK' }],+ });+ });++ it('throws a typed error when registration is rejected', async () => {+ fetchMock.mockResolvedValueOnce(json({ code: 'Forbidden.AccessDenied', message: 'no' }, 403));++ await expect(client.openStreamConnection([])).rejects.toMatchObject({+ code: 'Forbidden.AccessDenied',+ kind: 'permission',+ });+ });+ });++ describe('robot send', () => {+ beforeEach(() => {+ fetchMock.mockResolvedValueOnce(tokenResponse('tok'));+ });++ it('sends a single-chat message through oToMessages/batchSend', async () => {+ fetchMock.mockResolvedValueOnce(json({ processQueryKey: 'pqk' }));++ await client.sendSingleMessage(['staff_1'], {+ msgKey: 'sampleMarkdown',+ msgParam: { text: '**hi**', title: 'hi' },+ });++ expect(url(1)).toBe(`${DINGTALK_API_BASE_URL}/v1.0/robot/oToMessages/batchSend`);+ expect(body(1)).toEqual({+ msgKey: 'sampleMarkdown',+ msgParam: JSON.stringify({ text: '**hi**', title: 'hi' }),+ robotCode: 'ding_client',+ userIds: ['staff_1'],+ });+ });++ it('throws when batchSend rejects every recipient', async () => {+ fetchMock.mockResolvedValueOnce(+ json({ flowControlledStaffIdList: ['staff_1'], processQueryKey: 'pqk' }),+ );++ await expect(+ client.sendSingleMessage(['staff_1'], { msgKey: 'sampleText', msgParam: { content: 'x' } }),+ ).rejects.toMatchObject({ kind: 'rate_limit' });+ });++ it('sends a group message through groupMessages/send with robotCode', async () => {+ const custom = new DingTalkApiClient('ding_client', 'ding_secret', 'robot_x');+ fetchMock.mockResolvedValueOnce(json({ processQueryKey: 'pqk_g' }));++ const res = await custom.sendGroupMessage('cid_1', {+ msgKey: 'sampleText',+ msgParam: { content: 'hello' },+ });++ expect(res.processQueryKey).toBe('pqk_g');+ expect(url(1)).toBe(`${DINGTALK_API_BASE_URL}/v1.0/robot/groupMessages/send`);+ expect(body(1)).toEqual({+ msgKey: 'sampleText',+ msgParam: '{"content":"hello"}',+ openConversationId: 'cid_1',+ robotCode: 'robot_x',+ });+ });++ it('maps send.too.fast to a rate_limit error and keeps the DingTalk code', async () => {+ fetchMock.mockResolvedValueOnce(+ json({ code: 'send.too.fast', message: '发送太快', requestid: 'req_1' }, 400),+ );++ const error = await client+ .sendGroupMessage('cid', { msgKey: 'sampleText', msgParam: { content: 'x' } })+ .catch((e) => e);+ expect(error).toMatchObject({+ code: 'send.too.fast',+ kind: 'rate_limit',+ requestId: 'req_1',+ status: 400,+ });+ });++ it('exchanges a downloadCode for a temporary URL and downloads it', async () => {+ fetchMock+ .mockResolvedValueOnce(json({ downloadUrl: 'https://cdn.dingtalk.com/f.png' }))+ .mockResolvedValueOnce(new Response(new Uint8Array([1, 2, 3])));++ const buf = await client.downloadFile('dc_1');++ expect(url(1)).toBe(`${DINGTALK_API_BASE_URL}/v1.0/robot/messageFiles/download`);+ expect(body(1)).toEqual({ downloadCode: 'dc_1', robotCode: 'ding_client' });+ expect(url(2)).toBe('https://cdn.dingtalk.com/f.png');+ expect([...buf]).toEqual([1, 2, 3]);+ });+ });++ describe('sessionWebhook', () => {+ const WEBHOOK = 'https://oapi.dingtalk.com/robot/sendBySession?session=abc';++ it('posts text without an access token', async () => {+ fetchMock.mockResolvedValueOnce(json({ errcode: 0, errmsg: 'ok' }));++ await client.replyViaSessionWebhook(WEBHOOK, {+ msgKey: 'sampleText',+ msgParam: { content: 'hi' },+ });++ expect(url(0)).toBe(WEBHOOK);+ expect(fetchMock.mock.calls[0][1].headers['x-acs-dingtalk-access-token']).toBeUndefined();+ expect(body(0)).toEqual({ msgtype: 'text', text: { content: 'hi' } });+ });++ it('posts markdown with @ users', async () => {+ fetchMock.mockResolvedValueOnce(json({ errcode: 0 }));++ await client.replyViaSessionWebhook(+ WEBHOOK,+ { msgKey: 'sampleMarkdown', msgParam: { text: '# T', title: 'T' } },+ ['staff_1'],+ );++ expect(body(0)).toEqual({+ at: { atUserIds: ['staff_1'] },+ markdown: { text: '# T', title: 'T' },+ msgtype: 'markdown',+ });+ });++ it('throws a session_webhook error on a non-zero errcode (expired session)', async () => {+ fetchMock.mockResolvedValueOnce(json({ errcode: 300001, errmsg: 'session expired' }));++ await expect(+ client.replyViaSessionWebhook(WEBHOOK, {+ msgKey: 'sampleText',+ msgParam: { content: 'x' },+ }),+ ).rejects.toMatchObject({ code: '300001', kind: 'session_webhook' });+ });++ it('throws a session_webhook error on network failure', async () => {+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));++ await expect(+ client.replyViaSessionWebhook(WEBHOOK, {+ msgKey: 'sampleText',+ msgParam: { content: 'x' },+ }),+ ).rejects.toMatchObject({ kind: 'session_webhook', status: 0 });+ });+ });+});++describe('classifyDingTalkError', () => {+ it.each([+ [401, undefined, 'auth'],+ [400, 'invalidParameter.token.invalid', 'auth'],+ [403, 'Forbidden.AccessDenied.AccessTokenInvalid', 'auth'],+ [400, 'send.too.fast', 'rate_limit'],+ [400, 'send.byToken.tooFast', 'rate_limit'],+ [429, 'Throttling.Api', 'rate_limit'],+ [400, 'too.many.people', 'rate_limit'],+ [403, 'Forbidden.AccessDenied.IpNotInWhiteList', 'permission'],+ [400, 'bot.forbidden.sendMessage', 'permission'],+ [400, 'invalidParameter.robotCode.notExsit', 'invalid_request'],+ [500, 'system.error', 'server'],+ [503, undefined, 'server'],+ ] as const)('status %d code %s → %s', (status, code, kind) => {+ expect(classifyDingTalkError(status, code)).toBe(kind);+ });+});++describe('truncateUtf8', () => {+ it('keeps short text unchanged', () => {+ expect(truncateUtf8('hello', 100)).toBe('hello');+ });++ it('cuts multi-byte text on a character boundary within the byte budget', () => {+ const text = '钉'.repeat(10); // 30 bytes+ const out = truncateUtf8(text, 12);+ expect(new TextEncoder().encode(out).length).toBeLessThanOrEqual(12);+ expect(out).toBe('钉钉钉...');+ });+});diff --git a/packages/chat-adapter-dingtalk/src/api.ts b/packages/chat-adapter-dingtalk/src/api.tsnew file mode 100644index 00000000000..13e684c2e0e--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/api.ts@@ -0,0 +1,397 @@+import type {+ DingTalkAccessTokenResponse,+ DingTalkApiErrorBody,+ DingTalkBatchSendResponse,+ DingTalkConnectionOpenResponse,+ DingTalkFileDownloadResponse,+ DingTalkGroupSendResponse,+ DingTalkOutboundMessage,+ DingTalkSessionWebhookResponse,+ DingTalkStreamSubscription,+} from './types';++export const DINGTALK_API_BASE_URL = 'https://api.dingtalk.com';++/** `msgParam` of `groupMessages/send` is capped at 15000 bytes; keep headroom for JSON escaping. */+export const MAX_MSG_PARAM_TEXT_BYTES = 12_000;++/** Refresh the cached token this long before DingTalk's stated expiry. */+const TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;+const REQUEST_TIMEOUT_MS = 30_000;+const STREAM_UA = 'lobehub-chat-adapter-dingtalk/0.1.0';++export type DingTalkErrorKind =+ | 'auth'+ | 'invalid_request'+ | 'permission'+ | 'rate_limit'+ | 'server'+ | 'session_webhook'+ | 'unknown';++/**+ * Error raised for any non-success DingTalk response. `kind` is a coarse,+ * platform-independent classification callers can branch on; `code` keeps+ * DingTalk's original error code (e.g. `send.too.fast`, `InvalidAuthentication`).+ */+export class DingTalkApiError extends Error {+ readonly code?: string;+ readonly kind: DingTalkErrorKind;+ readonly requestId?: string;+ readonly status: number;++ constructor(options: {+ code?: string;+ kind: DingTalkErrorKind;+ message: string;+ requestId?: string;+ status: number;+ }) {+ super(options.message);+ this.name = 'DingTalkApiError';+ this.code = options.code;+ this.kind = options.kind;+ this.requestId = options.requestId;+ this.status = options.status;+ }+}++const AUTH_ERROR_CODES = new Set([+ 'Forbidden.AccessDenied.AccessTokenInvalid',+ 'InvalidAuthentication',+ 'invalidParameter.token.invalid',+]);++const RATE_LIMIT_PATTERN = /throttl|too\.?fast|qpslimit|too\.many/i;+const PERMISSION_CODES = new Set(['bot.forbidden.sendMessage', 'send.forbidden', 'unauthorized']);++/** Map an HTTP status + DingTalk error code to an error kind. */+export function classifyDingTalkError(status: number, code?: string): DingTalkErrorKind {+ if (status === 401 || (code && AUTH_ERROR_CODES.has(code))) return 'auth';+ if (status === 429 || (code && RATE_LIMIT_PATTERN.test(code))) return 'rate_limit';+ if (status === 403 || (code && (PERMISSION_CODES.has(code) || code.startsWith('Forbidden')))) {+ return 'permission';+ }+ if (status >= 500 || code === 'system.error') return 'server';+ if (status >= 400) return 'invalid_request';+ return 'unknown';+}++async function toApiError(response: Response, context: string): Promise<DingTalkApiError> {+ const text = await response.text().catch(() => '');+ let body: DingTalkApiErrorBody = {};+ try {+ body = JSON.parse(text) as DingTalkApiErrorBody;+ } catch {+ // non-JSON body+ }++ return new DingTalkApiError({+ code: body.code,+ kind: classifyDingTalkError(response.status, body.code),+ message: `DingTalk ${context} failed: ${response.status} ${body.code ?? ''} ${+ body.message ?? text+ }`.trim(),+ requestId: body.requestid,+ status: response.status,+ });+}++/** Truncate a string so its UTF-8 encoding stays within `maxBytes`. */+export function truncateUtf8(text: string, maxBytes: number): string {+ const encoder = new TextEncoder();+ if (encoder.encode(text).length <= maxBytes) return text;++ const suffix = '...';+ const budget = maxBytes - suffix.length;+ let bytes = 0;+ let end = 0;+ for (const char of text) {+ const size = encoder.encode(char).length;+ if (bytes + size > budget) break;+ bytes += size;+ end += char.length;+ }+ return text.slice(0, end) + suffix;+}++export class DingTalkApiClient {+ readonly clientId: string;+ readonly robotCode: string;+ private readonly clientSecret: string;+ private cachedToken?: string;+ private tokenExpiresAt = 0;+ private pendingToken?: Promise<string>;++ constructor(clientId: string, clientSecret: string, robotCode?: string) {+ this.clientId = clientId;+ this.clientSecret = clientSecret;+ this.robotCode = robotCode || clientId;+ }++ // ==================== Auth ====================++ /**+ * Get an internal-app access token (`POST /v1.0/oauth2/accessToken`).+ * Cached until 5 minutes before `expireIn`; concurrent callers share one request.+ */+ async getAccessToken(): Promise<string> {+ if (this.cachedToken && Date.now() < this.tokenExpiresAt) {+ return this.cachedToken;+ }+ if (this.pendingToken) return this.pendingToken;++ this.pendingToken = this.fetchAccessToken().finally(() => {+ this.pendingToken = undefined;+ });+ return this.pendingToken;+ }++ /** Drop the cached token so the next call fetches a new one. */+ invalidateAccessToken(): void {+ this.cachedToken = undefined;+ this.tokenExpiresAt = 0;+ }++ private async fetchAccessToken(): Promise<string> {+ const response = await fetch(`${DINGTALK_API_BASE_URL}/v1.0/oauth2/accessToken`, {+ body: JSON.stringify({ appKey: this.clientId, appSecret: this.clientSecret }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });++ if (!response.ok) {+ const error = await toApiError(response, 'auth');+ // Any 4xx from the token endpoint means the credentials are wrong.+ if (response.status < 500) {+ throw new DingTalkApiError({+ code: error.code,+ kind: 'auth',+ message: error.message,+ requestId: error.requestId,+ status: error.status,+ });+ }+ throw error;+ }++ const data = (await response.json()) as DingTalkAccessTokenResponse;+ if (!data.accessToken) {+ throw new DingTalkApiError({+ kind: 'auth',+ message: 'DingTalk auth failed: response has no accessToken',+ status: response.status,+ });+ }++ this.cachedToken = data.accessToken;+ const ttlMs = (data.expireIn || 7200) * 1000;+ this.tokenExpiresAt = Date.now() + Math.max(ttlMs - TOKEN_REFRESH_MARGIN_MS, ttlMs / 2);+ return data.accessToken;+ }++ /**+ * Authenticated OpenAPI call. An auth failure (token revoked or expired+ * early) invalidates the cached token and retries once with a fresh one.+ */+ private async call<T>(path: string, body: Record<string, unknown>, retried = false): Promise<T> {+ const token = await this.getAccessToken();+ const response = await fetch(`${DINGTALK_API_BASE_URL}${path}`, {+ body: JSON.stringify(body),+ headers: {+ 'Content-Type': 'application/json',+ 'x-acs-dingtalk-access-token': token,+ },+ method: 'POST',+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });++ if (!response.ok) {+ const error = await toApiError(response, `API POST ${path}`);+ if (error.kind === 'auth' && !retried) {+ this.invalidateAccessToken();+ return this.call<T>(path, body, true);+ }+ throw error;+ }++ const text = await response.text();+ return (text ? JSON.parse(text) : {}) as T;+ }++ // ==================== Stream gateway ====================++ /**+ * Register a Stream connection (`POST /v1.0/gateway/connections/open`).+ * Uses the client credentials directly, not an access token. The returned+ * ticket is single-use and valid for 90 seconds.+ */+ async openStreamConnection(+ subscriptions: DingTalkStreamSubscription[],+ ): Promise<DingTalkConnectionOpenResponse> {+ const response = await fetch(`${DINGTALK_API_BASE_URL}/v1.0/gateway/connections/open`, {+ body: JSON.stringify({+ clientId: this.clientId,+ clientSecret: this.clientSecret,+ subscriptions,+ ua: STREAM_UA,+ }),+ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },+ method: 'POST',+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });++ if (!response.ok) {+ throw await toApiError(response, 'stream connection open');+ }++ const data = (await response.json()) as DingTalkConnectionOpenResponse;+ if (!data.endpoint || !data.ticket) {+ throw new DingTalkApiError({+ kind: 'unknown',+ message: 'DingTalk stream connection open returned no endpoint/ticket',+ status: response.status,+ });+ }+ return data;+ }++ // ==================== Robot messages ====================++ /** Send a one-on-one message (`POST /v1.0/robot/oToMessages/batchSend`). */+ async sendSingleMessage(+ userIds: string[],+ message: DingTalkOutboundMessage,+ ): Promise<DingTalkBatchSendResponse> {+ const result = await this.call<DingTalkBatchSendResponse>('/v1.0/robot/oToMessages/batchSend', {+ msgKey: message.msgKey,+ msgParam: JSON.stringify(message.msgParam),+ robotCode: this.robotCode,+ userIds,+ });++ const rejected = [+ ...(result.invalidStaffIdList ?? []).map((id) => ({ id, kind: 'invalid_request' as const })),+ ...(result.flowControlledStaffIdList ?? []).map((id) => ({+ id,+ kind: 'rate_limit' as const,+ })),+ ];+ // batchSend answers 200 even when every recipient was rejected.+ if (rejected.length > 0 && rejected.length >= userIds.length) {+ const first = rejected[0];+ throw new DingTalkApiError({+ code: first.kind === 'rate_limit' ? 'flowControlled' : 'invalidStaffId',+ kind: first.kind,+ message: `DingTalk batchSend rejected recipients: ${rejected.map((r) => r.id).join(',')}`,+ status: 200,+ });+ }+ return result;+ }++ /** Send a group message (`POST /v1.0/robot/groupMessages/send`). */+ async sendGroupMessage(+ openConversationId: string,+ message: DingTalkOutboundMessage,+ ): Promise<DingTalkGroupSendResponse> {+ return this.call<DingTalkGroupSendResponse>('/v1.0/robot/groupMessages/send', {+ msgKey: message.msgKey,+ msgParam: JSON.stringify(message.msgParam),+ openConversationId,+ robotCode: this.robotCode,+ });+ }++ /**+ * Reply through the callback's `sessionWebhook`. The URL itself is the+ * credential, so no access token is sent. DingTalk answers HTTP 200 with a+ * non-zero `errcode` on failure (e.g. an expired session); both cases throw+ * a `session_webhook` error so callers can fall back to the OpenAPI.+ */+ async replyViaSessionWebhook(+ sessionWebhook: string,+ message: DingTalkOutboundMessage,+ atUserIds?: string[],+ ): Promise<void> {+ const at = atUserIds?.length ? { atUserIds } : undefined;+ let body: Record<string, unknown>;+ switch (message.msgKey) {+ case 'sampleText': {+ body = { at, msgtype: 'text', text: { content: message.msgParam.content } };+ break;+ }+ case 'sampleMarkdown': {+ body = { at, markdown: message.msgParam, msgtype: 'markdown' };+ break;+ }+ case 'sampleImageMsg': {+ body = {+ at,+ markdown: { text: ``, title: 'image' },+ msgtype: 'markdown',+ };+ break;+ }+ }++ let response: Response;+ try {+ response = await fetch(sessionWebhook, {+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ } catch (err) {+ throw new DingTalkApiError({+ kind: 'session_webhook',+ message: `DingTalk sessionWebhook request failed: ${(err as Error)?.message ?? err}`,+ status: 0,+ });+ }++ const text = await response.text().catch(() => '');+ let data: DingTalkSessionWebhookResponse = {};+ try {+ data = text ? (JSON.parse(text) as DingTalkSessionWebhookResponse) : {};+ } catch {+ // non-JSON body+ }++ if (!response.ok || (data.errcode !== undefined && data.errcode !== 0)) {+ throw new DingTalkApiError({+ code: data.errcode !== undefined ? String(data.errcode) : undefined,+ kind: 'session_webhook',+ message: `DingTalk sessionWebhook failed: ${response.status} ${data.errcode ?? ''} ${+ data.errmsg ?? text+ }`.trim(),+ status: response.status,+ });+ }+ }++ // ==================== Files ====================++ /**+ * Exchange an inbound message `downloadCode` for a temporary download URL+ * (`POST /v1.0/robot/messageFiles/download`).+ */+ async getFileDownloadUrl(downloadCode: string): Promise<string> {+ const data = await this.call<DingTalkFileDownloadResponse>(+ '/v1.0/robot/messageFiles/download',+ { downloadCode, robotCode: this.robotCode },+ );+ return data.downloadUrl;+ }++ async downloadFile(downloadCode: string): Promise<Buffer> {+ const url = await this.getFileDownloadUrl(downloadCode);+ const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });+ if (!response.ok) {+ throw await toApiError(response, 'file download');+ }+ return Buffer.from(await response.arrayBuffer());+ }+}diff --git a/packages/chat-adapter-dingtalk/src/crypto.ts b/packages/chat-adapter-dingtalk/src/crypto.tsnew file mode 100644index 00000000000..f91f420dab7--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/crypto.ts@@ -0,0 +1,34 @@+import { createHmac, timingSafeEqual } from 'node:crypto';++/** DingTalk rejects HTTP callbacks whose timestamp drifts more than 1 hour. */+export const CALLBACK_MAX_SKEW_MS = 60 * 60 * 1000;++/**+ * Compute the robot callback signature used by DingTalk's HTTP callback mode:+ * `Base64(HmacSHA256(key = clientSecret, message = timestamp + "\n" + clientSecret))`,+ * sent in the `sign` header next to a `timestamp` (Unix ms) header.+ *+ * The Stream gateway signs the events it forwards the same way, so the+ * webhook handler authenticates both paths with one check.+ */+export function signCallback(timestamp: string, clientSecret: string): string {+ return createHmac('sha256', clientSecret)+ .update(`${timestamp}\n${clientSecret}`)+ .digest('base64');+}++export function verifyCallbackSignature(+ timestamp: string | null,+ sign: string | null,+ clientSecret: string,+ now = Date.now(),+): boolean {+ if (!timestamp || !sign) return false;++ const ts = Number(timestamp);+ if (!Number.isFinite(ts) || Math.abs(now - ts) > CALLBACK_MAX_SKEW_MS) return false;++ const expected = Buffer.from(signCallback(timestamp, clientSecret));+ const actual = Buffer.from(sign);+ return expected.length === actual.length && timingSafeEqual(expected, actual);+}diff --git a/packages/chat-adapter-dingtalk/src/format-converter.test.ts b/packages/chat-adapter-dingtalk/src/format-converter.test.tsnew file mode 100644index 00000000000..b6acc4ddf65--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/format-converter.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import { DingTalkFormatConverter } from './format-converter';++const converter = new DingTalkFormatConverter();++describe('DingTalkFormatConverter', () => {+ it('derives the title from link text and picks markdown for link syntax', () => {+ expect(converter.deriveTitle('[Docs](https://example.com) for you')).toBe('Docs for you');+ expect(converter.toOutboundMessage('see [a](https://x.y)', 'see [a](https://x.y)').msgKey).toBe(+ 'sampleMarkdown',+ );+ expect(converter.toOutboundMessage('plain [text] (here)', 'plain [text] (here)').msgKey).toBe(+ 'sampleText',+ );+ });++ // Unclosed brackets / parens must not make the link patterns rescan the rest of+ // the line from every start position (polynomial ReDoS on agent output). At this+ // size a polynomial scan runs far past the test timeout, so finishing is the guard;+ // the assertions pin the outcome rather than a machine-dependent duration.+ it.each([+ ['unclosed brackets', '['.repeat(50_000)],+ ['unclosed link targets', '[]('.repeat(50_000)],+ ])('treats %s as plain text', (_, text) => {+ expect(converter.toOutboundMessage(text, text).msgKey).toBe('sampleText');+ expect(typeof converter.deriveTitle(text)).toBe('string');+ });+});diff --git a/packages/chat-adapter-dingtalk/src/format-converter.ts b/packages/chat-adapter-dingtalk/src/format-converter.tsnew file mode 100644index 00000000000..aa13bb13e29--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/format-converter.ts@@ -0,0 +1,68 @@+import type { AdapterPostableMessage, Root } from 'chat';+import { BaseFormatConverter, parseMarkdown, stringifyMarkdown } from 'chat';++import type { DingTalkOutboundMessage } from './types';++/**+ * Markdown syntax DingTalk renders in `sampleMarkdown` (headings, emphasis, links, lists, quotes, code).+ * Link parts exclude their own opening delimiter so an unclosed `[` / `(` cannot make the scan+ * restart from every later position (polynomial backtracking).+ */+const MARKDOWN_SYNTAX =+ /(^|\n)\s{0,3}(#{1,6}\s|>\s|[-*+]\s|\d+\.\s)|\*\*|__|`|!?\[[^[\]]*]\([^()]+\)/;+const TITLE_MAX_LENGTH = 20;++export class DingTalkFormatConverter extends BaseFormatConverter {+ /** DingTalk renders markdown natively, so mdast is stringified back to markdown. */+ fromAst(ast: Root): string {+ return stringifyMarkdown(ast);+ }++ toAst(text: string): Root {+ return parseMarkdown(this.cleanText(text));+ }++ /**+ * Inbound group text arrives with the leading `@robot` mention already+ * removed by DingTalk but keeps the separating U+2005 (four-per-em space); normalise it.+ */+ cleanText(text: string): string {+ return text.replaceAll('\u2005', ' ').trim();+ }++ /**+ * Pick the robot message template for an outbound message: markdown when the+ * caller sent markdown/AST or the text contains markdown syntax, else plain text.+ */+ toOutboundMessage(message: AdapterPostableMessage, text: string): DingTalkOutboundMessage {+ const isStructured =+ typeof message === 'object' &&+ message !== null &&+ ('markdown' in message || 'ast' in message);++ if (isStructured || MARKDOWN_SYNTAX.test(text)) {+ return { msgKey: 'sampleMarkdown', msgParam: { text, title: this.deriveTitle(text) } };+ }+ return { msgKey: 'sampleText', msgParam: { content: text } };+ }++ /** The markdown title is what DingTalk shows in notifications and the chat list. */+ deriveTitle(markdown: string): string {+ const firstLine =+ markdown+ .split('\n')+ .map((line) =>+ line+ .replaceAll(/!?\[([^[\]]*)]\([^()]*\)/g, '$1')+ .replaceAll(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/g, '')+ .replaceAll(/[*_`~]/g, '')+ .trim(),+ )+ .find(Boolean) ?? '';++ if (!firstLine) return 'Message';+ return firstLine.length > TITLE_MAX_LENGTH+ ? `${firstLine.slice(0, TITLE_MAX_LENGTH - 1)}…`+ : firstLine;+ }+}diff --git a/packages/chat-adapter-dingtalk/src/gateway.test.ts b/packages/chat-adapter-dingtalk/src/gateway.test.tsnew file mode 100644index 00000000000..eb9bc48ef3c--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/gateway.test.ts@@ -0,0 +1,426 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { verifyCallbackSignature } from './crypto';+import type { DingTalkGatewayOptions } from './gateway';+import { DEFAULT_STREAM_SUBSCRIPTIONS, DingTalkStreamConnection } from './gateway';+import { DINGTALK_STREAM_TOPICS } from './types';++// ---- Mock WebSocket (`ws`) ----++const { MockWebSocket } = vi.hoisted(() => {+ class MockWebSocket {+ static OPEN = 1;+ static CLOSED = 3;+ static instances: MockWebSocket[] = [];+ /** When false, the socket never opens (simulates a rejected handshake). */+ static autoOpen = true;++ readyState = 0;+ url: string;+ sentMessages: string[] = [];+ closeCalls: Array<{ code?: number; reason?: string }> = [];+ /** Half-open TCP: the peer never answers the close frame, so no `close` event fires. */+ hangOnClose = false;+ /** When false the peer swallows pings (half-open socket). */+ answerPings = true;+ pings = 0;+ terminated = false;+ private listeners = new Map<string, Array<(...args: any[]) => void>>();++ constructor(url: string) {+ this.url = url;+ MockWebSocket.instances.push(this);+ if (MockWebSocket.autoOpen) {+ setTimeout(() => {+ this.readyState = MockWebSocket.OPEN;+ this.emit('open', {});+ }, 0);+ }+ }++ addEventListener(event: string, fn: (...args: any[]) => void) {+ this.listeners.set(event, [...(this.listeners.get(event) || []), fn]);+ }++ removeEventListener(event: string, fn: (...args: any[]) => void) {+ this.listeners.set(+ event,+ (this.listeners.get(event) || []).filter((f) => f !== fn),+ );+ }++ /** `ws`-style listener registration (used for `pong`). */+ on(event: string, fn: (...args: any[]) => void) {+ this.addEventListener(event, fn);+ }++ ping() {+ this.pings++;+ if (this.answerPings) setTimeout(() => this.emit('pong', undefined), 0);+ }++ terminate() {+ this.terminated = true;+ this.close(1006, 'terminated');+ }++ send(data: string) {+ this.sentMessages.push(data);+ }++ close(code?: number, reason?: string) {+ this.closeCalls.push({ code, reason });+ if (this.hangOnClose) return;+ if (this.readyState === MockWebSocket.CLOSED) return;+ this.readyState = MockWebSocket.CLOSED;+ this.emit('close', { code: code ?? 1000, reason: reason ?? '' });+ }++ emit(event: string, data: any) {+ for (const fn of this.listeners.get(event) || []) fn(data);+ }++ simulateFrame(frame: Record<string, any>) {+ this.emit('message', { data: JSON.stringify(frame) });+ }++ sent(): Array<Record<string, any>> {+ return this.sentMessages.map((m) => JSON.parse(m));+ }+ }+ return { MockWebSocket };+});++vi.mock('ws', () => ({ default: MockWebSocket }));++// ---- Helpers ----++const SECRET = 'test_client_secret';+const WEBHOOK_URL = 'http://localhost:3000/api/agent/webhooks/dingtalk/app_1';++function createMockApi() {+ let n = 0;+ return {+ openStreamConnection: vi.fn().mockImplementation(async () => {+ n++;+ return { endpoint: 'wss://wss-open-connection.dingtalk.com:443/connect', ticket: `t${n}` };+ }),+ } as any;+}++function botFrame(messageId = 'msg_1', data: Record<string, any> = { msgId: 'm1' }) {+ return {+ data: JSON.stringify(data),+ headers: {+ contentType: 'application/json',+ messageId,+ time: String(Date.now()),+ topic: DINGTALK_STREAM_TOPICS.BOT_MESSAGE,+ },+ specVersion: '1.0',+ type: 'CALLBACK',+ };+}++describe('DingTalkStreamConnection', () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ MockWebSocket.instances = [];+ MockWebSocket.autoOpen = true;+ fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);+ vi.useFakeTimers({ shouldAdvanceTime: true });+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ function create(overrides?: Partial<DingTalkGatewayOptions>) {+ const api = createMockApi();+ const conn = new DingTalkStreamConnection(api, {+ clientSecret: SECRET,+ log: vi.fn(),+ webhookUrl: WEBHOOK_URL,+ ...overrides,+ });+ return { api, conn };+ }++ async function connected(overrides?: Partial<DingTalkGatewayOptions>) {+ const ctx = create(overrides);+ const promise = ctx.conn.connect();+ await vi.advanceTimersByTimeAsync(10);+ await promise;+ return { ...ctx, ws: MockWebSocket.instances[0] };+ }++ describe('handshake', () => {+ it('registers the connection and opens the socket with the ticket', async () => {+ const { api, ws, conn } = await connected();++ expect(api.openStreamConnection).toHaveBeenCalledWith(DEFAULT_STREAM_SUBSCRIPTIONS);+ expect(DEFAULT_STREAM_SUBSCRIPTIONS).toEqual([+ { topic: '/v1.0/im/bot/messages/get', type: 'CALLBACK' },+ ]);+ expect(ws.url).toBe('wss://wss-open-connection.dingtalk.com:443/connect?ticket=t1');+ conn.close();+ });++ it('rejects when registration fails (bad credentials)', async () => {+ const { api, conn } = create();+ api.openStreamConnection.mockRejectedValueOnce(new Error('invalid clientId'));++ await expect(conn.connect()).rejects.toThrow('invalid clientId');+ expect(MockWebSocket.instances).toHaveLength(0);+ });++ it('rejects when the socket closes before opening, without reconnecting', async () => {+ MockWebSocket.autoOpen = false;+ const { api, conn } = create();+ const promise = conn.connect();+ await vi.advanceTimersByTimeAsync(10);++ MockWebSocket.instances[0].close(1006, 'ticket expired');+ await expect(promise).rejects.toThrow(/closed before open: code=1006/);++ await vi.advanceTimersByTimeAsync(120_000);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(1);+ });+ });++ describe('ACK', () => {+ it('echoes ping frames with the same messageId and opaque data', async () => {+ const { ws, conn } = await connected();++ ws.simulateFrame({+ data: '{"opaque":"abc-123"}',+ headers: { messageId: 'ping_1', topic: 'ping' },+ type: 'SYSTEM',+ });++ expect(ws.sent()).toEqual([+ {+ code: 200,+ data: '{"opaque":"abc-123"}',+ headers: { contentType: 'application/json', messageId: 'ping_1' },+ message: 'OK',+ },+ ]);+ expect(fetchMock).not.toHaveBeenCalled();+ conn.close();+ });++ it('ACKs a robot message and forwards it to the webhook with a valid signature', async () => {+ const { ws, conn } = await connected();+ const data = { conversationId: 'cid1', msgId: 'm1', text: { content: 'hi' } };++ ws.simulateFrame(botFrame('cb_1', data));++ expect(ws.sent()).toEqual([+ {+ code: 200,+ data: JSON.stringify({ response: null }),+ headers: { contentType: 'application/json', messageId: 'cb_1' },+ message: 'OK',+ },+ ]);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(WEBHOOK_URL);+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual(data);+ expect(verifyCallbackSignature(init.headers.timestamp, init.headers.sign, SECRET)).toBe(true);+ conn.close();+ });++ it('answers 404 for an unsubscribed callback topic and does not forward it', async () => {+ const { ws, conn } = await connected();++ ws.simulateFrame({+ data: '{}',+ headers: { messageId: 'card_1', topic: '/v1.0/card/instances/callback' },+ type: 'CALLBACK',+ });++ expect(ws.sent()[0]).toMatchObject({ code: 404, headers: { messageId: 'card_1' } });+ expect(fetchMock).not.toHaveBeenCalled();+ conn.close();+ });++ it('ACKs event frames as SUCCESS so they are not redelivered', async () => {+ const { ws, conn } = await connected();++ ws.simulateFrame({ data: '{}', headers: { messageId: 'ev_1', topic: '*' }, type: 'EVENT' });++ const ack = ws.sent()[0];+ expect(ack.code).toBe(200);+ expect(JSON.parse(ack.data).status).toBe('SUCCESS');+ conn.close();+ });++ it('ignores malformed frames', async () => {+ const { ws, conn } = await connected();+ ws.emit('message', { data: 'not json' });+ expect(ws.sentMessages).toHaveLength(0);+ conn.close();+ });++ it('keeps the socket alive when forwarding fails', async () => {+ fetchMock.mockRejectedValueOnce(new Error('ECONNREFUSED'));+ const { ws, conn } = await connected();++ ws.simulateFrame(botFrame());+ await vi.advanceTimersByTimeAsync(10);++ expect(ws.readyState).toBe(MockWebSocket.OPEN);+ expect(ws.sent()[0].code).toBe(200);+ conn.close();+ });+ });++ describe('reconnect', () => {+ it('reconnects with a fresh ticket after a server disconnect frame', async () => {+ const { api, ws, conn } = await connected();++ ws.simulateFrame({+ data: '{"reason":"connection expired"}',+ headers: { messageId: 'sys_1', topic: 'disconnect' },+ type: 'SYSTEM',+ });+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);++ await vi.advanceTimersByTimeAsync(1100);++ expect(api.openStreamConnection).toHaveBeenCalledTimes(2);+ expect(MockWebSocket.instances).toHaveLength(2);+ expect(MockWebSocket.instances[1].url).toMatch(/ticket=t2$/);+ conn.close();+ });++ it('backs off exponentially when registration keeps failing, then recovers', async () => {+ const { api, ws, conn } = await connected();+ api.openStreamConnection+ .mockRejectedValueOnce(new Error('503'))+ .mockRejectedValueOnce(new Error('503'));++ ws.close(1006, 'network');++ await vi.advanceTimersByTimeAsync(1000); // attempt 1 (1s) fails+ expect(api.openStreamConnection).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1500); // attempt 2 not before 2s+ expect(api.openStreamConnection).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(600); // attempt 2 (2s) fails+ expect(api.openStreamConnection).toHaveBeenCalledTimes(3);+ await vi.advanceTimersByTimeAsync(4100); // attempt 3 (4s) succeeds+ expect(api.openStreamConnection).toHaveBeenCalledTimes(4);++ const latest = MockWebSocket.instances.at(-1)!;+ expect(latest.url).toMatch(/ticket=t\d+$/);+ expect(latest.readyState).toBe(MockWebSocket.OPEN);++ // attempts reset after a successful open: next drop retries after 1s again+ latest.close(1006, 'network');+ await vi.advanceTimersByTimeAsync(1100);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(5);+ conn.close();+ });++ it('keeps a silent connection that answers pings (idle streams carry no frames)', async () => {+ const { api, ws, conn } = await connected({ pingIntervalMs: 10_000 });++ await vi.advanceTimersByTimeAsync(300_000);++ expect(ws.pings).toBeGreaterThanOrEqual(29);+ expect(ws.readyState).toBe(MockWebSocket.OPEN);+ expect(ws.terminated).toBe(false);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(1);+ conn.close();+ });++ it('replaces a half-open connection that stops answering pings', async () => {+ const { api, ws, conn } = await connected({ pingIntervalMs: 10_000 });+ ws.answerPings = false;++ await vi.advanceTimersByTimeAsync(10_000); // ping sent, no pong+ expect(ws.terminated).toBe(false);+ await vi.advanceTimersByTimeAsync(10_000); // pong window missed+ expect(ws.terminated).toBe(true);++ await vi.advanceTimersByTimeAsync(1100);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(2);+ expect(MockWebSocket.instances).toHaveLength(2);+ conn.close();+ });++ it('reconnects once even when the half-open socket never emits close', async () => {+ const { api, ws, conn } = await connected({ pingIntervalMs: 10_000 });+ ws.answerPings = false;+ ws.hangOnClose = true;++ await vi.advanceTimersByTimeAsync(20_000);+ expect(ws.terminated).toBe(true);++ await vi.advanceTimersByTimeAsync(1100);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(2);++ // The retired socket finally closing (TCP timeout) must not trigger another reconnect.+ ws.hangOnClose = false;+ ws.readyState = MockWebSocket.OPEN;+ ws.close(1006, 'tcp timeout');+ await vi.advanceTimersByTimeAsync(5000);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(2);+ conn.close();+ });++ it('keeps retrying at the capped delay while registration stays down', async () => {+ const { api, ws, conn } = await connected();+ api.openStreamConnection.mockRejectedValue(new Error('503 Service Unavailable'));++ ws.close(1006, 'network');+ // Well past the old 10-attempt budget (~5 minutes of backoff).+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ const attempts = api.openStreamConnection.mock.calls.length;+ expect(attempts).toBeGreaterThan(11);++ // Registration recovers: the next capped retry reconnects.+ api.openStreamConnection.mockResolvedValue({ endpoint: 'wss://x/connect', ticket: 'back' });+ await vi.advanceTimersByTimeAsync(61_000);+ expect(MockWebSocket.instances.at(-1)!.url).toMatch(/ticket=back$/);+ expect(MockWebSocket.instances.at(-1)!.readyState).toBe(MockWebSocket.OPEN);+ conn.close();+ });++ it('does not reconnect after close()', async () => {+ const { api, ws, conn } = await connected();+ conn.close();++ expect(ws.closeCalls[0]).toEqual({ code: 1000, reason: 'Client shutdown' });+ await vi.advanceTimersByTimeAsync(120_000);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(1);+ });++ it('stops on abort signal', async () => {+ const controller = new AbortController();+ const { api, ws } = await connected({ abortSignal: controller.signal });++ controller.abort();+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);+ await vi.advanceTimersByTimeAsync(120_000);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(1);+ });++ it('closes after durationMs so the caller can restart it', async () => {+ const { api, ws } = await connected({ durationMs: 30_000 });++ await vi.advanceTimersByTimeAsync(30_000);+ expect(ws.readyState).toBe(MockWebSocket.CLOSED);+ await vi.advanceTimersByTimeAsync(120_000);+ expect(api.openStreamConnection).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/packages/chat-adapter-dingtalk/src/gateway.ts b/packages/chat-adapter-dingtalk/src/gateway.tsnew file mode 100644index 00000000000..b50297caca9--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/gateway.ts@@ -0,0 +1,345 @@+import WebSocket from 'ws';++import type { DingTalkApiClient } from './api';+import { signCallback } from './crypto';+import type { DingTalkStreamAck, DingTalkStreamFrame, DingTalkStreamSubscription } from './types';+import { DINGTALK_STREAM_FRAME_TYPES, DINGTALK_STREAM_TOPICS } from './types';++export type GatewayLogger = (...args: any[]) => void;++const noop: GatewayLogger = () => {};++const RECONNECT_BASE_DELAY_MS = 1000;+const RECONNECT_MAX_DELAY_MS = 60_000;++/**+ * An idle DingTalk stream carries no frames at all (measured: none in five+ * minutes on a healthy connection), so silence says nothing about liveness.+ * The client probes with protocol-level ping instead, as the official SDK+ * does: a socket that misses a whole pong window is half-open and replaced.+ */+const DEFAULT_PING_INTERVAL_MS = 30_000;++const FORWARD_TIMEOUT_MS = 30_000;++export const DEFAULT_STREAM_SUBSCRIPTIONS: DingTalkStreamSubscription[] = [+ { topic: DINGTALK_STREAM_TOPICS.BOT_MESSAGE, type: 'CALLBACK' },+];++export interface DingTalkGatewayOptions {+ /** AbortSignal to cancel the gateway connection */+ abortSignal?: AbortSignal;+ /** Client Secret used to sign forwarded events (same scheme as HTTP callback mode) */+ clientSecret: string;+ /** Duration in ms before the connection auto-closes (caller restarts) */+ durationMs?: number;+ /** Optional logger function (defaults to no-op) */+ log?: GatewayLogger;+ /** Protocol-level ping interval; a socket that misses one pong window is replaced */+ pingIntervalMs?: number;+ /** Topics to subscribe to; defaults to robot message callbacks */+ subscriptions?: DingTalkStreamSubscription[];+ /** URL to forward robot message callbacks to (POST) */+ webhookUrl: string;+}++/**+ * DingTalk Stream mode client.+ *+ * Lifecycle: `POST /v1.0/gateway/connections/open` (endpoint + one-shot+ * ticket) → WebSocket `endpoint?ticket=...` → answer `ping`, ACK every+ * callback, forward robot messages to `webhookUrl` → on `disconnect` or socket+ * loss, register again (tickets are single-use) and reconnect with backoff.+ */+export class DingTalkStreamConnection {+ private readonly api: DingTalkApiClient;+ private readonly options: DingTalkGatewayOptions;+ private readonly log: GatewayLogger;+ private readonly pingIntervalMs: number;++ private ws: WebSocket | null = null;+ private closed = false;+ private hasConnected = false;+ private reconnectAttempts = 0;+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;+ private durationTimer: ReturnType<typeof setTimeout> | null = null;+ private pingTimer: ReturnType<typeof setInterval> | null = null;+ private awaitingPong = false;+ /** Sockets replaced by the liveness probe; their late `close` must not schedule a reconnect. */+ private readonly retiredSockets = new WeakSet<WebSocket>();+ private onAbort?: () => void;++ constructor(api: DingTalkApiClient, options: DingTalkGatewayOptions) {+ this.api = api;+ this.options = options;+ this.log = options.log ?? noop;+ this.pingIntervalMs = options.pingIntervalMs ?? DEFAULT_PING_INTERVAL_MS;+ }++ /**+ * Open the stream. Resolves once the first WebSocket handshake succeeds;+ * rejects when registration or the first handshake fails (bad credentials,+ * Stream mode not enabled, network).+ */+ async connect(): Promise<void> {+ if (this.options.abortSignal?.aborted || this.closed) return;++ this.onAbort = () => this.close();+ this.options.abortSignal?.addEventListener('abort', this.onAbort, { once: true });++ if (this.options.durationMs) {+ this.durationTimer = setTimeout(() => {+ if (!this.closed) {+ this.log('Duration elapsed (%dms), closing', this.options.durationMs);+ this.close();+ }+ }, this.options.durationMs);+ }++ try {+ await this.openConnection();+ } catch (err) {+ this.close();+ throw err;+ }+ }++ /** Gracefully close the stream; no reconnect afterwards. */+ close(): void {+ this.closed = true;+ this.stopPing();+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);+ if (this.durationTimer) clearTimeout(this.durationTimer);+ this.reconnectTimer = null;+ this.durationTimer = null;+ if (this.onAbort) {+ this.options.abortSignal?.removeEventListener('abort', this.onAbort);+ this.onAbort = undefined;+ }+ const ws = this.ws;+ this.ws = null;+ ws?.close(1000, 'Client shutdown');+ }++ // ---------- Connection Management ----------++ private get stopped(): boolean {+ return this.closed || !!this.options.abortSignal?.aborted;+ }++ private async openConnection(): Promise<void> {+ const { endpoint, ticket } = await this.api.openStreamConnection(+ this.options.subscriptions ?? DEFAULT_STREAM_SUBSCRIPTIONS,+ );+ if (this.stopped) return;++ const separator = endpoint.includes('?') ? '&' : '?';+ const url = `${endpoint}${separator}ticket=${encodeURIComponent(ticket)}`;+ this.log('Stream endpoint: %s', endpoint);++ return new Promise<void>((resolve, reject) => {+ const ws = new WebSocket(url);+ this.ws = ws;+ let settled = false;+ const settle = (err?: Error) => {+ if (settled) return;+ settled = true;+ if (err) reject(err);+ else resolve();+ };++ ws.addEventListener('open', () => {+ if (this.ws !== ws) return;+ this.log('Stream WebSocket connected');+ this.hasConnected = true;+ this.reconnectAttempts = 0;+ this.startPing(ws);+ settle();+ });++ ws.addEventListener('message', (event) => {+ if (this.ws !== ws) return;+ const raw =+ typeof event.data === 'string'+ ? event.data+ : new TextDecoder().decode(event.data as ArrayBuffer);+ this.handleFrame(ws, raw);+ });++ ws.on('pong', () => {+ if (this.ws === ws) this.awaitingPong = false;+ });++ ws.addEventListener('close', (event) => {+ this.log('Stream WebSocket closed: code=%d reason=%s', event.code, event.reason);+ if (this.retiredSockets.has(ws)) return;+ if (this.ws !== ws && this.ws !== null) return;+ this.ws = null;+ this.stopPing();++ if (!settled) {+ settle(+ this.stopped+ ? undefined+ : new Error(+ `DingTalk stream socket closed before open: code=${event.code} reason=${+ event.reason || 'unknown'+ }`,+ ),+ );+ return;+ }++ if (!this.stopped) this.scheduleReconnect();+ });++ ws.addEventListener('error', (event) => {+ this.log('Stream WebSocket error: %O', event);+ settle(new Error('DingTalk stream WebSocket connection failed'));+ });+ });+ }++ private scheduleReconnect(): void {+ if (this.stopped || this.reconnectTimer) return;++ // No retry budget: the owning client already reported this connection as running, so+ // giving up would leave the bot silently offline until its next refresh. Retries back+ // off to one per RECONNECT_MAX_DELAY_MS and continue until the stream is back or closed.+ this.reconnectAttempts++;+ const delay = Math.min(+ RECONNECT_BASE_DELAY_MS * 2 ** (this.reconnectAttempts - 1),+ RECONNECT_MAX_DELAY_MS,+ );+ this.log('Reconnecting in %dms (attempt %d)', delay, this.reconnectAttempts);++ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null;+ if (this.stopped) return;+ // Tickets are single-use, so every reconnect registers again.+ this.openConnection().catch((err) => {+ this.log('Reconnect failed: %O', err);+ this.scheduleReconnect();+ });+ }, delay);+ }++ // ---------- Liveness ----------++ private startPing(ws: WebSocket): void {+ this.stopPing();+ this.pingTimer = setInterval(() => {+ if (this.ws !== ws || this.stopped) {+ this.stopPing();+ return;+ }+ if (this.awaitingPong) {+ this.log('No pong within %dms, replacing the connection', this.pingIntervalMs);+ // A half-open socket may never emit `close` (the peer cannot answer the close frame),+ // so detach it and reconnect now instead of waiting for the TCP timeout.+ this.retiredSockets.add(ws);+ this.ws = null;+ this.stopPing();+ ws.terminate();+ this.scheduleReconnect();+ return;+ }+ this.awaitingPong = true;+ try {+ ws.ping();+ } catch (err) {+ this.log('Ping failed: %O', err);+ }+ }, this.pingIntervalMs);+ }++ private stopPing(): void {+ if (this.pingTimer) clearInterval(this.pingTimer);+ this.pingTimer = null;+ this.awaitingPong = false;+ }++ // ---------- Frames ----------++ private handleFrame(ws: WebSocket, raw: string): void {+ let frame: DingTalkStreamFrame;+ try {+ frame = JSON.parse(raw);+ } catch {+ this.log('Failed to parse stream frame: %s', raw);+ return;+ }++ const topic = frame.headers?.topic;+ const messageId = frame.headers?.messageId;++ switch (frame.type) {+ case DINGTALK_STREAM_FRAME_TYPES.SYSTEM: {+ if (topic === DINGTALK_STREAM_TOPICS.PING) {+ // Echo `opaque` back unchanged.+ this.ack(ws, messageId, 200, frame.data);+ } else if (topic === DINGTALK_STREAM_TOPICS.DISCONNECT) {+ this.log('Server requested disconnect: %s', frame.data);+ // The server drops TCP ~10s later; reconnect right away instead.+ ws.close(4000, 'Server disconnect');+ } else {+ this.log('System frame: %s', topic);+ }+ return;+ }++ case DINGTALK_STREAM_FRAME_TYPES.CALLBACK: {+ if (topic !== DINGTALK_STREAM_TOPICS.BOT_MESSAGE) {+ this.ack(ws, messageId, 404, JSON.stringify({ response: null }), 'topic not supported');+ return;+ }+ // Robot messages are fire-and-forget: ACK immediately, never block on the agent.+ this.ack(ws, messageId, 200, JSON.stringify({ response: null }));+ this.forwardCallback(frame.data, messageId);+ return;+ }++ case DINGTALK_STREAM_FRAME_TYPES.EVENT: {+ this.ack(ws, messageId, 200, JSON.stringify({ message: 'ignored', status: 'SUCCESS' }));+ return;+ }++ default: {+ this.log('Unknown frame type: %s', (frame as { type?: string }).type);+ }+ }+ }++ private ack(+ ws: WebSocket,+ messageId: string | undefined,+ code: number,+ data: string,+ message = 'OK',+ ): void {+ if (!messageId || ws.readyState !== WebSocket.OPEN) return;+ const ack: DingTalkStreamAck = {+ code,+ data,+ headers: { contentType: 'application/json', messageId },+ message,+ };+ ws.send(JSON.stringify(ack));+ }++ private forwardCallback(data: string, messageId?: string): void {+ const timestamp = String(Date.now());+ fetch(this.options.webhookUrl, {+ body: data,+ headers: {+ 'Content-Type': 'application/json',+ 'sign': signCallback(timestamp, this.options.clientSecret),+ 'timestamp': timestamp,+ },+ method: 'POST',+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS),+ }).catch((err) => {+ this.log('Failed to forward callback %s to webhook: %O', messageId, err);+ });+ }+}diff --git a/packages/chat-adapter-dingtalk/src/index.ts b/packages/chat-adapter-dingtalk/src/index.tsnew file mode 100644index 00000000000..1a124e44ac7--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/index.ts@@ -0,0 +1,38 @@+export { createDingTalkAdapter, DingTalkAdapter } from './adapter';+export type { DingTalkErrorKind } from './api';+export {+ classifyDingTalkError,+ DINGTALK_API_BASE_URL,+ DingTalkApiClient,+ DingTalkApiError,+ MAX_MSG_PARAM_TEXT_BYTES,+ truncateUtf8,+} from './api';+export { signCallback, verifyCallbackSignature } from './crypto';+export { DingTalkFormatConverter } from './format-converter';+export type { DingTalkGatewayOptions, GatewayLogger } from './gateway';+export { DEFAULT_STREAM_SUBSCRIPTIONS, DingTalkStreamConnection } from './gateway';+export type {+ DingTalkAccessTokenResponse,+ DingTalkAdapterConfig,+ DingTalkApiErrorBody,+ DingTalkAtUser,+ DingTalkBatchSendResponse,+ DingTalkConnectionOpenResponse,+ DingTalkGroupSendResponse,+ DingTalkInboundMsgType,+ DingTalkMessageContent,+ DingTalkOutboundMessage,+ DingTalkRawMessage,+ DingTalkRichTextItem,+ DingTalkStreamAck,+ DingTalkStreamFrame,+ DingTalkStreamSubscription,+ DingTalkThreadId,+} from './types';+export {+ DINGTALK_CONVERSATION_TYPE,+ DINGTALK_MSG_KEYS,+ DINGTALK_STREAM_FRAME_TYPES,+ DINGTALK_STREAM_TOPICS,+} from './types';diff --git a/packages/chat-adapter-dingtalk/src/types.ts b/packages/chat-adapter-dingtalk/src/types.tsnew file mode 100644index 00000000000..318860b14de--- /dev/null+++ b/packages/chat-adapter-dingtalk/src/types.ts@@ -0,0 +1,200 @@+// ---- Adapter config ----++export interface DingTalkAdapterConfig {+ /** Client ID (formerly AppKey) of the internal app */+ clientId: string;+ /** Client Secret (formerly AppSecret) of the internal app */+ clientSecret: string;+ /**+ * Robot code used by the robot send APIs. For an internal-app robot it is the+ * same value as the Client ID, which is the default.+ */+ robotCode?: string;+}++/**+ * Thread identity.+ *+ * - `single`: one-on-one chat, `id` is the sender's `senderStaffId` (the+ * recipient used by `oToMessages/batchSend`).+ * - `group`: group chat, `id` is the `openConversationId` (callback+ * `conversationId`, the target used by `groupMessages/send`).+ */+export interface DingTalkThreadId {+ id: string;+ type: 'single' | 'group';+}++// ---- Stream mode (WebSocket) ----++export const DINGTALK_STREAM_TOPICS = {+ /** Robot message callback */+ BOT_MESSAGE: '/v1.0/im/bot/messages/get',+ /** System: graceful close, server drops TCP ~10s later */+ DISCONNECT: 'disconnect',+ /** System: health check, echo `opaque` back */+ PING: 'ping',+} as const;++export const DINGTALK_STREAM_FRAME_TYPES = {+ CALLBACK: 'CALLBACK',+ EVENT: 'EVENT',+ SYSTEM: 'SYSTEM',+} as const;++export interface DingTalkStreamSubscription {+ topic: string;+ type: 'CALLBACK' | 'EVENT';+}++export interface DingTalkConnectionOpenRequest {+ clientId: string;+ clientSecret: string;+ localIp?: string;+ subscriptions: DingTalkStreamSubscription[];+ ua?: string;+}++export interface DingTalkConnectionOpenResponse {+ /** WebSocket endpoint (wss://...) */+ endpoint: string;+ /** One-shot ticket, valid for 90 seconds */+ ticket: string;+}++export interface DingTalkStreamFrameHeaders {+ [key: string]: string | undefined;+ contentType?: string;+ messageId: string;+ time?: string;+ topic: string;+}++/** A frame pushed by the server over the Stream WebSocket */+export interface DingTalkStreamFrame {+ /** JSON string; shape depends on the topic */+ data: string;+ headers: DingTalkStreamFrameHeaders;+ specVersion?: string;+ type: 'SYSTEM' | 'EVENT' | 'CALLBACK';+}++/** ACK frame sent back by the client */+export interface DingTalkStreamAck {+ code: number;+ /** JSON string */+ data: string;+ headers: { contentType: 'application/json'; messageId: string };+ message: string;+}++// ---- Robot message callback ----++export const DINGTALK_CONVERSATION_TYPE = {+ GROUP: '2',+ SINGLE: '1',+} as const;++export interface DingTalkAtUser {+ dingtalkId: string;+ staffId?: string;+}++export interface DingTalkRichTextItem {+ downloadCode?: string;+ pictureDownloadCode?: string;+ text?: string;+ type?: string;+}++export interface DingTalkMessageContent {+ downloadCode?: string;+ /** audio / video duration */+ duration?: number | string;+ /** file name (msgtype=file) */+ fileName?: string;+ pictureDownloadCode?: string;+ /** speech-to-text result (msgtype=audio) */+ recognition?: string;+ richText?: DingTalkRichTextItem[];+ videoType?: string;+}++export type DingTalkInboundMsgType = 'text' | 'richText' | 'picture' | 'audio' | 'video' | 'file';++/**+ * Robot message callback payload (`data` of the `/v1.0/im/bot/messages/get`+ * frame, or the body of an HTTP-mode callback).+ */+export interface DingTalkRawMessage {+ atUsers?: DingTalkAtUser[];+ chatbotCorpId?: string;+ chatbotUserId?: string;+ content?: DingTalkMessageContent;+ conversationId: string;+ conversationTitle?: string;+ /** '1' = single chat, '2' = group chat */+ conversationType: string;+ createAt?: number;+ isAdmin?: boolean;+ isInAtList?: boolean;+ msgId: string;+ msgtype: string;+ robotCode?: string;+ senderCorpId?: string;+ senderId: string;+ senderNick?: string;+ /** Present for members of the robot's organization */+ senderStaffId?: string;+ sessionWebhook?: string;+ /** Unix ms */+ sessionWebhookExpiredTime?: number;+ text?: { content: string };+}++// ---- OpenAPI ----++export interface DingTalkAccessTokenResponse {+ accessToken: string;+ /** seconds */+ expireIn: number;+}++/** Robot message template keys (`msgKey`) */+export const DINGTALK_MSG_KEYS = {+ IMAGE: 'sampleImageMsg',+ MARKDOWN: 'sampleMarkdown',+ TEXT: 'sampleText',+} as const;++export type DingTalkOutboundMessage =+ | { msgKey: 'sampleText'; msgParam: { content: string } }+ | { msgKey: 'sampleMarkdown'; msgParam: { text: string; title: string } }+ | { msgKey: 'sampleImageMsg'; msgParam: { photoURL: string } };++export interface DingTalkBatchSendResponse {+ flowControlledStaffIdList?: string[];+ invalidStaffIdList?: string[];+ processQueryKey: string;+}++export interface DingTalkGroupSendResponse {+ processQueryKey: string;+}++export interface DingTalkFileDownloadResponse {+ downloadUrl: string;+}++/** Error body of the v1.0 OpenAPI */+export interface DingTalkApiErrorBody {+ code?: string;+ message?: string;+ requestid?: string;+}++/** Response of a sessionWebhook POST */+export interface DingTalkSessionWebhookResponse {+ errcode?: number;+ errmsg?: string;+}diff --git a/packages/chat-adapter-dingtalk/tsconfig.json b/packages/chat-adapter-dingtalk/tsconfig.jsonnew file mode 100644index 00000000000..d01dac0a552--- /dev/null+++ b/packages/chat-adapter-dingtalk/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "lib": ["ES2022"],+ "types": ["node"]+ },+ "exclude": ["node_modules", "dist"],+ "include": ["src/**/*"]+}diff --git a/packages/chat-adapter-dingtalk/tsup.config.ts b/packages/chat-adapter-dingtalk/tsup.config.tsnew file mode 100644index 00000000000..d4c69d1df67--- /dev/null+++ b/packages/chat-adapter-dingtalk/tsup.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ dts: true,+ entry: ['src/index.ts'],+ format: ['esm'],+ sourcemap: true,+});diff --git a/packages/chat-adapter-dingtalk/vitest.config.mts b/packages/chat-adapter-dingtalk/vitest.config.mtsnew file mode 100644index 00000000000..d28fa984095--- /dev/null+++ b/packages/chat-adapter-dingtalk/vitest.config.mts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ coverage: {},+ environment: 'node',+ },+});diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex eee0948b3b1..36695a64a26 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -88,6 +88,21 @@ export default {'channel.quickSetup.wecom.credentials.title': 'Copy the BotID and Secret','channel.quickSetup.wecom.credentials.desc':"Find them in the bot's API settings. A bot can be connected to only one place at a time.",+ 'channel.quickSetup.dingtalk.create.title': 'Create an internal app',+ 'channel.quickSetup.dingtalk.create.desc':+ 'In the DingTalk developer console, create an internal app, then copy the Client ID and Client Secret from Credentials & Basic Info.',+ 'channel.quickSetup.dingtalk.robot.title': 'Add the robot and choose Stream mode',+ 'channel.quickSetup.dingtalk.robot.desc':+ 'Under App Capabilities, add Robot, fill in its details and set the message receiving mode to Stream mode.',+ 'channel.quickSetup.dingtalk.robotWebhook.title': 'Add the robot and choose HTTP callback',+ 'channel.quickSetup.dingtalk.robotWebhook.desc':+ 'Under App Capabilities, add Robot, fill in its details, set the message receiving mode to HTTP callback, and paste the Webhook URL shown here after saving as the message receiving address.',+ 'channel.quickSetup.dingtalk.permissions.title': 'Grant the robot send permission',+ 'channel.quickSetup.dingtalk.permissions.desc':+ 'Under Permissions, request qyapi_robot_sendmsg so the bot can reply in single and group chats.',+ 'channel.quickSetup.dingtalk.publish.title': 'Publish a version',+ 'channel.quickSetup.dingtalk.publish.desc':+ 'Under Version Management, publish and choose who can see the robot. Internal apps go live without review.','channel.quickSetup.line.account.title': 'Create a LINE Official Account','channel.quickSetup.line.account.desc':'Sign in with your LINE Business ID and create the account the bot speaks as.',@@ -157,6 +172,8 @@ export default {'channel.home.title': 'Chat with <avatar/>{{name}} on Your Favorite Chat App','channel.platform.default.description':'Let people reach this agent from {{name}} without switching apps—ideal for anyone who wants help close at hand.',+ 'channel.platform.dingtalk.description':+ 'Answer questions and assist work in single chats and group @-mentions—ideal for teams that collaborate in DingTalk.','channel.platform.discord.description':'Support communities in servers and DMs—ideal for moderators, member support, and always-on help.','channel.platform.feishu.description':@@ -223,9 +240,25 @@ export default {'The bot session has expired. Save the bot again to reconnect it.','channel.connectionError.upstream_unavailable':'The platform service is temporarily unavailable. LobeHub will try again later.',+ 'channel.connectionError.webhook_mode_required':+ 'This deployment can only connect this platform in Webhook mode. Switch the connection mode to Webhook and update the callback address in the platform console.','channel.endpointUrl': 'Webhook URL','channel.endpointUrlHint':'Please copy this URL and paste it into the <bold>{{fieldName}}</bold> field in the {{name}} Developer Portal.',+ 'channel.dingtalk.clientId': 'Client ID (AppKey)',+ 'channel.dingtalk.clientIdHint':+ 'From the DingTalk developer console → your internal app → Credentials & Basic Info. Formerly called AppKey.',+ 'channel.dingtalk.clientIdPlaceholder': 'e.g. dingxxxxxxxxxxxxxxxx',+ 'channel.dingtalk.clientSecret': 'Client Secret (AppSecret)',+ 'channel.dingtalk.clientSecretHint':+ 'Shown next to the Client ID. Formerly called AppSecret. It will be encrypted and stored securely.',+ 'channel.dingtalk.description':+ 'Connect this agent to a DingTalk robot for single chats and group @-mentions.',+ 'channel.dingtalk.identifierInvalid':+ 'Use only letters, digits, hyphens and underscores. Copy the value from the DingTalk developer console without spaces.',+ 'channel.dingtalk.robotCode': 'RobotCode',+ 'channel.dingtalk.robotCodeHint':+ "Optional. An internal-app robot's RobotCode is its Client ID, which is used when this is blank. Fill it in only if the robot page shows a different code.",'channel.feishu.description': 'Connect this agent to Feishu for private and group chats.','channel.feishu.webhookMigrationTitle': 'Consider migrating to WebSocket mode','channel.feishu.webhookMigrationDesc':@@ -815,6 +848,8 @@ export default {'channel.userIdMissingDesc':"Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in on the Access tab.",'channel.userIdMissingTitle': 'Add your platform User ID',+ 'channel.userIdHint.dingtalk':+ 'Your DingTalk user ID (staff ID). Find it in the DingTalk admin console \u2192 Contacts \u2192 member details, or send /whoami to the bot in a direct message.','channel.userIdHint.discord':'Enable Developer Mode (Settings → Advanced), then right-click your avatar → Copy User ID.','channel.userIdHint.feishu':diff --git a/src/features/AgentChannel/PlatformCard.tsx b/src/features/AgentChannel/PlatformCard.tsxindex 75261551aa7..cdb8511e1d4 100644--- a/src/features/AgentChannel/PlatformCard.tsx+++ b/src/features/AgentChannel/PlatformCard.tsx@@ -70,6 +70,9 @@ const PlatformCard = memo<PlatformCardProps>(({ onSelect, platform, status }) =>const getPlatformDescription = (id: string, name: string) => {switch (id) {+ case 'dingtalk': {+ return t('channel.platform.dingtalk.description');+ }case 'discord': {return t('channel.platform.discord.description');}diff --git a/src/features/AgentChannel/const.test.ts b/src/features/AgentChannel/const.test.tsindex 1a3251a6b22..8a326f12751 100644--- a/src/features/AgentChannel/const.test.ts+++ b/src/features/AgentChannel/const.test.ts@@ -10,9 +10,16 @@ describe('getPlatformIcon', () => {expect('Color' in Icons.WeCom).toBe(true);});+ it('resolves DingTalk by platform id and by display name', () => {+ expect(Icons.DingTalk).toBeDefined();+ expect(getPlatformIcon('dingtalk')).toBe(Icons.DingTalk);+ expect(getPlatformIcon('DingTalk')).toBe(Icons.DingTalk);+ });+it('keeps resolving the other platforms from @lobehub/ui/icons', () => {expect(getPlatformIcon('wechat')).toBe(Icons.WeChat);expect(getPlatformIcon('feishu')).toBe(Icons.Lark);+ expect(getPlatformIcon('qq')).toBe(Icons.QQ);expect(getPlatformIcon('Discord')).toBe(Icons.Discord);expect(getPlatformIcon('unknown-platform')).toBeUndefined();});diff --git a/src/features/AgentChannel/const.ts b/src/features/AgentChannel/const.tsindex e6a769c1f62..0112c3581ba 100644--- a/src/features/AgentChannel/const.ts+++ b/src/features/AgentChannel/const.ts@@ -5,6 +5,7 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platfor/** Known icon names from @lobehub/ui/icons that correspond to chat platforms. */const ICON_NAMES = [+ 'DingTalk','Discord','GoogleChat','IMessage',diff --git a/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx b/src/features/AgentChannel/quickSetup/QuickSetupSection.tsxindex 679981e8d8c..8d743766857 100644--- a/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx+++ b/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx@@ -55,9 +55,10 @@ const QuickSetupSection = memo<QuickSetupSectionProps>(}) => {const { t } = useTranslation('agent');const applicationId = useWatch(form, (values) => values?.applicationId as string | undefined);+ const connectionMode = useWatch(form, 'settings.connectionMode') as string | undefined;const guide = useMemo(- () => getSetupGuide(platformId, { applicationId, appName }),- [platformId, applicationId, appName],+ () => getSetupGuide(platformId, { applicationId, appName, connectionMode }),+ [platformId, applicationId, appName, connectionMode],);// Platforms with a scan flow keep the manual steps one click away; the rest// have no other way in, so the steps are open from the start.diff --git a/src/features/AgentChannel/quickSetup/guides.ts b/src/features/AgentChannel/quickSetup/guides.tsindex 09d4e094395..8e0ff8c006b 100644--- a/src/features/AgentChannel/quickSetup/guides.ts+++ b/src/features/AgentChannel/quickSetup/guides.ts@@ -3,6 +3,7 @@ import {buildDiscordInviteUrl,buildSlackAppPageUrl,buildSlackCreateAppUrl,+ DINGTALK_CONSOLE_URL,DISCORD_DEVELOPER_PORTAL_URL,FEISHU_CONSOLE_URL,LINE_ACCOUNT_ENTRY_URL,@@ -57,6 +58,8 @@ export interface SetupGuideContext {/** Application ID already in the form, unlocking deep links into that app. */applicationId?: string;appName: string;+ /** Connection mode selected in the form, for steps that differ between modes. */+ connectionMode?: string;}/**@@ -65,7 +68,7 @@ export interface SetupGuideContext {*/export const getSetupGuide = (platformId: string,- { applicationId, appDescription, appName }: SetupGuideContext,+ { applicationId, appDescription, appName, connectionMode }: SetupGuideContext,): SetupGuide | undefined => {const appId = applicationId?.trim() || undefined;@@ -164,6 +167,26 @@ export const getSetupGuide = (],};}+ case 'dingtalk': {+ // The robot, its receiving mode and the send permission only take effect once a+ // version is published. In Stream mode the connection opens on save, so the whole+ // console setup comes first; in webhook mode the save is what produces the+ // callback URL the robot step asks for, so those steps follow it.+ const beforeConnect = connectionMode !== 'webhook';+ return {+ guide: 'dingtalk',+ steps: [+ {+ key: 'create',+ fields: ['applicationId', 'clientSecret'],+ link: { href: DINGTALK_CONSOLE_URL, label: 'openConsole' },+ },+ { beforeConnect, key: beforeConnect ? 'robot' : 'robotWebhook' },+ { beforeConnect, key: 'permissions' },+ { beforeConnect, key: 'publish' },+ ],+ };+ }case 'line': {return {guide: 'line',diff --git a/src/features/AgentChannel/quickSetup/links.ts b/src/features/AgentChannel/quickSetup/links.tsindex a41a6c3bb06..bb074c2819b 100644--- a/src/features/AgentChannel/quickSetup/links.ts+++ b/src/features/AgentChannel/quickSetup/links.ts@@ -10,6 +10,8 @@ export const FEISHU_CONSOLE_URL = {feishu: 'https://open.feishu.cn/app',lark: 'https://open.larksuite.com/app',} as const;+// Internal apps list; the robot is a capability added to an internal app.+export const DINGTALK_CONSOLE_URL = 'https://open-dev.dingtalk.com/fe/app#/corp/app';export const QQ_BOT_CONSOLE_URL = 'https://q.qq.com/qqbot/';/** WeCom admin console; AI bots live under 智能专区 → 智能机器人. */export const WECOM_ADMIN_CONSOLE_URL = 'https://work.weixin.qq.com/wework_admin/frame';diff --git a/src/features/AgentChannel/quickSetup/quickSetup.test.ts b/src/features/AgentChannel/quickSetup/quickSetup.test.tsindex ebfdb968141..bba4bc35bb6 100644--- a/src/features/AgentChannel/quickSetup/quickSetup.test.ts+++ b/src/features/AgentChannel/quickSetup/quickSetup.test.ts@@ -1,10 +1,13 @@import { describe, expect, it } from 'vitest';+import defaultAgentLocale from '@/locales/default/agent';+import { connectStepIndex, getInlineFieldKeys, getSetupGuide } from './guides';import {buildDiscordInviteUrl,buildSlackCreateAppUrl,buildSlackManifest,+ DINGTALK_CONSOLE_URL,DISCORD_BOT_PERMISSIONS,MAX_TRANSIENT_POLL_FAILURES,REGISTRATION_NAME_MAX_LENGTH,@@ -164,6 +167,58 @@ describe('getSetupGuide', () => {expect(guide.steps[1].link?.href).toBe('https://api.slack.com/apps/A1/oauth');});+ it('walks DingTalk from an internal app to a published Stream-mode robot', () => {+ const guide = getSetupGuide('dingtalk', { applicationId: 'dingabc', appName: 'Moss' })!;++ expect(guide.guide).toBe('dingtalk');+ expect(guide.scanToCreate).toBeUndefined();+ expect(guide.steps.map((step) => step.key)).toEqual([+ 'create',+ 'robot',+ 'permissions',+ 'publish',+ ]);+ // The console cannot be deep-linked by Client ID, so the link never depends on it.+ expect(guide.steps[0].link).toEqual({ href: DINGTALK_CONSOLE_URL, label: 'openConsole' });+ expect(DINGTALK_CONSOLE_URL).toMatch(/^https:\/\/open-dev\.dingtalk\.com\//);+ });++ it('finishes the DingTalk console setup before connecting in Stream mode only', () => {+ const steps = (connectionMode: string) =>+ getSetupGuide('dingtalk', { appName: 'Moss', connectionMode })!.steps;++ // Stream mode connects on save, so robot, permission and publish come first.+ expect(connectStepIndex(steps('websocket'))).toBe(steps('websocket').length);+ // Webhook mode needs the save to produce the callback URL the robot step uses.+ expect(connectStepIndex(steps('webhook'))).toBe(1);+ });++ it('tells DingTalk webhook bots to configure HTTP callback, not Stream mode', () => {+ const stepKeys = (connectionMode: string) =>+ getSetupGuide('dingtalk', { appName: 'Moss', connectionMode })!.steps.map((step) => step.key);++ expect(stepKeys('webhook')).toContain('robotWebhook');+ expect(stepKeys('webhook')).not.toContain('robot');+ expect(stepKeys('websocket')).toContain('robot');+ expect(defaultAgentLocale['channel.quickSetup.dingtalk.robotWebhook.title']).toMatch(+ /HTTP callback/,+ );+ });++ it('asks for the DingTalk Client ID and Secret inline and leaves RobotCode optional', () => {+ expect([...getInlineFieldKeys('dingtalk')]).toEqual(['applicationId', 'clientSecret']);+ expect(getInlineFieldKeys('dingtalk').has('robotCode')).toBe(false);+ });++ it('has English copy for every DingTalk step', () => {+ for (const step of getSetupGuide('dingtalk', { appName: 'Moss' })!.steps) {+ for (const part of ['title', 'desc'] as const) {+ const key = `channel.quickSetup.dingtalk.${step.key}.${part}`;+ expect(defaultAgentLocale[key as keyof typeof defaultAgentLocale], key).toBeTruthy();+ }+ }+ });+it('has no guide for platforms with their own flow', () => {expect(getSetupGuide('wechat', { appName: 'Moss' })).toBeUndefined();});@@ -186,6 +241,7 @@ describe('getSetupGuide', () => {'feishu','lark','wecom',+ 'dingtalk',]) {const guide = getSetupGuide(platform, { appName: 'Moss' })!;const keys = guide.steps.flatMap((step) => step.fields ?? []);@@ -219,6 +275,8 @@ describe('getSetupGuide', () => {expect(at('discord')).toEqual(['create', 'credentials', 'bot', 'intent', 'invite', 'connect']);expect(at('telegram')).toEqual(['botfather', 'token', 'connect', 'privacy']);expect(at('line')).toEqual(['account', 'messagingApi', 'credentials', 'connect', 'webhook']);+ // Stream mode connects on save, so the DingTalk console setup comes first.+ expect(at('dingtalk')).toEqual(['create', 'robot', 'permissions', 'publish', 'connect']);expect(connectStepIndex([{ key: 'only' }])).toBe(1);expect(connectStepIndex([diff --git a/src/features/AgentTopicManager/utils.test.ts b/src/features/AgentTopicManager/utils.test.tsindex eb110d7c8af..5c403daee57 100644--- a/src/features/AgentTopicManager/utils.test.ts+++ b/src/features/AgentTopicManager/utils.test.ts@@ -129,6 +129,7 @@ describe('AgentTopicManager utils', () => {it('exposes human-readable platform names', () => {expect(getBotPlatformName('discord')).toBe('Discord');expect(getBotPlatformName('feishu')).toBe('Feishu');+ expect(getBotPlatformName('dingtalk')).toBe('DingTalk');expect(getBotPlatformName('unknown-platform')).toBe('unknown-platform');});});diff --git a/src/features/AgentTopicManager/utils.ts b/src/features/AgentTopicManager/utils.tsindex be3dd8fa472..4cd9a98f7ce 100644--- a/src/features/AgentTopicManager/utils.ts+++ b/src/features/AgentTopicManager/utils.ts@@ -158,6 +158,7 @@ export const getProjectLabel = (topic: ChatTopic): string | undefined => {/** Client-side platform display names (server `PlatformDefinition.name`). */const PLATFORM_DISPLAY_NAMES: Record<string, string> = {+ dingtalk: 'DingTalk',discord: 'Discord',feishu: 'Feishu',googlechat: 'Google Chat',