Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(im): add personal DingTalk bot connector
DavidShen81dfc60df848
diff --git a/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.ts b/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.tsnew file mode 100644index 0000000000..edf19e9fad--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/__tests__/interaction.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, vi } from 'vitest';+import type { DingTalkIM } from '@cindy/im';++import { __testing, handleDingTalkTextInteraction } from '../interaction';++describe('dingtalk text interactions', () => {+ it('parses explicit allow and deny replies', () => {+ const request = {+ kind: 'permission' as const,+ requestId: 'request-1',+ toolName: 'shell_command',+ input: {},+ };+ expect(__testing.parseInteractionReply(request, '允许')).toEqual({+ kind: 'permission',+ behavior: 'allow',+ });+ expect(__testing.parseInteractionReply(request, '拒绝')).toEqual({+ kind: 'permission',+ behavior: 'deny',+ reason: 'dingtalk_user_denied',+ });+ });++ it('maps a numbered answer to the matching option label', () => {+ const request = {+ kind: 'ask_user_question' as const,+ requestId: 'request-2',+ questions: [+ {+ question: '选择方向',+ options: [{ label: 'A' }, { label: 'B' }],+ },+ ],+ };+ expect(__testing.parseInteractionReply(request, '2')).toEqual({+ kind: 'ask_user_question',+ answers: { 选择方向: 'B' },+ });+ });++ it('asks multiple questions one at a time', async () => {+ const replies = ['2', 'custom'];+ const requestTextReply = vi.fn(+ async <T>(_userId: string, _prompt: string, parse: (text: string) => T | null) =>+ parse(replies.shift() ?? '') as T,+ );+ const im = { requestTextReply } as unknown as DingTalkIM;+ const request = {+ kind: 'ask_user_question' as const,+ requestId: 'request-3',+ questions: [+ { question: '方向', options: [{ label: 'A' }, { label: 'B' }] },+ { question: '备注' },+ ],+ };++ await expect(handleDingTalkTextInteraction(im, 'owner-1', request)).resolves.toEqual({+ kind: 'ask_user_question',+ answers: { 方向: 'B', 备注: 'custom' },+ });+ expect(requestTextReply).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.ts b/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.tsnew file mode 100644index 0000000000..fe956286b2--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/__tests__/permissionPolicy.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++import { createDingTalkTurnPermissionPolicy } from '../permissionPolicy';++describe('dingtalk turn permission policy', () => {+ it('forces confirmation for destructive and opaque writes', () => {+ const policy = createDingTalkTurnPermissionPolicy('message-1');+ expect(policy.origin).toEqual({+ kind: 'im',+ channel: 'dingtalk',+ taskId: 'message-1',+ });+ expect(policy.forceConfirmToolCall?.('file_change', {})).toBe(true);+ expect(policy.forceConfirmToolCall?.('permissions', {})).toBe(true);+ });+});diff --git a/apps/desktop/src/main/im/dingtalk/adapter.ts b/apps/desktop/src/main/im/dingtalk/adapter.tsnew file mode 100644index 0000000000..118b0791f6--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/adapter.ts@@ -0,0 +1,75 @@+import fs from 'node:fs';+import type { DingTalkIM, RichChannelIM } from '@cindy/im';+import { decodeDingTalkLaneUserId } from '@cindy/im';++import type { ImChannelAdapter, ImOrchestratorConfig } from '../shared/types';+import { ownerScopedImUserDataPath } from '../ownerScopedStorage';+import { handleDingTalkTextInteraction } from './interaction';+import { createDingTalkTurnPermissionPolicy } from './permissionPolicy';+import { ui } from './uiText';++function ensureWorkingDir(appKey: string): string {+ const safeKey = appKey.replace(/[^a-zA-Z0-9_-]/g, '-').slice(-64) || 'bot';+ const dir = ownerScopedImUserDataPath('im-working-dir', `dingtalk-${safeKey}`);+ fs.mkdirSync(dir, { recursive: true });+ return dir;+}++function sessionSafeUserId(userId: string): string {+ return userId.replace(/[^a-zA-Z0-9_-]/g, '-');+}++function sanitizeSpeaker(value: string): string {+ // eslint-disable-next-line no-control-regex+ return value+ .replace(/[\u0000-\u001f\u007f\u200b]/g, ' ')+ .trim()+ .slice(0, 64);+}++export function buildDingTalkAdapter(+ dingtalkIm: DingTalkIM,+ config: ImOrchestratorConfig,+): ImChannelAdapter {+ return {+ channel: 'dingtalk',+ // The shared card-action subscription still expects the rich interface.+ // Normal turn output is discriminated below and never calls card methods.+ im: dingtalkIm as RichChannelIM,+ output: {+ kind: 'chunked-text',+ im: dingtalkIm,+ commitFinal: (output) => dingtalkIm.commitFinal(output),+ },+ config,+ ui,+ sessions: {+ source: 'dingtalk',+ sessionIdFor: (appKey, userId) =>+ `dingtalk_${sessionSafeUserId(appKey)}_${sessionSafeUserId(userId)}`,+ defaultTitle: (userId) =>+ decodeDingTalkLaneUserId(userId)+ ? `钉钉群聊 · ${userId.slice(-6)}`+ : `钉钉 · ${userId.slice(-6)}`,+ generatedTitlePrefix: '钉钉 · ',+ workspaceKind: 'dialogue',+ ensureWorkingDir,+ extraInsertColumns: (appKey, userId) => ({+ imBotContextId: appKey,+ imUserId: userId,+ }),+ },+ processingEmoji: '',+ buildVendorOptions: (userId) => ({ dingtalkChatId: userId, source: 'dingtalk' }),+ handleTextInteraction: (userId, request) =>+ handleDingTalkTextInteraction(dingtalkIm, userId, request),+ turnPermissionPolicyFor: (event) => createDingTalkTurnPermissionPolicy(event.messageId),+ prepareAgentTurnText: async (event) => {+ if (!event.speaker) return null;+ const speaker = sanitizeSpeaker(event.speaker.name);+ return {+ agentText: `[发言人] ${speaker} · id:${event.speaker.id}${event.speaker.isOwner ? ' · 主人' : ''}\n${event.text}`,+ };+ },+ };+}diff --git a/apps/desktop/src/main/im/dingtalk/index.ts b/apps/desktop/src/main/im/dingtalk/index.tsnew file mode 100644index 0000000000..fddda35d63--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/index.ts@@ -0,0 +1,12 @@+import type { DingTalkIM } from '@cindy/im';++import { createImOrchestrator } from '../shared/orchestrator';+import type { ImOrchestratorConfig } from '../shared/types';+import { buildDingTalkAdapter } from './adapter';++export function wireDingTalkOrchestrator(+ dingtalkIm: DingTalkIM,+ config: ImOrchestratorConfig,+): void {+ createImOrchestrator(buildDingTalkAdapter(dingtalkIm, config));+}diff --git a/apps/desktop/src/main/im/dingtalk/interaction.ts b/apps/desktop/src/main/im/dingtalk/interaction.tsnew file mode 100644index 0000000000..1656c938a4--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/interaction.ts@@ -0,0 +1,116 @@+import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';+import type { DingTalkIM } from '@cindy/im';++export function handleDingTalkTextInteraction(+ im: DingTalkIM,+ userId: string,+ request: InteractionRequest,+): Promise<InteractionDecision> {+ if (request.kind === 'ask_user_question') {+ return answerQuestions(im, userId, request);+ }+ return im.requestTextReply(userId, formatInteractionPrompt(request), (text) =>+ parseInteractionReply(request, text),+ );+}++async function answerQuestions(+ im: DingTalkIM,+ userId: string,+ request: Extract<InteractionRequest, { kind: 'ask_user_question' }>,+): Promise<InteractionDecision> {+ const answers: Record<string, string> = {};+ for (const [index, question] of request.questions.entries()) {+ answers[question.question] = await im.requestTextReply(+ userId,+ formatQuestionPrompt(question, index, request.questions.length),+ (text) => parseQuestionAnswer(question, text),+ );+ }+ return { kind: 'ask_user_question', answers };+}++function formatInteractionPrompt(request: InteractionRequest): string {+ if (request.kind === 'permission') {+ return [`需要确认操作:${request.toolName}`, '回复“允许”继续,或回复“拒绝”取消。'].join('\n');+ }+ if (request.kind === 'plan_review') {+ return ['计划已准备好。', '回复“批准”继续,或回复“拒绝”取消。'].join('\n');+ }+ const lines: string[] = ['需要你补充以下信息:'];+ request.questions.forEach((question, questionIndex) => {+ lines.push(`${questionIndex + 1}. ${question.question}`);+ question.options?.forEach((option, optionIndex) => {+ lines.push(` ${optionIndex + 1}) ${option.label}`);+ });+ });+ lines.push('请直接回复选项序号或你的答案。');+ return lines.join('\n');+}++function formatQuestionPrompt(+ question: Extract<InteractionRequest, { kind: 'ask_user_question' }>['questions'][number],+ index: number,+ total: number,+): string {+ const lines = [`需要你补充信息(${index + 1}/${total}):${question.question}`];+ question.options?.forEach((option, optionIndex) => {+ lines.push(`${optionIndex + 1}) ${option.label}`);+ });+ lines.push('请回复选项序号或你的答案。');+ return lines.join('\n');+}++function parseQuestionAnswer(+ question: Extract<InteractionRequest, { kind: 'ask_user_question' }>['questions'][number],+ rawText: string,+): string | null {+ const text = rawText.trim();+ if (!text) return null;+ const index = Number.parseInt(text, 10);+ const option = Number.isInteger(index) && index >= 1 ? question.options?.[index - 1] : undefined;+ return option?.label ?? text;+}++function parseInteractionReply(+ request: InteractionRequest,+ rawText: string,+): InteractionDecision | null {+ const text = rawText.trim();+ if (!text) return null;+ const normalized = text.toLowerCase();+ if (request.kind === 'permission') {+ if (['允许', '同意', '确认', '继续', 'allow', 'yes', 'y'].includes(normalized)) {+ return { kind: 'permission', behavior: 'allow' };+ }+ if (['拒绝', '取消', 'deny', 'no', 'n'].includes(normalized)) {+ return { kind: 'permission', behavior: 'deny', reason: 'dingtalk_user_denied' };+ }+ return null;+ }+ if (request.kind === 'plan_review') {+ if (['批准', '同意', '确认', '继续', 'approve', 'yes', 'y'].includes(normalized)) {+ return { kind: 'plan_review', behavior: 'allow' };+ }+ if (['拒绝', '取消', 'deny', 'no', 'n'].includes(normalized)) {+ return { kind: 'plan_review', behavior: 'deny', reason: 'dingtalk_user_denied' };+ }+ return null;+ }++ const answers: Record<string, string> = {};+ for (const question of request.questions) {+ const index = Number.parseInt(text, 10);+ const option =+ Number.isInteger(index) && index >= 1 ? question.options?.[index - 1] : undefined;+ answers[question.question] = option?.label ?? text;+ }+ return { kind: 'ask_user_question', answers };+}++export const __testing = {+ formatInteractionPrompt,+ formatQuestionPrompt,+ parseQuestionAnswer,+ parseInteractionReply,+};diff --git a/apps/desktop/src/main/im/dingtalk/permissionPolicy.ts b/apps/desktop/src/main/im/dingtalk/permissionPolicy.tsnew file mode 100644index 0000000000..7c280fe3b9--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/permissionPolicy.ts@@ -0,0 +1,42 @@+import type { TurnPermissionPolicy } from '@cindy/maker-core';++import { checkDestructiveToolCall } from '../../destructiveGuard';++function record(value: unknown): Record<string, unknown> | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ return value as Record<string, unknown>;+}++/**+ * Every remote DingTalk turn carries an explicit confirmation boundary for+ * destructive or opaque writes. Sessions configured with an incompatible+ * unattended permission mode fail closed in maker-core.+ */+export function createDingTalkTurnPermissionPolicy(taskId: string): TurnPermissionPolicy {+ return {+ origin: { kind: 'im', channel: 'dingtalk', taskId },+ confirmationSurface: 'channel',+ confirmationTimeoutMs: 30 * 60 * 1_000,+ forceConfirmToolCall(toolName, input) {+ const direct = checkDestructiveToolCall(toolName, record(input));+ if (direct.destructive) return true;++ const outer = record(input);+ const nested = record(outer?.toolParams);+ const innerName =+ typeof nested?.name === 'string'+ ? nested.name+ : typeof outer?.name === 'string'+ ? outer.name+ : null;+ if (+ innerName &&+ (checkDestructiveToolCall(innerName, nested ?? outer).destructive ||+ /(?:^|_)(?:merge|system_write|overwrite)(?:_|$)/i.test(innerName))+ ) {+ return true;+ }+ return toolName === 'file_change' || toolName === 'permissions';+ },+ };+}diff --git a/apps/desktop/src/main/im/dingtalk/uiText.ts b/apps/desktop/src/main/im/dingtalk/uiText.tsnew file mode 100644index 0000000000..a2febd0ba4--- /dev/null+++ b/apps/desktop/src/main/im/dingtalk/uiText.ts@@ -0,0 +1,24 @@+import type { ImUiTextPack } from '../shared/types';+import { telegramUiText } from '../telegram/uiText';++/**+ * Shared IM control copy is channel-neutral apart from a small number of+ * route labels. Keep the DingTalk pack derived at the composition boundary so+ * fixes to permissions, model selection, and takeover guidance stay aligned.+ */+export const ui = replaceChannelLabel(telegramUiText) as ImUiTextPack;++function replaceChannelLabel(value: unknown): unknown {+ if (typeof value === 'string') {+ return value.replaceAll('Telegram', '钉钉').replaceAll('TG', '钉钉');+ }+ if (typeof value === 'function') {+ return (...args: unknown[]) =>+ replaceChannelLabel((value as (...input: unknown[]) => unknown)(...args));+ }+ if (Array.isArray(value)) return value.map(replaceChannelLabel);+ if (!value || typeof value !== 'object') return value;+ return Object.fromEntries(+ Object.entries(value).map(([key, child]) => [key, replaceChannelLabel(child)]),+ );+}diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.tsindex 87222081dd..d7f480797e 100644--- a/apps/desktop/src/main/im/host.ts+++ b/apps/desktop/src/main/im/host.ts@@ -16,6 +16,7 @@ import { app, ipcMain, BrowserWindow, net, shell } from 'electron';import {createIM,createDiscordIM,+ createDingTalkIM,createFeishuIM,createTelegramIM,type IMHost,@@ -164,6 +165,9 @@ export const telegramIm = createTelegramIM(host, {}),),});+export const dingtalkIm = createDingTalkIM(host, {+ fetcher: (input, init) => net.fetch(input instanceof URL ? input.toString() : input, init),+});/*** Telegram 个人 bot 的行为/人格/群参与配置 IPC(设置卡数据通道)。* 必须由 bootstrap 显式调用(与 im.registerIpc() 同期) — 不能放模块顶层:@@ -266,4 +270,4 @@ wechatCompatibilityPolicy.subscribe((decision) => {log.warn('failed to apply personal WeChat compatibility policy');});});-export const im = createIM([feishuIm, discordIm, wechatIm, telegramIm]);+export const im = createIM([feishuIm, discordIm, wechatIm, telegramIm, dingtalkIm]);diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.tsindex 64a34d125f..90781fdb33 100644--- a/apps/desktop/src/main/im/index.ts+++ b/apps/desktop/src/main/im/index.ts@@ -59,10 +59,19 @@ import { and, eq, like, ne, sql } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current';import { sessions } from '../localDb/schema';-import { im, feishuIm, discordIm, telegramIm, wechatCompatibilityPolicy, wechatIm } from './host';+import {+ im,+ feishuIm,+ discordIm,+ telegramIm,+ dingtalkIm,+ wechatCompatibilityPolicy,+ wechatIm,+} from './host';import { wireFeishuOrchestrator, type FeishuOrchestratorConfig } from './feishu';import { wireDiscordOrchestrator } from './discord';import { wireTelegramOrchestrator } from './telegram';+import { wireDingTalkOrchestrator } from './dingtalk';import { wireWechatOrchestrator } from './wechat';import { resetTelegramGroupContextCursors } from './telegram/groupWindow';import { getImOrchestrator, listImOrchestrators } from './shared/orchestrator';@@ -89,7 +98,15 @@ import {writeWechatWorkingDir,} from './wechat/channelSettings';-export { registerTelegramBotConfigIpc, im, feishuIm, discordIm, telegramIm, wechatIm } from './host';+export {+ registerTelegramBotConfigIpc,+ im,+ feishuIm,+ discordIm,+ telegramIm,+ dingtalkIm,+ wechatIm,+} from './host';const log = createLogger('main:im');@@ -158,6 +175,13 @@ const TELEGRAM_CONFIG: ImOrchestratorConfig = {effortOverrides: IM_DEFAULT_EFFORT_OVERRIDES,};+const DINGTALK_CONFIG: ImOrchestratorConfig = {+ agentKind: IM_DEFAULT_SETTINGS.agentKind,+ defaultModel: IM_DEFAULT_SETTINGS.agents[IM_DEFAULT_SETTINGS.agentKind].model,+ defaultPermissionMode: 'auto',+ effortOverrides: IM_DEFAULT_EFFORT_OVERRIDES,+};+const WECHAT_CONFIG: ImOrchestratorConfig = {agentKind: IM_DEFAULT_SETTINGS.agentKind,defaultModel: IM_DEFAULT_SETTINGS.agents[IM_DEFAULT_SETTINGS.agentKind].model,@@ -183,6 +207,7 @@ export function startImOrchestrators(): void {wireFeishuOrchestrator(feishuIm, FEISHU_CONFIG);wireDiscordOrchestrator(discordIm, DISCORD_CONFIG);wireTelegramOrchestrator(telegramIm, TELEGRAM_CONFIG);+ wireDingTalkOrchestrator(dingtalkIm, DINGTALK_CONFIG);wireWechatOrchestrator(wechatIm, WECHAT_CONFIG);ipcMain.handle('wechatBot:get-state', (event) => {diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.tsindex 3202bdc3d3..17b46532da 100644--- a/apps/desktop/src/main/im/shared/types.ts+++ b/apps/desktop/src/main/im/shared/types.ts@@ -28,7 +28,7 @@ import type {import type { ChannelIM, ImOutputDriver, IMMessageEvent, IMUnsupportedEntry } from '@cindy/im';/** 渠道名 — 同时是 sessions.source 列值与 IdentityKey.channel 的值域。 */-export type ImChannelName = 'feishu' | 'slack' | 'discord' | 'wechat' | 'telegram';+export type ImChannelName = 'feishu' | 'slack' | 'discord' | 'wechat' | 'telegram' | 'dingtalk';/*** IM 编排层的产品默认配置(由 main/im/index.ts 产品接线层注入)。diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex 67e825d1df..5db948e2c9 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -27,6 +27,7 @@ const SESSION_SOURCES = ['telegram','discord','wechat',+ 'dingtalk','scheduler','learn','shared',diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex fd38b2be87..2226abaca8 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -386,6 +386,8 @@ const fanOutFeishuBotRegistrationStatus = createIpcFanOut('feishuBot:registratioconst fanOutDiscordBotStatusChange = createIpcFanOut('discordBot:status-change');// 个人 Telegram Bot:本机凭证模式(BotFather token 直连);同上只暴露 transport 状态。const fanOutTelegramBotStatusChange = createIpcFanOut('telegramBot:status-change');+const fanOutDingTalkBotStatusChange = createIpcFanOut('dingtalkBot:status-change');+const fanOutDingTalkBotOwnerChange = createIpcFanOut('dingtalkBot:owner-change');// Personal WeChat: main owns auth/polling and broadcasts a credential-free state snapshot.const fanOutWechatBotStateChange = createIpcFanOut('wechatBot:state-changed');const fanOutVoiceInputEvent = createIpcFanOut('voice-input:event');@@ -1599,6 +1601,50 @@ contextBridge.exposeInMainWorld('electronAPI', {onStatusChange: fanOutTelegramBotStatusChange,},+ // ── Personal DingTalk Bot (Settings → IM Bot → Personal) ──+ // Client Secret is only forwarded into main-process encrypted storage and is never returned.+ dingtalkBot: {+ getState: (): Promise<{+ status:+ | { kind: 'idle' }+ | { kind: 'connecting' }+ | { kind: 'connected'; appId: string }+ | { kind: 'conflict'; appId: string }+ | { kind: 'error'; reason: string };+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ }> => ipcRenderer.invoke('dingtalkBot:get-state'),+ save: (payload: {+ appKey: string;+ appSecret: string;+ }): Promise<{+ status:+ | { kind: 'idle' }+ | { kind: 'connecting' }+ | { kind: 'connected'; appId: string }+ | { kind: 'conflict'; appId: string }+ | { kind: 'error'; reason: string };+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ }> => ipcRenderer.invoke('dingtalkBot:save', payload),+ reconnect: (): Promise<{+ status:+ | { kind: 'idle' }+ | { kind: 'connecting' }+ | { kind: 'connected'; appId: string }+ | { kind: 'conflict'; appId: string }+ | { kind: 'error'; reason: string };+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ }> => ipcRenderer.invoke('dingtalkBot:reconnect'),+ clear: (): Promise<{ ok: true }> => ipcRenderer.invoke('dingtalkBot:clear'),+ onStatusChange: fanOutDingTalkBotStatusChange,+ onOwnerChange: fanOutDingTalkBotOwnerChange,+ },+// ── Personal WeChat (Settings → IM Bot → Personal) ──// Renderer receives state only. Authorization URLs and credentials never// cross preload; main opens the Tencent page in the system browser.diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.tsindex ab996c367e..9b1b83316c 100644--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts@@ -101,7 +101,7 @@ describe('automation-generated sessions', () => {});it('keeps scheduler sessions in the desktop-visible source contract', () => {- // feishu / slack / telegram / discord 四个 IM 渠道均进 desktop sidebar+ // 所有会生成本地会话的 IM 渠道均进入 desktop sidebar。// (feishu 2026-07-16 起以「对话」分组回归, 见 sessionSource.ts 注释)。expect(DESKTOP_VISIBLE_SESSION_SOURCES).toEqual(['desktop',@@ -110,6 +110,7 @@ describe('automation-generated sessions', () => {'telegram','discord','wechat',+ 'dingtalk','scheduler','learn','shared',@@ -118,6 +119,7 @@ describe('automation-generated sessions', () => {expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('feishu');expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('telegram');expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('discord');+ expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('dingtalk');expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('plugin');expect(normalizeSessionSource('desktop')).toBe('desktop');@@ -126,6 +128,7 @@ describe('automation-generated sessions', () => {expect(normalizeSessionSource('feishu')).toBe('feishu');expect(normalizeSessionSource('telegram')).toBe('telegram');expect(normalizeSessionSource('discord')).toBe('discord');+ expect(normalizeSessionSource('dingtalk')).toBe('dingtalk');expect(normalizeSessionSource('plugin')).toBe('plugin');expect(normalizeSessionSource(null)).toBe('desktop');expect(normalizeSessionSource('unknown')).toBe('desktop');diff --git a/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx b/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsxnew file mode 100644index 0000000000..ae6046d3af--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx@@ -0,0 +1,325 @@+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Loader2, Trash2 } from 'lucide-react';++import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { useDingTalkBot } from '@/hooks/useDingTalkBot';+import { cn } from '@/lib/utils';+import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelSettingsCard';+import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';++const DEVELOPER_PORTAL_URL = 'https://open-dev.dingtalk.com/';++const statusKey: Record<DingTalkBotTransportStatus['kind'], string> = {+ idle: 'settings.dingtalkBot.status.needsConfig',+ connecting: 'settings.dingtalkBot.status.connecting',+ connected: 'settings.dingtalkBot.status.connected',+ conflict: 'settings.dingtalkBot.status.connecting',+ error: 'settings.dingtalkBot.status.error',+};++function statusColor(status: DingTalkBotTransportStatus): string {+ if (status.kind === 'connected') return 'var(--settings-badge-connected)';+ if (status.kind === 'error') return 'var(--settings-badge-error)';+ if (status.kind === 'idle') return 'var(--settings-badge-needs-config)';+ return 'var(--settings-badge-saved)';+}++export function DingTalkBotSection({+ expanded,+ onToggle,+}: {+ expanded: boolean;+ onToggle: () => void;+}) {+ const bot = useDingTalkBot();+ const { confirm } = useConfirmDialog();+ const { t } = useTranslation();+ const [showSecret, setShowSecret] = useState(false);+ const [guideOpen, setGuideOpen] = useState(false);+ const [routeSummary, setRouteSummary] = useImChannelSettingsSummary('dingtalk');++ const guideSteps = useMemo(+ () => [1, 2, 3, 4].map((step) => t(`settings.dingtalkBot.guide.step${step}`)),+ [t],+ );++ const clear = useCallback(async () => {+ const confirmed = await confirm({+ title: t('settings.dingtalkBot.disconnectConfirm.title'),+ description: t('settings.dingtalkBot.disconnectConfirm.description'),+ confirmText: t('settings.dingtalkBot.disconnectConfirm.confirm'),+ cancelText: t('settings.dingtalkBot.disconnectConfirm.cancel'),+ });+ if (confirmed) await bot.clear();+ }, [bot, confirm, t]);++ const connected = bot.status.kind === 'connected';++ return (+ <ImChannelSettingsCard+ id="personal-im-dingtalk"+ title={t('settings.dingtalkBot.title')}+ description={t('settings.dingtalkBot.description')}+ routeSummary={+ routeSummary+ ? `${t(`settings.imBot.defaults.agents.${routeSummary.agentKind}`)} · ${routeSummary.model}`+ : null+ }+ expanded={expanded}+ onToggle={onToggle}+ status={+ <span+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-full px-2.5 py-1',+ 'border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)]',+ 'text-11 font-medium tracking-[0.12px]',+ )}+ style={{ color: statusColor(bot.status) }}+ role="status"+ aria-live="polite"+ >+ <span+ className="h-1.5 w-1.5 rounded-full"+ style={{ backgroundColor: statusColor(bot.status) }}+ aria-hidden+ />+ {t(statusKey[bot.status.kind])}+ </span>+ }+ >+ <ImDefaultSettingsSection channel="dingtalk" embedded onSummaryChange={setRouteSummary} />+ <div className="h-px w-full bg-[var(--border-default)]" />++ {connected ? (+ <div+ className={cn(+ 'flex flex-col gap-3 rounded-xl p-5',+ 'border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',+ )}+ >+ <div className="flex items-start gap-3">+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)] text-[var(--settings-badge-connected)]">+ <Check size={16} />+ </div>+ <div>+ <div className="text-13 font-medium text-[var(--settings-section-title)]">+ {t('settings.dingtalkBot.connected.heading')}+ </div>+ <div className="mt-1 text-12 text-[var(--settings-section-desc)]">+ {bot.ownerUserId+ ? t('settings.dingtalkBot.connected.ownerBound')+ : t('settings.dingtalkBot.connected.waitingOwner')}+ </div>+ </div>+ </div>+ <InfoRow label={t('settings.dingtalkBot.appKeyLabel')} value={bot.appKey} />+ <InfoRow+ label={t('settings.dingtalkBot.connected.ownerLabel')}+ value={bot.ownerUserId || t('settings.dingtalkBot.connected.notBound')}+ />+ <button+ type="button"+ onClick={() => void clear()}+ disabled={bot.isClearing}+ className={cn(+ 'flex h-9 items-center justify-center gap-1.5 rounded-full',+ 'border border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',+ 'text-12 font-medium text-[var(--settings-btn-secondary-text)]',+ bot.isClearing && 'cursor-not-allowed opacity-40',+ )}+ >+ {bot.isClearing ? (+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />+ ) : (+ <Trash2 size={13} />+ )}+ {t('settings.dingtalkBot.disconnect')}+ </button>+ </div>+ ) : (+ <div className="flex flex-col gap-3">+ <FieldLabel>{t('settings.dingtalkBot.appKeyLabel')}</FieldLabel>+ <TextInput+ value={bot.appKey}+ onChange={bot.setAppKey}+ placeholder={t('settings.dingtalkBot.appKeyPlaceholder')}+ />+ <FieldLabel>{t('settings.dingtalkBot.appSecretLabel')}</FieldLabel>+ <div className="relative">+ <TextInput+ type={showSecret ? 'text' : 'password'}+ value={bot.appSecret}+ onChange={bot.setAppSecret}+ placeholder={+ bot.hasSecret+ ? t('settings.dingtalkBot.appSecretSavedPlaceholder')+ : t('settings.dingtalkBot.appSecretPlaceholder')+ }+ className="pr-10"+ />+ <button+ type="button"+ onClick={() => setShowSecret((value) => !value)}+ className="absolute right-3.5 top-1/2 -translate-y-1/2 text-[var(--settings-eye-icon)]"+ aria-label={+ showSecret+ ? t('settings.dingtalkBot.hideSecret')+ : t('settings.dingtalkBot.showSecret')+ }+ >+ {showSecret ? <EyeOff size={18} /> : <Eye size={18} />}+ </button>+ </div>+ <div className="min-h-[18px] text-12">+ {bot.validationError ? (+ <span className="text-[var(--settings-error-text)]" role="alert">+ {bot.validationError}+ </span>+ ) : bot.status.kind === 'error' ? (+ <span className="text-[var(--settings-error-text)]" role="alert">+ {t('settings.dingtalkBot.errorHint')}+ </span>+ ) : (+ <span className="text-[var(--settings-source-meta)]">+ {t('settings.dingtalkBot.formHint')}+ </span>+ )}+ </div>+ <div className="flex gap-2">+ {bot.hasSecret && !bot.appSecret.trim() ? (+ <button+ type="button"+ onClick={() => void bot.reconnect()}+ disabled={bot.isSaving}+ className={primaryButtonClass}+ >+ {bot.isSaving && (+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" />+ )}+ {t('settings.dingtalkBot.reconnect')}+ </button>+ ) : (+ <button+ type="button"+ onClick={() => void bot.connect()}+ disabled={!bot.canConnect}+ className={cn(+ primaryButtonClass,+ !bot.canConnect && 'cursor-not-allowed opacity-40',+ )}+ >+ {bot.isSaving && (+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" />+ )}+ {t('settings.dingtalkBot.connect')}+ </button>+ )}+ {bot.hasSecret && (+ <button+ type="button"+ onClick={() => void clear()}+ disabled={bot.isClearing}+ className="flex h-[42px] w-[42px] shrink-0 items-center justify-center rounded-full border border-[var(--settings-btn-secondary-border)] text-[var(--settings-trash-icon)]"+ aria-label={t('settings.dingtalkBot.disconnect')}+ >+ <Trash2 size={16} />+ </button>+ )}+ </div>+ </div>+ )}++ <div className="border-t border-[var(--settings-theme-card-border)] pt-3">+ <button+ type="button"+ onClick={() => setGuideOpen((value) => !value)}+ className="flex w-full items-center justify-between bg-transparent p-0 text-left"+ aria-expanded={guideOpen}+ >+ <span className="text-13 font-medium text-[var(--settings-section-title)]">+ {t('settings.dingtalkBot.guide.title')}+ </span>+ <span className="text-[var(--settings-section-desc)]">+ {guideOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ </span>+ </button>+ {guideOpen && (+ <div className="mt-3 flex flex-col gap-2 text-12 leading-[1.6] text-[var(--settings-section-desc)]">+ {guideSteps.map((step, index) => (+ <div key={step} className="flex gap-2">+ <span className="font-medium text-[var(--settings-section-title)]">+ {index + 1}.+ </span>+ <span>{step}</span>+ </div>+ ))}+ <button+ type="button"+ onClick={() => window.electronAPI.openExternal?.(DEVELOPER_PORTAL_URL)}+ className="mt-1 w-fit bg-transparent p-0 text-12 font-medium text-[var(--settings-source-link)] underline underline-offset-2"+ >+ {t('settings.dingtalkBot.guide.openPortal')}+ </button>+ </div>+ )}+ </div>+ </ImChannelSettingsCard>+ );+}++const primaryButtonClass = cn(+ 'flex h-[42px] flex-1 items-center justify-center gap-1.5 rounded-full',+ 'border border-[var(--settings-btn-primary-border)] bg-[var(--settings-btn-primary-bg)]',+ 'text-13 font-medium text-[var(--settings-btn-primary-text)]',+);++function FieldLabel({ children }: { children: React.ReactNode }) {+ return (+ <label className="text-12 font-medium text-[var(--settings-section-desc)]">{children}</label>+ );+}++function TextInput({+ value,+ onChange,+ placeholder,+ type = 'text',+ className,+}: {+ value: string;+ onChange: (value: string) => void;+ placeholder: string;+ type?: 'text' | 'password';+ className?: string;+}) {+ return (+ <input+ type={type}+ value={value}+ onChange={(event) => onChange(event.target.value)}+ placeholder={placeholder}+ spellCheck={false}+ autoComplete="off"+ className={cn(+ 'h-[42px] w-full rounded-full px-3.5',+ 'border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',+ 'text-13 text-[var(--settings-input-text)] placeholder:text-[var(--settings-input-placeholder)]',+ 'outline-none focus:border-[var(--settings-input-border-focus)]',+ className,+ )}+ style={{ userSelect: 'text', WebkitUserSelect: 'text' }}+ />+ );+}++function InfoRow({ label, value }: { label: string; value: string }) {+ return (+ <div className="flex justify-between gap-4 text-12 text-[var(--settings-section-desc)]">+ <span>{label}</span>+ <span className="max-w-[65%] truncate font-medium text-[var(--settings-section-title)]">+ {value}+ </span>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx b/apps/desktop/src/renderer/components/settings/ImBotSection.tsxindex eeb14d94b6..e37619b357 100644--- a/apps/desktop/src/renderer/components/settings/ImBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ImBotSection.tsx@@ -15,7 +15,7 @@** 可见性(imBotVisibility 单点):本地模式与「国区构建 + 个人账号登录」都* 没有 Cindy 分栏(深链/兜底一律落「个人」);国区个人账号的个人分栏进一步- * 隐藏 Discord 机器人,只剩飞书(Tips 换 personalFeishuOnly 文案)。+ * 隐藏 Discord / Telegram 机器人,保留中国大陆可用的个人连接。*/import { Lightbulb } from 'lucide-react';@@ -26,6 +26,7 @@ import { cn } from '@/lib/utils';import { useAuth } from '@/contexts/AuthContext';import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';import { DiscordBotSection } from './DiscordBotSection';+import { DingTalkBotSection } from './DingTalkBotSection';import { FeishuBotSection } from './FeishuBotSection';import { HookConnectionsSection } from './HookConnectionsSection';import { TelegramBotSection } from './TelegramBotSection';@@ -69,10 +70,10 @@ function PersonalGroupContent({showTelegram: boolean;}) {const [expandedChannel, setExpandedChannel] = useState<- 'wechat' | 'feishu' | 'discord' | 'telegram' | null+ 'wechat' | 'feishu' | 'discord' | 'telegram' | 'dingtalk' | null>(null);- const toggle = (channel: 'wechat' | 'feishu' | 'discord' | 'telegram') => {+ const toggle = (channel: 'wechat' | 'feishu' | 'discord' | 'telegram' | 'dingtalk') => {setExpandedChannel((current) => (current === channel ? null : channel));};@@ -80,6 +81,10 @@ function PersonalGroupContent({<div className="flex flex-col gap-3"><WechatBotSection expanded={expandedChannel === 'wechat'} onToggle={() => toggle('wechat')} /><FeishuBotSection expanded={expandedChannel === 'feishu'} onToggle={() => toggle('feishu')} />+ <DingTalkBotSection+ expanded={expandedChannel === 'dingtalk'}+ onToggle={() => toggle('dingtalk')}+ />{showDiscord && (<DiscordBotSectionexpanded={expandedChannel === 'discord'}diff --git a/apps/desktop/src/renderer/hooks/useDingTalkBot.ts b/apps/desktop/src/renderer/hooks/useDingTalkBot.tsnew file mode 100644index 0000000000..2bb579ad0d--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useDingTalkBot.ts@@ -0,0 +1,186 @@+import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { createLogger } from '@/lib/logger';+import { toast } from '@/lib/toast';++const log = createLogger('useDingTalkBot');++interface CachedState {+ appKey: string;+ hasSecret: boolean;+ ownerUserId: string;+ status: DingTalkBotTransportStatus;+}++let cachedState: CachedState | null = null;++export function useDingTalkBot() {+ const { t } = useTranslation();+ const [appKey, setAppKeyState] = useState(() => cachedState?.appKey ?? '');+ const [appSecret, setAppSecretState] = useState('');+ const [hasSecret, setHasSecret] = useState(() => cachedState?.hasSecret ?? false);+ const [ownerUserId, setOwnerUserId] = useState(() => cachedState?.ownerUserId ?? '');+ const [status, setStatus] = useState<DingTalkBotTransportStatus>(+ () => cachedState?.status ?? { kind: 'idle' },+ );+ const [validationError, setValidationError] = useState<string | null>(null);+ const [isSaving, setIsSaving] = useState(false);+ const [isClearing, setIsClearing] = useState(false);++ const updateState = useCallback(+ (state: {+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ status: DingTalkBotTransportStatus;+ }) => {+ const next = {+ appKey: state.appKey ?? '',+ hasSecret: state.hasSecret,+ ownerUserId: state.ownerUserId ?? '',+ status: state.status,+ };+ setAppKeyState(next.appKey);+ setHasSecret(next.hasSecret);+ setOwnerUserId(next.ownerUserId);+ setStatus(next.status);+ cachedState = next;+ },+ [],+ );++ useEffect(() => {+ let cancelled = false;+ void window.electronAPI.dingtalkBot+ .getState()+ .then((state) => {+ if (!cancelled) updateState(state);+ })+ .catch((error) => {+ log.error('getState failed:', error instanceof Error ? error.message : String(error));+ });+ return () => {+ cancelled = true;+ };+ }, [updateState]);++ useEffect(() => {+ const unsubStatus = window.electronAPI.dingtalkBot.onStatusChange(({ status: next }) => {+ setStatus(next);+ if (cachedState) cachedState = { ...cachedState, status: next };+ });+ const unsubOwner = window.electronAPI.dingtalkBot.onOwnerChange(({ ownerUserId: next }) => {+ setOwnerUserId(next);+ if (cachedState) cachedState = { ...cachedState, ownerUserId: next };+ });+ return () => {+ unsubStatus();+ unsubOwner();+ };+ }, []);++ const setAppKey = useCallback((value: string) => {+ setAppKeyState(value);+ setValidationError(null);+ }, []);++ const setAppSecret = useCallback((value: string) => {+ setAppSecretState(value);+ setValidationError(null);+ }, []);++ const connect = useCallback(async () => {+ if (isSaving) return false;+ const key = appKey.trim();+ const secret = appSecret.trim();+ if (!key || !secret) {+ setValidationError(t('logic.validation.dingtalkFieldsRequired'));+ return false;+ }+ setIsSaving(true);+ setValidationError(null);+ try {+ const state = await window.electronAPI.dingtalkBot.save({+ appKey: key,+ appSecret: secret,+ });+ updateState(state);+ setAppSecretState('');+ toast.success(t('logic.toasts.dingtalkBotConnected'));+ return true;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log.error('save failed:', message);+ try {+ updateState(await window.electronAPI.dingtalkBot.getState());+ } catch {+ // Preserve the actionable connection error when state refresh also fails.+ }+ toast.error(t('logic.toasts.dingtalkBotConnectFailed'));+ return false;+ } finally {+ setIsSaving(false);+ }+ }, [appKey, appSecret, isSaving, t, updateState]);++ const reconnect = useCallback(async () => {+ if (isSaving) return false;+ setIsSaving(true);+ try {+ const state = await window.electronAPI.dingtalkBot.reconnect();+ updateState(state);+ toast.success(t('logic.toasts.dingtalkBotConnected'));+ return true;+ } catch (error) {+ log.error('reconnect failed:', error instanceof Error ? error.message : String(error));+ try {+ updateState(await window.electronAPI.dingtalkBot.getState());+ } catch {+ // The toast below remains the user-facing fallback.+ }+ toast.error(t('logic.toasts.dingtalkBotConnectFailed'));+ return false;+ } finally {+ setIsSaving(false);+ }+ }, [isSaving, t, updateState]);++ const clear = useCallback(async () => {+ if (isClearing) return;+ setIsClearing(true);+ try {+ await window.electronAPI.dingtalkBot.clear();+ updateState({+ appKey: null,+ hasSecret: false,+ ownerUserId: null,+ status: { kind: 'idle' },+ });+ setAppSecretState('');+ toast.success(t('logic.toasts.dingtalkBotDisconnected'));+ } catch (error) {+ log.error('clear failed:', error instanceof Error ? error.message : String(error));+ toast.error(t('logic.toasts.dingtalkBotDisconnectFailed'));+ } finally {+ setIsClearing(false);+ }+ }, [isClearing, t, updateState]);++ return {+ appKey,+ appSecret,+ hasSecret,+ ownerUserId,+ status,+ validationError,+ isSaving,+ isClearing,+ canConnect: Boolean(appKey.trim() && appSecret.trim() && !isSaving && !isClearing),+ setAppKey,+ setAppSecret,+ connect,+ reconnect,+ clear,+ };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 958ff4e322..33ac2c690a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1912,6 +1912,49 @@}}},+ "dingtalkBot": {+ "title": "DingTalk Bot",+ "description": "Connect your own DingTalk bot and use {{appName}} in DMs and group chats through Stream mode.",+ "status": {+ "needsConfig": "Needs setup",+ "connecting": "Connecting…",+ "connected": "Connected",+ "error": "Connection failed"+ },+ "connected": {+ "heading": "DingTalk bot connected",+ "ownerBound": "The owner is linked. DM the bot or @mention it in a group to begin.",+ "waitingOwner": "DM the bot first. The first direct sender is securely linked as the owner.",+ "ownerLabel": "Owner user ID",+ "notBound": "Waiting for first DM"+ },+ "appKeyLabel": "Client ID",+ "appKeyPlaceholder": "Paste the bot application's Client ID",+ "appSecretLabel": "Client Secret",+ "appSecretPlaceholder": "Paste the bot application's Client Secret",+ "appSecretSavedPlaceholder": "Saved securely; leave blank to reconnect",+ "showSecret": "Show Client Secret",+ "hideSecret": "Hide Client Secret",+ "formHint": "Credentials are encrypted locally. The first DM links the owner after connection.",+ "errorHint": "Connection failed. Check the credentials, Stream mode, and your network, then retry.",+ "connect": "Connect",+ "reconnect": "Reconnect",+ "disconnect": "Unbind",+ "disconnectConfirm": {+ "title": "Unbind DingTalk bot?",+ "description": "This disconnects the bot and removes the locally saved Client ID, Client Secret, and owner link.",+ "confirm": "Unbind",+ "cancel": "Cancel"+ },+ "guide": {+ "title": "Setup guide",+ "step1": "Create an internal app in the DingTalk developer portal and add bot capability.",+ "step2": "Enable Stream mode for the bot and publish an app version.",+ "step3": "Copy the Client ID and Client Secret from App Credentials and enter them above.",+ "step4": "After connecting, DM the bot once to link the owner. @mention it in group chats.",+ "openPortal": "Open DingTalk developer portal ↗"+ }+ },"logout": {"button": "Log out","aria": "Log out"@@ -2634,7 +2677,7 @@"tips": {"cindy": "Cindy is the official shared bot — no credentials needed. Connect Slack and just @Cindy to hand off tasks.","personal": "Personal connections include WeChat scan authorization and your own Feishu / Discord / Telegram credentials. Each channel keeps independent new-conversation settings.",- "personalFeishuOnly": "Personal connections include WeChat scan authorization and your own Feishu credentials. Each channel keeps independent new-conversation settings."+ "personalFeishuOnly": "Personal connections include WeChat scan authorization plus your own Feishu and DingTalk credentials. Each channel keeps independent new-conversation settings."},"defaults": {"title": "New Conversation Configuration",@@ -7577,7 +7620,11 @@"telegramBotConnectFailed": "Telegram bot connection failed; check the token and your network","telegramBotSaveFailed": "Save failed: {{message}}","telegramBotDisconnected": "Telegram bot unbound",- "telegramBotDisconnectFailed": "Unbind failed: {{message}}"+ "telegramBotDisconnectFailed": "Unbind failed: {{message}}",+ "dingtalkBotConnected": "DingTalk bot connected",+ "dingtalkBotConnectFailed": "DingTalk bot connection failed; check credentials, Stream mode, and your network",+ "dingtalkBotDisconnected": "DingTalk bot unbound",+ "dingtalkBotDisconnectFailed": "Failed to unbind DingTalk bot"},"errors": {"openFileFailed": "Cannot open file in system",@@ -7602,7 +7649,8 @@"discordOwnerUserIdFormat": "Discord user ID must be 17-20 digits","telegramFieldsRequired": "Bot Token and Telegram user ID are both required","telegramTokenFormat": "Invalid token format: expected the \"digits:secret\" shape generated by BotFather",- "telegramOwnerUserIdFormat": "Telegram user ID must be numeric"+ "telegramOwnerUserIdFormat": "Telegram user ID must be numeric",+ "dingtalkFieldsRequired": "Client ID and Client Secret are both required"},"confirm": {"logoutTitle": "Log out",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 90035d4dde..9b19b6e0fb 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1911,6 +1911,49 @@}}},+ "dingtalkBot": {+ "title": "DingTalk ボット",+ "description": "自作の DingTalk ボットを接続し、Stream モードで DM やグループから {{appName}} を利用します。",+ "status": {+ "needsConfig": "設定が必要",+ "connecting": "接続中…",+ "connected": "接続済み",+ "error": "接続失敗"+ },+ "connected": {+ "heading": "DingTalk ボットに接続済み",+ "ownerBound": "オーナーを連携済みです。DM またはグループでメンションして開始できます。",+ "waitingOwner": "まずボットに DM してください。最初の送信者がオーナーとして安全に連携されます。",+ "ownerLabel": "オーナーのユーザー ID",+ "notBound": "最初の DM を待機中"+ },+ "appKeyLabel": "Client ID",+ "appKeyPlaceholder": "ボットアプリの Client ID を貼り付け",+ "appSecretLabel": "Client Secret",+ "appSecretPlaceholder": "ボットアプリの Client Secret を貼り付け",+ "appSecretSavedPlaceholder": "安全に保存済み。空欄のまま再接続できます",+ "showSecret": "Client Secret を表示",+ "hideSecret": "Client Secret を隠す",+ "formHint": "認証情報はローカルで暗号化されます。接続後、最初の DM でオーナーを連携します。",+ "errorHint": "接続できません。認証情報、Stream モード、ネットワークを確認して再試行してください。",+ "connect": "接続",+ "reconnect": "再接続",+ "disconnect": "連携解除",+ "disconnectConfirm": {+ "title": "DingTalk ボットの連携を解除しますか?",+ "description": "接続を切断し、保存済みの Client ID、Client Secret、オーナー連携を削除します。",+ "confirm": "連携解除",+ "cancel": "キャンセル"+ },+ "guide": {+ "title": "設定ガイド",+ "step1": "DingTalk 開発者ポータルで社内アプリを作成し、ボット機能を追加します。",+ "step2": "ボットの Stream モードを有効にし、アプリのバージョンを公開します。",+ "step3": "アプリ認証情報から Client ID と Client Secret をコピーして入力します。",+ "step4": "接続後、最初にボットへ DM してオーナーを連携します。グループではメンションしてください。",+ "openPortal": "DingTalk 開発者ポータルを開く ↗"+ }+ },"logout": {"button": "ログアウト","aria": "ログアウト"@@ -2633,7 +2676,7 @@"tips": {"cindy": "Cindy は公式提供の共有ボットです。認証情報の申請は不要で、Slack を連携して @Cindy にメンションするだけでタスクを任せられます。","personal": "個人接続には WeChat のスキャン認証と、自分の Feishu / Discord / Telegram 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。",- "personalFeishuOnly": "個人接続には WeChat のスキャン認証と、自分の Feishu 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。"+ "personalFeishuOnly": "個人接続には WeChat のスキャン認証と、自分の Feishu / DingTalk 認証情報を使用する接続があります。新規会話設定はチャネルごとに保存されます。"},"defaults": {"title": "新規会話設定",@@ -7566,7 +7609,11 @@"telegramBotConnectFailed": "Telegram ボットの接続に失敗しました。Token とネットワークを確認してください","telegramBotSaveFailed": "保存に失敗しました:{{message}}","telegramBotDisconnected": "Telegram ボットの連携を解除しました",- "telegramBotDisconnectFailed": "連携解除に失敗しました:{{message}}"+ "telegramBotDisconnectFailed": "連携解除に失敗しました:{{message}}",+ "dingtalkBotConnected": "DingTalk ボットに接続しました",+ "dingtalkBotConnectFailed": "DingTalk ボットに接続できません。認証情報、Stream モード、ネットワークを確認してください",+ "dingtalkBotDisconnected": "DingTalk ボットの連携を解除しました",+ "dingtalkBotDisconnectFailed": "DingTalk ボットの連携解除に失敗しました"},"errors": {"openFileFailed": "システムでファイルを開けません",@@ -7591,7 +7638,8 @@"discordOwnerUserIdFormat": "Discord ユーザー ID は 17-20 桁の数字である必要があります","telegramFieldsRequired": "Bot Token と Telegram ユーザー ID の両方を入力してください","telegramTokenFormat": "Token の形式が不正です。BotFather が生成する「数字:シークレット」の形にしてください",- "telegramOwnerUserIdFormat": "Telegram ユーザー ID は数字である必要があります"+ "telegramOwnerUserIdFormat": "Telegram ユーザー ID は数字である必要があります",+ "dingtalkFieldsRequired": "Client ID と Client Secret の両方を入力してください"},"confirm": {"logoutTitle": "ログアウト",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex af16740823..8cd161a9cd 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1911,6 +1911,49 @@}}},+ "dingtalkBot": {+ "title": "DingTalk 봇",+ "description": "직접 만든 DingTalk 봇을 연결하고 Stream 모드로 DM과 그룹에서 {{appName}}를 사용합니다.",+ "status": {+ "needsConfig": "설정 필요",+ "connecting": "연결 중…",+ "connected": "연결됨",+ "error": "연결 실패"+ },+ "connected": {+ "heading": "DingTalk 봇 연결됨",+ "ownerBound": "소유자가 연결되었습니다. DM을 보내거나 그룹에서 멘션해 시작하세요.",+ "waitingOwner": "먼저 봇에게 DM을 보내세요. 첫 번째 발신자가 소유자로 안전하게 연결됩니다.",+ "ownerLabel": "소유자 사용자 ID",+ "notBound": "첫 DM 대기 중"+ },+ "appKeyLabel": "Client ID",+ "appKeyPlaceholder": "봇 애플리케이션의 Client ID 붙여넣기",+ "appSecretLabel": "Client Secret",+ "appSecretPlaceholder": "봇 애플리케이션의 Client Secret 붙여넣기",+ "appSecretSavedPlaceholder": "안전하게 저장됨. 비워 두고 다시 연결할 수 있습니다",+ "showSecret": "Client Secret 표시",+ "hideSecret": "Client Secret 숨기기",+ "formHint": "자격 증명은 로컬에 암호화됩니다. 연결 후 첫 DM으로 소유자를 연결합니다.",+ "errorHint": "연결 실패. 자격 증명, Stream 모드, 네트워크를 확인한 후 다시 시도하세요.",+ "connect": "연결",+ "reconnect": "다시 연결",+ "disconnect": "연동 해제",+ "disconnectConfirm": {+ "title": "DingTalk 봇 연동을 해제하시겠습니까?",+ "description": "연결을 끊고 저장된 Client ID, Client Secret, 소유자 연결을 삭제합니다.",+ "confirm": "연동 해제",+ "cancel": "취소"+ },+ "guide": {+ "title": "설정 가이드",+ "step1": "DingTalk 개발자 포털에서 내부 앱을 만들고 봇 기능을 추가합니다.",+ "step2": "봇의 Stream 모드를 활성화하고 앱 버전을 게시합니다.",+ "step3": "앱 자격 증명에서 Client ID와 Client Secret을 복사해 입력합니다.",+ "step4": "연결 후 봇에게 먼저 DM을 보내 소유자를 연결합니다. 그룹에서는 멘션하세요.",+ "openPortal": "DingTalk 개발자 포털 열기 ↗"+ }+ },"logout": {"button": "로그아웃","aria": "로그아웃"@@ -2633,7 +2676,7 @@"tips": {"cindy": "Cindy는 공식 제공 공유 봇입니다. 자격 증명을 신청할 필요 없이 Slack을 연결하고 @Cindy를 멘션하면 바로 작업을 맡길 수 있습니다.","personal": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu / Discord / Telegram 인증 정보 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다.",- "personalFeishuOnly": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu 인증 정보 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다."+ "personalFeishuOnly": "개인 연결에는 WeChat 스캔 인증과 직접 발급한 Feishu 및 DingTalk 자격 증명 연결이 포함됩니다. 새 대화 설정은 채널별로 저장됩니다."},"defaults": {"title": "새 대화 설정",@@ -7566,7 +7609,11 @@"telegramBotConnectFailed": "Telegram 봇 연결 실패. Token과 네트워크를 확인하세요","telegramBotSaveFailed": "저장 실패: {{message}}","telegramBotDisconnected": "Telegram 봇 연동이 해제됨",- "telegramBotDisconnectFailed": "연동 해제 실패: {{message}}"+ "telegramBotDisconnectFailed": "연동 해제 실패: {{message}}",+ "dingtalkBotConnected": "DingTalk 봇이 연결됨",+ "dingtalkBotConnectFailed": "DingTalk 봇 연결 실패. 자격 증명, Stream 모드, 네트워크를 확인하세요",+ "dingtalkBotDisconnected": "DingTalk 봇 연동이 해제됨",+ "dingtalkBotDisconnectFailed": "DingTalk 봇 연동 해제 실패"},"errors": {"openFileFailed": "시스템에서 파일을 열 수 없습니다",@@ -7591,7 +7638,8 @@"discordOwnerUserIdFormat": "Discord 사용자 ID는 17-20자리 숫자여야 합니다","telegramFieldsRequired": "Bot Token과 Telegram 사용자 ID 둘 다 입력해야 합니다","telegramTokenFormat": "Token 형식이 잘못되었습니다. BotFather가 생성한 \"숫자:시크릿\" 형태여야 합니다",- "telegramOwnerUserIdFormat": "Telegram 사용자 ID는 숫자여야 합니다"+ "telegramOwnerUserIdFormat": "Telegram 사용자 ID는 숫자여야 합니다",+ "dingtalkFieldsRequired": "Client ID와 Client Secret을 모두 입력해야 합니다"},"confirm": {"logoutTitle": "로그아웃",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 8d0ebee811..bcc1eadd13 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1911,6 +1911,49 @@}}},+ "dingtalkBot": {+ "title": "钉钉机器人",+ "description": "连接你自建的钉钉机器人,通过 Stream 模式在私聊和群聊中使用 {{appName}}。",+ "status": {+ "needsConfig": "需要配置",+ "connecting": "连接中…",+ "connected": "已连接",+ "error": "连接失败"+ },+ "connected": {+ "heading": "钉钉机器人已连接",+ "ownerBound": "主人已绑定;私聊或在群里 @ 机器人即可开始。",+ "waitingOwner": "请先私聊机器人,第一位私聊者会安全绑定为主人。",+ "ownerLabel": "主人用户 ID",+ "notBound": "等待首次私聊"+ },+ "appKeyLabel": "Client ID",+ "appKeyPlaceholder": "粘贴机器人应用的 Client ID",+ "appSecretLabel": "Client Secret",+ "appSecretPlaceholder": "粘贴机器人应用的 Client Secret",+ "appSecretSavedPlaceholder": "已安全保存;留空可直接重新连接",+ "showSecret": "显示 Client Secret",+ "hideSecret": "隐藏 Client Secret",+ "formHint": "凭证仅加密保存在本机;连接后首次私聊会绑定主人。",+ "errorHint": "连接失败,请检查凭证、Stream 模式和网络后重试。",+ "connect": "连接",+ "reconnect": "重新连接",+ "disconnect": "解绑",+ "disconnectConfirm": {+ "title": "解绑钉钉机器人?",+ "description": "解绑后会断开连接,并清除本机保存的 Client ID、Client Secret 和主人绑定。",+ "confirm": "解绑",+ "cancel": "取消"+ },+ "guide": {+ "title": "配置引导",+ "step1": "在钉钉开放平台创建企业内部应用,并添加机器人能力。",+ "step2": "为机器人启用 Stream 模式,并发布应用版本。",+ "step3": "从应用凭证页复制 Client ID 和 Client Secret,填入上方。",+ "step4": "连接成功后先私聊机器人完成主人绑定;群聊中需要 @ 机器人。",+ "openPortal": "打开钉钉开放平台 ↗"+ }+ },"logout": {"button": "退出登录","aria": "退出登录"@@ -2633,7 +2676,7 @@"tips": {"cindy": "Cindy 是官方提供的共享机器人:无需申请任何凭证,连接 Slack 后 @Cindy 即可直接派活。","personal": "个人连接包括微信扫码,以及使用自有凭证接入飞书 / Discord / Telegram;各渠道独立保存新对话配置。",- "personalFeishuOnly": "个人连接包括微信扫码,以及使用自有凭证接入飞书;各渠道独立保存新对话配置。"+ "personalFeishuOnly": "个人连接包括微信扫码,以及使用自有凭证接入飞书和钉钉;各渠道独立保存新对话配置。"},"defaults": {"title": "新对话配置",@@ -7566,7 +7609,11 @@"telegramBotConnectFailed": "Telegram 机器人连接失败,请检查 Token 和网络","telegramBotSaveFailed": "保存失败:{{message}}","telegramBotDisconnected": "已解绑 Telegram 机器人",- "telegramBotDisconnectFailed": "解绑失败:{{message}}"+ "telegramBotDisconnectFailed": "解绑失败:{{message}}",+ "dingtalkBotConnected": "钉钉机器人已连接",+ "dingtalkBotConnectFailed": "钉钉机器人连接失败,请检查凭证、Stream 模式和网络",+ "dingtalkBotDisconnected": "已解绑钉钉机器人",+ "dingtalkBotDisconnectFailed": "钉钉机器人解绑失败"},"errors": {"openFileFailed": "无法在系统中打开文件",@@ -7591,7 +7638,8 @@"discordOwnerUserIdFormat": "Discord 用户 ID 必须是 17-20 位纯数字","telegramFieldsRequired": "Bot Token 和 Telegram 用户 ID 都需要填写","telegramTokenFormat": "Token 格式不对:应为 BotFather 生成的「1234567:xxxx」形态",- "telegramOwnerUserIdFormat": "Telegram 用户 ID 必须是纯数字"+ "telegramOwnerUserIdFormat": "Telegram 用户 ID 必须是纯数字",+ "dingtalkFieldsRequired": "Client ID 和 Client Secret 都需要填写"},"confirm": {"logoutTitle": "退出登录",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8514eecd49..9ebe710bbb 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -412,6 +412,8 @@ type TelegramBotTransportStatus =| { kind: 'conflict'; appId: string }| { kind: 'error'; reason: string };+type DingTalkBotTransportStatus = DiscordBotTransportStatus;+type WechatBotPhase =| 'disconnected'| 'authorizing'@@ -1792,6 +1794,33 @@ interface ElectronAPI {) => () => void;};+ // ── Personal DingTalk Bot (Settings → IM Bot → Personal) ──+ dingtalkBot: {+ getState: () => Promise<{+ status: DingTalkBotTransportStatus;+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ }>;+ save: (payload: { appKey: string; appSecret: string }) => Promise<{+ status: DingTalkBotTransportStatus;+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ }>;+ reconnect: () => Promise<{+ status: DingTalkBotTransportStatus;+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+ }>;+ clear: () => Promise<{ ok: true }>;+ onStatusChange: (+ callback: (update: { status: DingTalkBotTransportStatus }) => void,+ ) => () => void;+ onOwnerChange: (callback: (update: { ownerUserId: string }) => void) => () => void;+ };+// ── Personal WeChat (Settings → IM Bot → Personal) ──wechatBot: {getState: () => Promise<WechatBotState>;diff --git a/apps/desktop/src/shared/imDefaultSettings.ts b/apps/desktop/src/shared/imDefaultSettings.tsindex b20fa5a3e4..d773f1de80 100644--- a/apps/desktop/src/shared/imDefaultSettings.ts+++ b/apps/desktop/src/shared/imDefaultSettings.ts@@ -8,7 +8,7 @@ export type ImDefaultEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' |* 刻意读 global(channel=undefined, 见 hook-control/session-runner.ts), 不落* 在这个键上 — 两者互不影响。*/-export type ImDefaultSettingsChannel = 'feishu' | 'slack' | 'discord' | 'wechat' | 'telegram';+export type ImDefaultSettingsChannel = 'feishu' | 'slack' | 'discord' | 'wechat' | 'telegram' | 'dingtalk';export interface ImDefaultAgentSettings {providerId: string | null;@@ -57,6 +57,7 @@ export const IM_DEFAULT_SETTINGS_CHANNELS: readonly ImDefaultSettingsChannel[] ='discord','wechat','telegram',+ 'dingtalk',];export const IM_DEFAULT_EFFORT_OVERRIDES: Readonly<Partial<Record<string, ImDefaultEffort>>> = {diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.tsindex 166ab0a9cb..d33ef54613 100644--- a/apps/desktop/src/shared/sessionSource.ts+++ b/apps/desktop/src/shared/sessionSource.ts@@ -5,6 +5,7 @@ export const SESSION_SOURCES = ['telegram','discord','wechat',+ 'dingtalk','scheduler','learn','shared',@@ -17,6 +18,7 @@ export type SessionSource = (typeof SESSION_SOURCES)[number];// slack: IM 渠道自动建的会话——用户在 Slack 发消息后 desktop 同步可见。// telegram: 共享 Cindy Telegram bot 派发并在本机执行的会话。// discord: IM 渠道自动建的会话——用户在 Discord 发消息后 desktop 同步可见。+// dingtalk: 钉钉机器人私聊与群 lane 自动建的会话。// feishu: IM 渠道自动建的会话——落侧边栏「对话」分组(workspaceKind='dialogue')。// (2026-07-06 曾加入后按 Lizi 要求回退;2026-07-16 按 Lizi 要求重新加入,// 这次带 dialogue 归组,不再以 im-working-dir 聚成假项目组。)@@ -31,6 +33,7 @@ export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = ['telegram','discord','wechat',+ 'dingtalk','scheduler','learn','shared',@@ -43,6 +46,7 @@ export function normalizeSessionSource(source: unknown): SessionSource {source === 'telegram' ||source === 'discord' ||source === 'wechat' ||+ source === 'dingtalk' ||source === 'scheduler' ||source === 'learn' ||source === 'shared' ||diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 7f308858a5..2c49a25c89 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -156,6 +156,10 @@ device-link 里「可以选择在哪台机器上运行」这一维度,两端OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入的一次性代码。当前先采用各语言直译,作为待产品裁决术语登记,避免后续界面出现“设备代码/配对码/认证码”等多套说法。+### DingTalk++钉钉机器人连接的产品名称,沿用官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。+### Black Cat灵动岛角色皮肤名(设置页「图标皮肤」列表)。角色本体是黑猫形象,四语先采用直译并登记为待讨论,避免后续界面出现「ブラックキャット / 블랙캣」等音译与直译混用。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 7fc4d4ee86..e1ee02fe5a 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -87,6 +87,17 @@},"note": "个人微信连接在设置页中的产品名称;先登记为 proposed,待产品术语评审后再决定是否固化。"},+ {+ "id": "dingtalk",+ "status": "proposed",+ "en": "DingTalk",+ "translations": {+ "zh-CN": "钉钉",+ "ja": "DingTalk",+ "ko": "DingTalk"+ },+ "note": "钉钉机器人连接的产品名称,沿用官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。"+ },{"id": "openclaw","status": "proposed",diff --git a/packages/lizi-im/package.json b/packages/lizi-im/package.jsonindex 326b9bb22e..06a502547f 100644--- a/packages/lizi-im/package.json+++ b/packages/lizi-im/package.json@@ -21,6 +21,7 @@"license": "Apache-2.0","dependencies": {"@larksuiteoapi/node-sdk": "^1.60.0",+ "dingtalk-stream": "^2.1.5","discord.js": "^14.16.0"},"devDependencies": {diff --git a/packages/lizi-im/src/dingtalk/__tests__/api.test.ts b/packages/lizi-im/src/dingtalk/__tests__/api.test.tsnew file mode 100644index 0000000000..8bfe0438c0--- /dev/null+++ b/packages/lizi-im/src/dingtalk/__tests__/api.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from "vitest";++import { DingTalkApiClient } from "../api.js";++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++describe("DingTalkApiClient", () => {+ it("never posts to an untrusted session webhook and falls back to the fixed API", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ jsonResponse({ accessToken: "token", expireIn: 7200 }),+ )+ .mockResolvedValueOnce(jsonResponse({}));+ const api = new DingTalkApiClient("app-key", "app-secret", fetcher);++ await api.sendText(+ {+ kind: "direct",+ id: "owner-1",+ sessionWebhook: "https://example.invalid/collect",+ sessionWebhookExpiresAt: Date.now() + 60_000,+ },+ "hello",+ );++ expect(fetcher.mock.calls.map(([url]) => String(url))).toEqual([+ "https://api.dingtalk.com/v1.0/oauth2/accessToken",+ "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend",+ ]);+ });++ it("rejects media download URLs outside the expected service domains", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ jsonResponse({ accessToken: "token", expireIn: 7200 }),+ )+ .mockResolvedValueOnce(+ jsonResponse({ downloadUrl: "https://127.0.0.1/internal-resource" }),+ );+ const api = new DingTalkApiClient("app-key", "app-secret", fetcher);++ await expect(api.downloadImage("download-code")).rejects.toThrow(+ /untrusted URL/,+ );+ expect(fetcher).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/lizi-im/src/dingtalk/__tests__/codec.test.ts b/packages/lizi-im/src/dingtalk/__tests__/codec.test.tsnew file mode 100644index 0000000000..d274d7cec6--- /dev/null+++ b/packages/lizi-im/src/dingtalk/__tests__/codec.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from "vitest";++import { decodeLaneUserId, encodeLaneUserId } from "../codec.js";++describe("dingtalk lane codec", () => {+ it("round-trips group conversation ids without leaking separators", () => {+ const encoded = encodeLaneUserId("cid/a b");+ expect(encoded).toBe("g/cid%2Fa%20b");+ expect(decodeLaneUserId(encoded)).toEqual({ conversationId: "cid/a b" });+ });++ it("does not treat direct user ids as group lanes", () => {+ expect(decodeLaneUserId("user-1")).toBeNull();+ expect(decodeLaneUserId("g/")).toBeNull();+ });+});diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.tsnew file mode 100644index 0000000000..68d904f315--- /dev/null+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts@@ -0,0 +1,288 @@+import { describe, expect, it, vi } from "vitest";+import type { DWClientDownStream } from "dingtalk-stream";++import type { IMHost, IMMessageEvent } from "../../types.js";+import { DingTalkIM, type DingTalkStreamClient } from "../index.js";++class FakeClient implements DingTalkStreamClient {+ connected = false;+ registered = false;+ config = { autoReconnect: true };+ callback: ((message: DWClientDownStream) => void) | null = null;+ acknowledgements: Array<{ messageId: string; result: unknown }> = [];++ registerCallbackListener(+ _topic: string,+ callback: (message: DWClientDownStream) => void,+ ): DingTalkStreamClient {+ this.callback = callback;+ return this;+ }++ async connect(): Promise<void> {+ this.connected = true;+ this.registered = true;+ }++ disconnect(): void {+ this.connected = false;+ this.registered = false;+ }++ socketCallBackResponse(messageId: string, result: unknown): void {+ this.acknowledgements.push({ messageId, result });+ }++ emit(payload: Record<string, unknown>, callbackId = "callback-1"): void {+ this.callback?.({+ headers: { messageId: callbackId },+ data: JSON.stringify(payload),+ } as DWClientDownStream);+ }+}++function makeHost() {+ const secrets = new Map<string, string>([+ ["dingtalk-bot-app-key", "app-key"],+ ["dingtalk-bot-app-secret", "app-secret"],+ ]);+ const handlers = new Map<string, (payload?: unknown) => unknown>();+ const broadcasts: Array<{ channel: string; payload: unknown }> = [];+ const host: IMHost = {+ secrets: {+ write: (key, value) => {+ secrets.set(key, value);+ return true;+ },+ read: (key) => secrets.get(key) ?? null,+ remove: (key) => void secrets.delete(key),+ isAvailable: () => true,+ },+ ipc: {+ handle: (channel, handler) => void handlers.set(channel, handler),+ broadcast: (channel, payload) =>+ void broadcasts.push({ channel, payload }),+ },+ paths: { feishuMediaDir: "/unused" },+ httpPostForm: async () => ({ status: 200, body: {} }),+ };+ return { host, secrets, handlers, broadcasts };+}++function directMessage(overrides: Record<string, unknown> = {}) {+ return {+ conversationId: "direct-chat",+ conversationType: "1",+ msgId: "message-1",+ msgtype: "text",+ robotCode: "app-key",+ senderId: "sender-id",+ senderStaffId: "owner-1",+ senderNick: "Owner",+ text: { content: "hello" },+ ...overrides,+ };+}++describe("DingTalkIM", () => {+ it("claims the first direct sender, acknowledges immediately, and drops other direct users", async () => {+ const { host, secrets } = makeHost();+ const client = new FakeClient();+ const im = new DingTalkIM(host, { clientFactory: () => client });+ const received: IMMessageEvent[] = [];+ im.onMessage((event) => received.push(event));+ await im.init();++ client.emit(directMessage());+ await vi.waitFor(() => expect(received).toHaveLength(1));+ expect(client.acknowledgements).toEqual([+ { messageId: "callback-1", result: { success: true } },+ ]);+ expect(secrets.get("dingtalk-bot-owner-user-id")).toBe("owner-1");+ expect(received[0]).toMatchObject({+ channelName: "dingtalk",+ senderId: "owner-1",+ text: "hello",+ });++ client.emit(+ directMessage({+ msgId: "message-2",+ senderStaffId: "other-user",+ text: { content: "ignored" },+ }),+ "callback-2",+ );+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(received).toHaveLength(1);+ });++ it("routes mentioned group messages to one lane with speaker metadata", async () => {+ const { host } = makeHost();+ const client = new FakeClient();+ const im = new DingTalkIM(host, { clientFactory: () => client });+ const received: IMMessageEvent[] = [];+ im.onMessage((event) => received.push(event));+ await im.init();+ client.emit(directMessage());+ await vi.waitFor(() => expect(received).toHaveLength(1));++ client.emit(+ directMessage({+ conversationId: "group/a",+ conversationType: "2",+ msgId: "group-message-1",+ senderStaffId: "guest-1",+ senderNick: "Guest",+ isInAtList: true,+ text: { content: "group question" },+ }),+ "callback-2",+ );+ await vi.waitFor(() => expect(received).toHaveLength(2));+ expect(received[1]).toMatchObject({+ senderId: "g/group%2Fa",+ chatId: "group/a",+ text: "group question",+ speaker: { id: "guest-1", name: "Guest", isOwner: false },+ });+ });++ it("does not expose the app secret through public state", async () => {+ const { host } = makeHost();+ const client = new FakeClient();+ const im = new DingTalkIM(host, { clientFactory: () => client });+ im.registerIpc();+ await im.init();+ const state = im.getPublicState();+ expect(state).toEqual({+ status: { kind: "connected", appId: "app-key" },+ appKey: "app-key",+ hasSecret: true,+ ownerUserId: null,+ });+ expect(state).not.toHaveProperty("appSecret");+ });++ it("does not emit a slow media callback after the connection is disposed", async () => {+ const { host, secrets } = makeHost();+ secrets.set("dingtalk-bot-owner-user-id", "owner-1");+ host.media = {+ getCachedImage: vi.fn(async () => null),+ cacheImage: vi.fn(async () => ({+ absPath: "/media/image.png",+ url: "cindy-media://image.png",+ })),+ resolveMediaUrl: vi.fn(() => null),+ };+ let releaseDownload!: (response: Response) => void;+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ accessToken: "token", expireIn: 7200 })),+ )+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ downloadUrl: "https://media.dingtalk.com/image.png",+ }),+ ),+ )+ .mockImplementationOnce(+ () =>+ new Promise<Response>((resolve) => {+ releaseDownload = resolve;+ }),+ );+ const client = new FakeClient();+ const im = new DingTalkIM(host, { clientFactory: () => client, fetcher });+ const received: IMMessageEvent[] = [];+ im.onMessage((event) => received.push(event));+ await im.init();++ client.emit(+ directMessage({+ msgId: "picture-1",+ msgtype: "picture",+ content: { downloadCode: "download-1" },+ }),+ );+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(3));+ await im.dispose();+ releaseDownload(+ new Response(+ Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ ),+ );+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(received).toHaveLength(0);+ });++ it("preserves arrival order while an earlier image is downloading", async () => {+ const { host, secrets } = makeHost();+ secrets.set("dingtalk-bot-owner-user-id", "owner-1");+ host.media = {+ getCachedImage: vi.fn(async () => null),+ cacheImage: vi.fn(async () => ({+ absPath: "/media/image.png",+ url: "cindy-media://image.png",+ })),+ resolveMediaUrl: vi.fn(() => null),+ };+ let releaseDownload!: (response: Response) => void;+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ accessToken: "token", expireIn: 7200 })),+ )+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ downloadUrl: "https://media.dingtalk.com/image.png",+ }),+ ),+ )+ .mockImplementationOnce(+ () =>+ new Promise<Response>((resolve) => {+ releaseDownload = resolve;+ }),+ );+ const client = new FakeClient();+ const im = new DingTalkIM(host, { clientFactory: () => client, fetcher });+ const received: IMMessageEvent[] = [];+ im.onMessage((event) => received.push(event));+ await im.init();++ client.emit(+ directMessage({+ msgId: "picture-1",+ msgtype: "picture",+ content: { downloadCode: "download-1" },+ }),+ "callback-picture",+ );+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(3));+ client.emit(+ directMessage({+ msgId: "text-2",+ text: { content: "after image" },+ }),+ "callback-text",+ );+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(received).toHaveLength(0);++ releaseDownload(+ new Response(+ Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ ),+ );+ await vi.waitFor(() => expect(received).toHaveLength(2));+ expect(received.map((event) => event.messageId)).toEqual([+ "picture-1",+ "text-2",+ ]);+ });+});diff --git a/packages/lizi-im/src/dingtalk/__tests__/inbound.test.ts b/packages/lizi-im/src/dingtalk/__tests__/inbound.test.tsnew file mode 100644index 0000000000..03255a23f9--- /dev/null+++ b/packages/lizi-im/src/dingtalk/__tests__/inbound.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";++import { parseInboundContent, parseInboundEnvelope } from "../inbound.js";++function envelope(overrides: Record<string, unknown> = {}) {+ return {+ conversationId: "chat-1",+ conversationType: "1",+ msgId: "message-1",+ msgtype: "text",+ robotCode: "app-key",+ senderId: "sender-id",+ senderStaffId: "staff-id",+ senderNick: "Alice",+ sessionWebhook: "https://oapi.dingtalk.com/robot/sendBySession",+ sessionWebhookExpiredTime: 2_000_000_000,+ text: { content: " hello " },+ ...overrides,+ };+}++describe("dingtalk inbound normalization", () => {+ it("normalizes identifiers and second-based webhook expiry", () => {+ const parsed = parseInboundEnvelope(envelope());+ expect(parsed).toMatchObject({+ senderId: "staff-id",+ senderName: "Alice",+ sessionWebhookExpiresAt: 2_000_000_000_000,+ });+ expect(parsed && parseInboundContent(parsed)).toMatchObject({+ text: "hello",+ unsupported: [],+ });+ });++ it("detects a group mention from the bot code", () => {+ const parsed = parseInboundEnvelope(+ envelope({+ conversationType: "2",+ atUsers: [{ dingtalkId: "app-key" }],+ }),+ );+ expect(parsed?.mentioned).toBe(true);+ });++ it("uses audio recognition and fails closed for raw media", () => {+ const audio = parseInboundEnvelope(+ envelope({ msgtype: "audio", recognition: "明天提醒我" }),+ );+ expect(audio && parseInboundContent(audio).text).toBe("明天提醒我");++ const video = parseInboundEnvelope(envelope({ msgtype: "video" }));+ expect(video && parseInboundContent(video).unsupported).toEqual([+ { type: "video", label: "视频" },+ ]);+ });++ it("collects text and image download codes from rich text content", () => {+ const parsed = parseInboundEnvelope(+ envelope({+ msgtype: "richText",+ content: {+ richText: [+ { type: "text", text: "first" },+ { type: "picture", downloadCode: "image-1" },+ { type: "text", text: "second" },+ ],+ },+ }),+ );+ expect(parsed && parseInboundContent(parsed)).toMatchObject({+ text: "first\n\nsecond",+ downloadCodes: ["image-1"],+ });+ });+});diff --git a/packages/lizi-im/src/dingtalk/api.ts b/packages/lizi-im/src/dingtalk/api.tsnew file mode 100644index 0000000000..d374f40acc--- /dev/null+++ b/packages/lizi-im/src/dingtalk/api.ts@@ -0,0 +1,295 @@+const ACCESS_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken";+const DOWNLOAD_URL =+ "https://api.dingtalk.com/v1.0/robot/messageFiles/download";+const DIRECT_SEND_URL =+ "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend";+const GROUP_SEND_URL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send";+const MAX_IMAGE_BYTES = 20 * 1024 * 1024;+const HTTP_TIMEOUT_MS = 30_000;++export type DingTalkFetch = typeof fetch;++interface AccessTokenCache {+ value: string;+ expiresAt: number;+}++export interface DingTalkOutboundTarget {+ kind: "direct" | "group";+ id: string;+ sessionWebhook: string | null;+ sessionWebhookExpiresAt: number | null;+}++export class DingTalkApiClient {+ private accessToken: AccessTokenCache | null = null;+ private readonly activeRequests = new Set<AbortController>();+ private closed = false;++ constructor(+ private readonly appKey: string,+ private readonly appSecret: string,+ private readonly fetcher: DingTalkFetch = fetch,+ ) {}++ clearAccessToken(): void {+ this.accessToken = null;+ }++ close(): void {+ this.closed = true;+ this.accessToken = null;+ for (const controller of this.activeRequests) controller.abort();+ this.activeRequests.clear();+ }++ async sendText(target: DingTalkOutboundTarget, text: string): Promise<void> {+ if (target.sessionWebhook && this.isWebhookUsable(target)) {+ try {+ await this.postJson(target.sessionWebhook, {+ msgtype: "text",+ text: { content: text },+ });+ return;+ } catch {+ // The proactive API is the durable fallback after a session webhook expires.+ }+ }++ const token = await this.getAccessToken();+ const body =+ target.kind === "group"+ ? {+ robotCode: this.appKey,+ openConversationId: target.id,+ msgKey: "sampleText",+ msgParam: JSON.stringify({ content: text }),+ }+ : {+ robotCode: this.appKey,+ userIds: [target.id],+ msgKey: "sampleText",+ msgParam: JSON.stringify({ content: text }),+ };+ await this.postJson(+ target.kind === "group" ? GROUP_SEND_URL : DIRECT_SEND_URL,+ body,+ token,+ );+ }++ async downloadImage(+ downloadCode: string,+ ): Promise<{ buffer: Uint8Array; mimeType: string }> {+ const token = await this.getAccessToken();+ const response = await this.postJson(+ DOWNLOAD_URL,+ { downloadCode, robotCode: this.appKey },+ token,+ );+ const downloadUrl = stringField(response, "downloadUrl");+ if (!downloadUrl)+ throw new Error("dingtalk media response missing downloadUrl");+ const parsed = new URL(downloadUrl);+ if (!isAllowedMediaHost(parsed)) {+ throw new Error("dingtalk media response returned an untrusted URL");+ }++ const res = await this.fetchWithTimeout(downloadUrl, { redirect: "error" });+ if (!res.ok)+ throw new Error(`dingtalk media download failed: HTTP ${res.status}`);+ const declaredLength = Number(res.headers.get("content-length") ?? 0);+ if (declaredLength > MAX_IMAGE_BYTES) {+ throw new Error("dingtalk media exceeds the image size limit");+ }+ const bytes = await readBodyLimited(res, MAX_IMAGE_BYTES);+ if (bytes.byteLength === 0) {+ throw new Error("dingtalk media has an invalid image size");+ }+ const mimeType = detectImageMime(bytes);+ if (!mimeType) {+ throw new Error("dingtalk media is not an image");+ }+ return { buffer: bytes, mimeType };+ }++ private isWebhookUsable(target: DingTalkOutboundTarget): boolean {+ if (!target.sessionWebhook) return false;+ let url: URL;+ try {+ url = new URL(target.sessionWebhook);+ } catch {+ return false;+ }+ if (+ url.protocol !== "https:" ||+ (url.hostname !== "api.dingtalk.com" &&+ url.hostname !== "oapi.dingtalk.com")+ )+ return false;+ return (+ target.sessionWebhookExpiresAt === null ||+ target.sessionWebhookExpiresAt > Date.now()+ );+ }++ private async getAccessToken(): Promise<string> {+ if (this.accessToken && this.accessToken.expiresAt - 60_000 > Date.now()) {+ return this.accessToken.value;+ }+ const body = await this.postJson(ACCESS_TOKEN_URL, {+ appKey: this.appKey,+ appSecret: this.appSecret,+ });+ const value = stringField(body, "accessToken");+ if (!value) throw new Error("dingtalk access token response is invalid");+ const expiresIn = numberField(body, "expireIn") ?? 7_200;+ this.accessToken = {+ value,+ expiresAt: Date.now() + Math.max(60, expiresIn) * 1_000,+ };+ return value;+ }++ private async postJson(+ url: string,+ body: Record<string, unknown>,+ accessToken?: string,+ ): Promise<unknown> {+ const res = await this.fetchWithTimeout(url, {+ method: "POST",+ redirect: "error",+ headers: {+ "Content-Type": "application/json",+ ...(accessToken ? { "x-acs-dingtalk-access-token": accessToken } : {}),+ },+ body: JSON.stringify(body),+ });+ const payload = (await res.json().catch(() => null)) as unknown;+ if (!res.ok)+ throw new Error(`dingtalk API request failed: HTTP ${res.status}`);+ if (isRecord(payload)) {+ const code = payload.code;+ const legacyCode = payload.errcode;+ if (+ (typeof code === "string" && code && code !== "0") ||+ (typeof code === "number" && code !== 0) ||+ (typeof legacyCode === "string" && legacyCode && legacyCode !== "0") ||+ (typeof legacyCode === "number" && legacyCode !== 0)+ ) {+ throw new Error("dingtalk API request returned an error");+ }+ }+ return payload;+ }++ private async fetchWithTimeout(+ input: Parameters<DingTalkFetch>[0],+ init: Parameters<DingTalkFetch>[1],+ ): Promise<Response> {+ if (this.closed) throw new Error("dingtalk API client is closed");+ const controller = new AbortController();+ this.activeRequests.add(controller);+ const timer = setTimeout(() => controller.abort(), HTTP_TIMEOUT_MS);+ try {+ return await this.fetcher(input, { ...init, signal: controller.signal });+ } finally {+ clearTimeout(timer);+ this.activeRequests.delete(controller);+ }+ }+}++function isAllowedMediaHost(url: URL): boolean {+ if (url.protocol !== "https:") return false;+ const hostname = url.hostname.toLowerCase();+ return (+ hostname === "dingtalk.com" ||+ hostname.endsWith(".dingtalk.com") ||+ hostname === "aliyuncs.com" ||+ hostname.endsWith(".aliyuncs.com") ||+ hostname === "alicdn.com" ||+ hostname.endsWith(".alicdn.com")+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function stringField(value: unknown, key: string): string | null {+ if (!isRecord(value)) return null;+ return typeof value[key] === "string" && value[key] ? value[key] : null;+}++function numberField(value: unknown, key: string): number | null {+ if (!isRecord(value)) return null;+ return typeof value[key] === "number" && Number.isFinite(value[key])+ ? value[key]+ : null;+}++async function readBodyLimited(+ response: Response,+ maxBytes: number,+): Promise<Uint8Array> {+ if (!response.body) return new Uint8Array();+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let total = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > maxBytes) {+ await reader.cancel();+ throw new Error("dingtalk media exceeds the image size limit");+ }+ chunks.push(value);+ }+ } finally {+ reader.releaseLock();+ }+ const output = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ output.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return output;+}++function detectImageMime(bytes: Uint8Array): string | null {+ if (+ bytes.length >= 8 &&+ bytes[0] === 0x89 &&+ bytes[1] === 0x50 &&+ bytes[2] === 0x4e &&+ bytes[3] === 0x47+ ) {+ return "image/png";+ }+ if (+ bytes.length >= 3 &&+ bytes[0] === 0xff &&+ bytes[1] === 0xd8 &&+ bytes[2] === 0xff+ ) {+ return "image/jpeg";+ }+ if (+ bytes.length >= 6 &&+ ["GIF87a", "GIF89a"].includes(String.fromCharCode(...bytes.slice(0, 6)))+ ) {+ return "image/gif";+ }+ if (+ bytes.length >= 12 &&+ String.fromCharCode(...bytes.slice(0, 4)) === "RIFF" &&+ String.fromCharCode(...bytes.slice(8, 12)) === "WEBP"+ ) {+ return "image/webp";+ }+ return null;+}diff --git a/packages/lizi-im/src/dingtalk/codec.ts b/packages/lizi-im/src/dingtalk/codec.tsnew file mode 100644index 0000000000..26996aefd2--- /dev/null+++ b/packages/lizi-im/src/dingtalk/codec.ts@@ -0,0 +1,24 @@+const GROUP_LANE_PREFIX = "g/";++export interface DingTalkLane {+ conversationId: string;+}++export function encodeLaneUserId(conversationId: string): string {+ if (!conversationId || conversationId.includes("\0")) {+ throw new Error("invalid dingtalk conversation id");+ }+ return `${GROUP_LANE_PREFIX}${encodeURIComponent(conversationId)}`;+}++export function decodeLaneUserId(userId: string): DingTalkLane | null {+ if (!userId.startsWith(GROUP_LANE_PREFIX)) return null;+ const encoded = userId.slice(GROUP_LANE_PREFIX.length);+ if (!encoded) return null;+ try {+ const conversationId = decodeURIComponent(encoded);+ return conversationId ? { conversationId } : null;+ } catch {+ return null;+ }+}diff --git a/packages/lizi-im/src/dingtalk/inbound.ts b/packages/lizi-im/src/dingtalk/inbound.tsnew file mode 100644index 0000000000..c4486e515d--- /dev/null+++ b/packages/lizi-im/src/dingtalk/inbound.ts@@ -0,0 +1,227 @@+import type { IMAttachment, IMUnsupportedEntry } from "../types.js";++export interface DingTalkInboundEnvelope {+ conversationId: string;+ conversationType: "1" | "2";+ messageId: string;+ messageType: string;+ robotCode: string;+ senderId: string;+ senderName: string;+ senderStaffId: string;+ sessionWebhook: string | null;+ sessionWebhookExpiresAt: number | null;+ mentioned: boolean;+ raw: Record<string, unknown>;+}++export interface DingTalkInboundContent {+ text: string;+ downloadCodes: string[];+ unsupported: IMUnsupportedEntry[];+}++export function parseInboundEnvelope(+ raw: unknown,+): DingTalkInboundEnvelope | null {+ if (!isRecord(raw)) return null;+ const conversationId = readString(raw, "conversationId");+ const conversationType = readString(raw, "conversationType");+ const messageId = readString(raw, "msgId");+ const messageType = readString(raw, "msgtype");+ const robotCode = readString(raw, "robotCode");+ const senderId = readString(raw, "senderId");+ const senderStaffId = readString(raw, "senderStaffId");+ if (+ !conversationId ||+ (conversationType !== "1" && conversationType !== "2") ||+ !messageId ||+ !messageType ||+ !robotCode ||+ (!senderId && !senderStaffId)+ ) {+ return null;+ }++ return {+ conversationId,+ conversationType,+ messageId,+ messageType,+ robotCode,+ senderId: senderStaffId || senderId,+ senderStaffId,+ senderName: readString(raw, "senderNick") || "钉钉用户",+ sessionWebhook: readString(raw, "sessionWebhook") || null,+ sessionWebhookExpiresAt: normalizeEpochMs(+ readFiniteNumber(raw, "sessionWebhookExpiredTime"),+ ),+ mentioned: isBotMentioned(raw, robotCode),+ raw,+ };+}++export function parseInboundContent(+ envelope: DingTalkInboundEnvelope,+): DingTalkInboundContent {+ const raw = envelope.raw;+ switch (envelope.messageType) {+ case "text":+ return result(readNestedString(raw, "text", "content"));+ case "richText":+ return parseRichText(raw);+ case "picture":+ return {+ text: "",+ downloadCodes: [+ readNestedString(raw, "content", "downloadCode") ||+ readString(raw, "downloadCode"),+ ].filter(Boolean),+ unsupported: [],+ };+ case "audio": {+ const recognition =+ readString(raw, "recognition") ||+ readNestedString(raw, "content", "recognition");+ return recognition+ ? result(recognition)+ : unsupported("audio", "语音(没有可用的文字识别结果)");+ }+ case "video":+ return unsupported("video", "视频");+ case "file":+ return unsupported("file", "文件");+ default:+ return unsupported(+ envelope.messageType,+ `暂不支持的消息类型 ${envelope.messageType}`,+ );+ }+}++export function imageAttachment(+ absPath: string,+ url: string,+ mimeType: string,+): IMAttachment {+ return {+ kind: "image",+ absPath,+ originalName: `dingtalk-image.${extensionForMime(mimeType)}`,+ mimeType,+ url,+ };+}++function result(text: string): DingTalkInboundContent {+ return { text: text.trim(), downloadCodes: [], unsupported: [] };+}++function unsupported(type: string, label: string): DingTalkInboundContent {+ return { text: "", downloadCodes: [], unsupported: [{ type, label }] };+}++function parseRichText(raw: Record<string, unknown>): DingTalkInboundContent {+ const content = isRecord(raw.content) ? raw.content : {};+ const richText = content.richText;+ const parts: string[] = [];+ const downloadCodes: string[] = [];+ visitRichText(richText, parts, downloadCodes);+ return {+ text: parts+ .join("")+ .replace(/\n{3,}/g, "\n\n")+ .trim(),+ downloadCodes: Array.from(new Set(downloadCodes)),+ unsupported: [],+ };+}++function visitRichText(+ value: unknown,+ parts: string[],+ downloadCodes: string[],+): void {+ if (typeof value === "string") {+ parts.push(value);+ return;+ }+ if (Array.isArray(value)) {+ value.forEach((entry, index) => {+ visitRichText(entry, parts, downloadCodes);+ if (index < value.length - 1 && isRecord(entry)) parts.push("\n");+ });+ return;+ }+ if (!isRecord(value)) return;+ const type = readString(value, "type");+ const downloadCode =+ readString(value, "downloadCode") ||+ (type === "picture" ? readString(value, "pictureUrl") : "");+ if (downloadCode) downloadCodes.push(downloadCode);+ for (const key of ["text", "content", "title"]) {+ if (typeof value[key] === "string") parts.push(value[key] as string);+ }+ for (const key of ["richText", "children", "items"]) {+ if (value[key] !== undefined)+ visitRichText(value[key], parts, downloadCodes);+ }+}++function isBotMentioned(+ raw: Record<string, unknown>,+ robotCode: string,+): boolean {+ if (raw.isInAtList === true) return true;+ const atUsers = raw.atUsers;+ if (!Array.isArray(atUsers)) return false;+ return atUsers.some((entry) => {+ if (!isRecord(entry)) return false;+ return Object.values(entry).some((value) => value === robotCode);+ });+}++function extensionForMime(mimeType: string): string {+ switch (mimeType) {+ case "image/jpeg":+ return "jpg";+ case "image/webp":+ return "webp";+ case "image/gif":+ return "gif";+ default:+ return "png";+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function readString(value: Record<string, unknown>, key: string): string {+ return typeof value[key] === "string" ? (value[key] as string).trim() : "";+}++function readNestedString(+ value: Record<string, unknown>,+ parent: string,+ key: string,+): string {+ return isRecord(value[parent])+ ? readString(value[parent] as Record<string, unknown>, key)+ : "";+}++function readFiniteNumber(+ value: Record<string, unknown>,+ key: string,+): number | null {+ return typeof value[key] === "number" && Number.isFinite(value[key])+ ? (value[key] as number)+ : null;+}++function normalizeEpochMs(value: number | null): number | null {+ if (value === null) return null;+ return value < 1_000_000_000_000 ? value * 1_000 : value;+}diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.tsnew file mode 100644index 0000000000..6cf741a203--- /dev/null+++ b/packages/lizi-im/src/dingtalk/index.ts@@ -0,0 +1,764 @@+import {+ DWClient,+ TOPIC_ROBOT,+ type DWClientDownStream,+} from "dingtalk-stream";++import { BaseIM } from "../BaseIM.js";+import type { ChannelIM, ImFinalOutput } from "../channelIM.js";+import type {+ IMCardActionEvent,+ IMHost,+ IMMessageEvent,+ IMStatus,+ InteractiveCardSpec,+ SendFileResult,+ StreamingTextHandle,+} from "../types.js";+import {+ DingTalkApiClient,+ type DingTalkFetch,+ type DingTalkOutboundTarget,+} from "./api.js";+import { decodeLaneUserId, encodeLaneUserId } from "./codec.js";+import {+ imageAttachment,+ parseInboundContent,+ parseInboundEnvelope,+ type DingTalkInboundEnvelope,+} from "./inbound.js";++const APP_KEY_SECRET = "dingtalk-bot-app-key";+const APP_SECRET_SECRET = "dingtalk-bot-app-secret";+const OWNER_USER_ID_SECRET = "dingtalk-bot-owner-user-id";+const DEDUP_TTL_MS = 5 * 60 * 1_000;+const DEDUP_CAPACITY = 2_048;+const STATUS_POLL_MS = 2_000;+const INTERACTION_TIMEOUT_MS = 30 * 60 * 1_000;+const OUTBOUND_CHUNK_SIZE = 3_500;+const REGISTRATION_TIMEOUT_MS = 10_000;++type MessageHandler = (event: IMMessageEvent) => void;+type StatusHandler = (status: IMStatus) => void;++export interface DingTalkStreamClient {+ readonly connected: boolean;+ readonly registered: boolean;+ readonly config: { autoReconnect?: boolean };+ registerCallbackListener(+ topic: string,+ callback: (message: DWClientDownStream) => void,+ ): DingTalkStreamClient;+ connect(): Promise<void>;+ disconnect(): void;+ socketCallBackResponse(messageId: string, result: unknown): void;+}++export interface DingTalkIMOptions {+ fetcher?: DingTalkFetch;+ clientFactory?: (credentials: {+ appKey: string;+ appSecret: string;+ }) => DingTalkStreamClient;+}++export interface DingTalkPublicState {+ status: IMStatus;+ appKey: string | null;+ hasSecret: boolean;+ ownerUserId: string | null;+}++interface Credentials {+ appKey: string;+ appSecret: string;+}++interface PendingReply<T = unknown> {+ parse(text: string): T | null;+ resolve(value: T): void;+ reject(error: Error): void;+ timer: ReturnType<typeof setTimeout>;+}++export class DingTalkIM extends BaseIM implements ChannelIM {+ private readonly messageHandlers = new Set<MessageHandler>();+ private readonly statusHandlers = new Set<StatusHandler>();+ private readonly targetByUserId = new Map<string, DingTalkOutboundTarget>();+ private readonly laneQueues = new Map<string, Promise<void>>();+ private readonly seenMessageIds = new Map<string, number>();+ private readonly pendingReplies = new Map<string, PendingReply>();++ private status: IMStatus = { kind: "idle" };+ private client: DingTalkStreamClient | null = null;+ private api: DingTalkApiClient | null = null;+ private appKey = "";+ private ownerUserId = "";+ private connectionVersion = 0;+ private statusTimer: ReturnType<typeof setInterval> | null = null;++ constructor(+ host: IMHost,+ private readonly options: DingTalkIMOptions = {},+ ) {+ super("dingtalk", host);+ }++ async init(): Promise<void> {+ const credentials = this.readCredentials();+ this.ownerUserId =+ this.host.secrets.read(OWNER_USER_ID_SECRET)?.trim() ?? "";+ if (!credentials) {+ this.setStatus({ kind: "idle" });+ return;+ }+ try {+ await this.connect(credentials);+ } catch (error) {+ this.setStatus({+ kind: "error",+ reason: safeConnectionError(error),+ });+ }+ }++ async dispose(): Promise<void> {+ this.connectionVersion += 1;+ this.stopStatusMonitor();+ this.client?.disconnect();+ this.client = null;+ this.api?.close();+ this.api = null;+ this.targetByUserId.clear();+ this.laneQueues.clear();+ this.seenMessageIds.clear();+ this.rejectPendingReplies("DINGTALK_DISCONNECTED");+ this.setStatus({ kind: "idle" });+ }++ registerIpc(): void {+ this.host.ipc.handle("dingtalkBot:get-state", () => this.getPublicState());+ this.host.ipc.handle("dingtalkBot:save", async (payload) => {+ const record = isRecord(payload) ? payload : {};+ const appKey =+ typeof record.appKey === "string" ? record.appKey.trim() : "";+ const appSecret =+ typeof record.appSecret === "string" ? record.appSecret.trim() : "";+ if (+ !appKey ||+ !appSecret ||+ appKey.length > 256 ||+ appSecret.length > 512+ ) {+ throw new Error("[INVALID_PAYLOAD] appKey and appSecret required");+ }+ return this.runInAccountScope(() =>+ this.saveAndConnect({ appKey, appSecret }),+ );+ });+ this.host.ipc.handle("dingtalkBot:reconnect", async () => {+ return this.runInAccountScope(async () => {+ const credentials = this.readCredentials();+ if (!credentials) throw new Error("DINGTALK_CREDENTIALS_MISSING");+ await this.connect(credentials);+ return this.getPublicState();+ });+ });+ this.host.ipc.handle("dingtalkBot:clear", async () => {+ await this.clearAndDisconnect();+ return { ok: true };+ });+ }++ onMessage(handler: MessageHandler): () => void {+ this.messageHandlers.add(handler);+ return () => this.messageHandlers.delete(handler);+ }++ onStatusChange(handler: StatusHandler): () => void {+ this.statusHandlers.add(handler);+ return () => this.statusHandlers.delete(handler);+ }++ onCardAction(handler: (event: IMCardActionEvent) => void): () => void {+ void handler;+ return () => undefined;+ }++ getStatus(): IMStatus {+ return this.status;+ }++ getPublicState(): DingTalkPublicState {+ const credentials = this.readCredentials();+ return {+ status: this.status,+ appKey: credentials?.appKey ?? null,+ hasSecret: Boolean(credentials),+ ownerUserId: this.host.secrets.read(OWNER_USER_ID_SECRET)?.trim() || null,+ };+ }++ async sendText(userId: string, text: string): Promise<{ messageId: string }> {+ const api = this.requireApi();+ const target = this.resolveTarget(userId);+ const chunks = chunkText(text);+ for (const chunk of chunks) {+ await api.sendText(target, chunk);+ }+ return { messageId: `out:${Date.now().toString(36)}` };+ }++ sendMarkdownText(+ userId: string,+ markdown: string,+ ): Promise<{ messageId: string }> {+ return this.sendText(userId, markdown);+ }++ async sendFile(+ _userId: string,+ _absPath: string,+ _displayName?: string,+ ): Promise<SendFileResult> {+ return { ok: false, reason: "SEND_FAIL" };+ }++ sendInteractiveCard(+ _userId: string,+ _spec: InteractiveCardSpec,+ ): Promise<{ messageId: string }> {+ return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));+ }++ updateInteractiveCard(+ _messageId: string,+ _spec: InteractiveCardSpec,+ ): Promise<void> {+ return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));+ }++ patchMarkdownCard(_messageId: string, _markdown: string): Promise<void> {+ return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));+ }++ startStreamingText(+ _userId: string,+ _initial?: string,+ _opts?: { threadTs?: string },+ ): Promise<StreamingTextHandle> {+ return Promise.reject(new Error("DINGTALK_RICH_OUTPUT_UNSUPPORTED"));+ }++ async commitFinal(output: ImFinalOutput): Promise<void> {+ await this.sendText(output.userId, normalizeFinalText(output.text));+ }++ async requestTextReply<T>(+ userId: string,+ prompt: string,+ parse: (text: string) => T | null,+ timeoutMs = INTERACTION_TIMEOUT_MS,+ ): Promise<T> {+ if (this.pendingReplies.has(userId)) {+ throw new Error("DINGTALK_INTERACTION_ALREADY_PENDING");+ }+ let resolveReply!: (value: T) => void;+ let rejectReply!: (error: Error) => void;+ const reply = new Promise<T>((resolve, reject) => {+ resolveReply = resolve;+ rejectReply = reject;+ });+ const timer = setTimeout(() => {+ this.pendingReplies.delete(userId);+ rejectReply(new Error("DINGTALK_INTERACTION_TIMEOUT"));+ }, timeoutMs);+ const pending: PendingReply<T> = {+ parse,+ resolve: resolveReply,+ reject: rejectReply,+ timer,+ };+ this.pendingReplies.set(userId, pending as PendingReply);+ try {+ await this.sendText(userId, prompt);+ } catch (error) {+ if (this.pendingReplies.get(userId) === pending) {+ this.pendingReplies.delete(userId);+ }+ clearTimeout(pending.timer);+ throw error;+ }+ return reply;+ }++ private async saveAndConnect(+ credentials: Credentials,+ ): Promise<DingTalkPublicState> {+ if (!this.host.secrets.isAvailable()) {+ throw new Error("DINGTALK_SECURE_STORAGE_UNAVAILABLE");+ }++ const previous = this.readCredentials();+ const previousOwner = this.host.secrets.read(OWNER_USER_ID_SECRET);+ try {+ await this.connect(credentials);+ if (!this.writeCredentials(credentials)) {+ throw new Error("DINGTALK_CREDENTIAL_SAVE_FAILED");+ }+ if (previous?.appKey !== credentials.appKey) {+ this.host.secrets.remove(OWNER_USER_ID_SECRET);+ this.ownerUserId = "";+ }+ return this.getPublicState();+ } catch (error) {+ this.restoreSecret(APP_KEY_SECRET, previous?.appKey ?? null);+ this.restoreSecret(APP_SECRET_SECRET, previous?.appSecret ?? null);+ this.restoreSecret(OWNER_USER_ID_SECRET, previousOwner);+ this.ownerUserId = previousOwner?.trim() ?? "";+ if (previous) {+ try {+ await this.connect(previous);+ } catch {+ // The original error is more useful to the Settings surface.+ }+ } else {+ await this.stopConnection();+ this.setStatus({ kind: "idle" });+ }+ throw error;+ }+ }++ private async clearAndDisconnect(): Promise<void> {+ await this.stopConnection();+ this.host.secrets.remove(APP_KEY_SECRET);+ this.host.secrets.remove(APP_SECRET_SECRET);+ this.host.secrets.remove(OWNER_USER_ID_SECRET);+ this.ownerUserId = "";+ this.targetByUserId.clear();+ this.seenMessageIds.clear();+ this.rejectPendingReplies("DINGTALK_CREDENTIALS_CLEARED");+ this.setStatus({ kind: "idle" });+ }++ private async connect(credentials: Credentials): Promise<void> {+ await this.stopConnection();+ const version = this.connectionVersion;+ this.setStatus({ kind: "connecting" });+ const client = (this.options.clientFactory ?? defaultClientFactory)(+ credentials,+ );+ client.config.autoReconnect = false;+ client.registerCallbackListener(TOPIC_ROBOT, (message) => {+ this.ackDownstream(client, message);+ if (version !== this.connectionVersion) return;+ const accountToken = this.host.accountScope?.capture();+ if (this.host.accountScope && accountToken === null) return;+ void this.acceptDownstream(message, version, accountToken);+ });+ await client.connect();+ if (version !== this.connectionVersion) {+ client.disconnect();+ throw new Error("DINGTALK_CONNECTION_REPLACED");+ }+ if (!client.connected || !(await waitForRegistration(client))) {+ client.disconnect();+ throw new Error("DINGTALK_CONNECTION_FAILED");+ }+ client.config.autoReconnect = true;+ this.client = client;+ this.appKey = credentials.appKey;+ this.api = new DingTalkApiClient(+ credentials.appKey,+ credentials.appSecret,+ this.options.fetcher,+ );+ this.setStatus({ kind: "connected", appId: credentials.appKey });+ this.startStatusMonitor(version);+ }++ private async stopConnection(): Promise<void> {+ this.connectionVersion += 1;+ this.stopStatusMonitor();+ const client = this.client;+ this.client = null;+ this.api?.close();+ this.api = null;+ client?.disconnect();+ this.targetByUserId.clear();+ this.laneQueues.clear();+ this.seenMessageIds.clear();+ this.rejectPendingReplies("DINGTALK_CONNECTION_REPLACED");+ }++ private startStatusMonitor(version: number): void {+ this.stopStatusMonitor();+ this.statusTimer = setInterval(() => {+ if (version !== this.connectionVersion || !this.client) return;+ if (this.client.connected && this.client.registered) {+ if (this.status.kind !== "connected") {+ this.setStatus({ kind: "connected", appId: this.appKey });+ }+ } else if (this.status.kind === "connected") {+ this.setStatus({ kind: "connecting" });+ }+ }, STATUS_POLL_MS);+ }++ private stopStatusMonitor(): void {+ if (this.statusTimer) clearInterval(this.statusTimer);+ this.statusTimer = null;+ }++ private ackDownstream(+ client: DingTalkStreamClient,+ message: DWClientDownStream,+ ): void {+ try {+ client.socketCallBackResponse(message.headers.messageId, {+ success: true,+ });+ } catch (error) {+ this.log.warn(+ `dingtalk callback acknowledgement failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ }++ private async acceptDownstream(+ message: DWClientDownStream,+ connectionVersion: number,+ accountToken: unknown,+ ): Promise<void> {+ let raw: unknown;+ try {+ raw = JSON.parse(message.data);+ } catch {+ this.log.warn("dingtalk callback contained invalid JSON");+ return;+ }+ const envelope = parseInboundEnvelope(raw);+ if (!envelope || envelope.robotCode !== this.appKey) return;+ if (this.isDuplicate(envelope.messageId)) return;++ const userId =+ envelope.conversationType === "2"+ ? encodeLaneUserId(envelope.conversationId)+ : envelope.senderId;+ this.rememberTarget(userId, envelope);+ const prior = this.laneQueues.get(userId) ?? Promise.resolve();+ const next = prior+ .catch(() => undefined)+ .then(() =>+ this.runInCapturedAccountScope(accountToken, () =>+ this.processEnvelope(userId, envelope, connectionVersion),+ ),+ )+ .catch((error) => {+ this.log.warn(+ `dingtalk inbound processing failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ })+ .finally(() => {+ if (this.laneQueues.get(userId) === next)+ this.laneQueues.delete(userId);+ });+ this.laneQueues.set(userId, next);+ await next;+ }++ private async processEnvelope(+ userId: string,+ envelope: DingTalkInboundEnvelope,+ connectionVersion: number,+ ): Promise<void> {+ if (connectionVersion !== this.connectionVersion) return;+ const isGroup = envelope.conversationType === "2";+ if (!this.ownerUserId) {+ if (isGroup || !this.claimOwner(envelope.senderId)) return;+ }+ if (!isGroup && envelope.senderId !== this.ownerUserId) return;+ if (isGroup && !envelope.mentioned) return;++ const content = parseInboundContent(envelope);+ if (+ content.text &&+ this.tryResolvePendingReply(userId, envelope.senderId, content.text)+ ) {+ return;+ }++ const attachments = [];+ const unsupported = [...content.unsupported];+ for (const downloadCode of content.downloadCodes) {+ const attachment = await this.resolveImage(+ downloadCode,+ connectionVersion,+ ).catch((error) => {+ this.log.warn(+ `dingtalk image download failed: ${error instanceof Error ? error.message : String(error)}`,+ );+ return null;+ });+ if (attachment) attachments.push(attachment);+ else unsupported.push({ type: "picture", label: "图片(下载失败)" });+ }+ if (connectionVersion !== this.connectionVersion) return;++ const event: IMMessageEvent = {+ channelName: "dingtalk",+ senderId: userId,+ chatId: envelope.conversationId,+ contextId: this.appKey,+ messageId: envelope.messageId,+ text: content.text,+ ...(isGroup+ ? {+ speaker: {+ id: envelope.senderId,+ name: envelope.senderName,+ isOwner: envelope.senderId === this.ownerUserId,+ },+ }+ : {}),+ attachments,+ unsupported,+ };+ for (const handler of this.messageHandlers) {+ try {+ handler(event);+ } catch {+ // One consumer must not prevent the remaining subscribers from receiving the message.+ }+ }+ }++ private async resolveImage(downloadCode: string, connectionVersion: number) {+ if (connectionVersion !== this.connectionVersion) return null;+ const media = this.host.media;+ if (!media) return null;+ const cached = await media.getCachedImage("dingtalk", downloadCode);+ if (connectionVersion !== this.connectionVersion) return null;+ if (cached) {+ return imageAttachment(cached.absPath, cached.url, cached.mimeType);+ }+ const downloaded = await this.requireApi().downloadImage(downloadCode);+ if (connectionVersion !== this.connectionVersion) return null;+ const stored = await media.cacheImage({+ integration: "dingtalk",+ token: downloadCode,+ buffer: downloaded.buffer,+ mimeType: downloaded.mimeType,+ });+ return imageAttachment(stored.absPath, stored.url, downloaded.mimeType);+ }++ private tryResolvePendingReply(+ userId: string,+ senderId: string,+ text: string,+ ): boolean {+ const pending = this.pendingReplies.get(userId);+ if (!pending) return false;+ const lane = decodeLaneUserId(userId);+ if (lane && senderId !== this.ownerUserId) return true;+ const value = pending.parse(text);+ if (value === null) return true;+ this.pendingReplies.delete(userId);+ clearTimeout(pending.timer);+ pending.resolve(value);+ return true;+ }++ private claimOwner(senderId: string): boolean {+ if (!this.host.secrets.isAvailable()) return false;+ if (!this.host.secrets.write(OWNER_USER_ID_SECRET, senderId)) return false;+ this.ownerUserId = senderId;+ this.host.ipc.broadcast("dingtalkBot:owner-change", {+ ownerUserId: senderId,+ });+ return true;+ }++ private rememberTarget(+ userId: string,+ envelope: DingTalkInboundEnvelope,+ ): void {+ this.targetByUserId.set(userId, {+ kind: envelope.conversationType === "2" ? "group" : "direct",+ id:+ envelope.conversationType === "2"+ ? envelope.conversationId+ : envelope.senderId,+ sessionWebhook: envelope.sessionWebhook,+ sessionWebhookExpiresAt: envelope.sessionWebhookExpiresAt,+ });+ }++ private resolveTarget(userId: string): DingTalkOutboundTarget {+ const cached = this.targetByUserId.get(userId);+ if (cached) return cached;+ const lane = decodeLaneUserId(userId);+ return lane+ ? {+ kind: "group",+ id: lane.conversationId,+ sessionWebhook: null,+ sessionWebhookExpiresAt: null,+ }+ : {+ kind: "direct",+ id: userId,+ sessionWebhook: null,+ sessionWebhookExpiresAt: null,+ };+ }++ private isDuplicate(messageId: string): boolean {+ const now = Date.now();+ for (const [id, seenAt] of this.seenMessageIds) {+ if (now - seenAt > DEDUP_TTL_MS) this.seenMessageIds.delete(id);+ }+ if (this.seenMessageIds.has(messageId)) return true;+ this.seenMessageIds.set(messageId, now);+ while (this.seenMessageIds.size > DEDUP_CAPACITY) {+ const oldest = this.seenMessageIds.keys().next().value;+ if (!oldest) break;+ this.seenMessageIds.delete(oldest);+ }+ return false;+ }++ private setStatus(status: IMStatus): void {+ this.status = status;+ this.host.ipc.broadcast("dingtalkBot:status-change", { status });+ for (const handler of this.statusHandlers) {+ try {+ handler(status);+ } catch {+ // Status fan-out is best effort.+ }+ }+ }++ private readCredentials(): Credentials | null {+ const appKey = this.host.secrets.read(APP_KEY_SECRET)?.trim() ?? "";+ const appSecret = this.host.secrets.read(APP_SECRET_SECRET)?.trim() ?? "";+ return appKey && appSecret ? { appKey, appSecret } : null;+ }++ private writeCredentials(credentials: Credentials): boolean {+ const previousKey = this.host.secrets.read(APP_KEY_SECRET);+ const previousSecret = this.host.secrets.read(APP_SECRET_SECRET);+ if (!this.host.secrets.write(APP_KEY_SECRET, credentials.appKey))+ return false;+ if (this.host.secrets.write(APP_SECRET_SECRET, credentials.appSecret))+ return true;+ this.restoreSecret(APP_KEY_SECRET, previousKey);+ this.restoreSecret(APP_SECRET_SECRET, previousSecret);+ return false;+ }++ private restoreSecret(key: string, value: string | null): void {+ if (value === null) this.host.secrets.remove(key);+ else this.host.secrets.write(key, value);+ }++ private requireApi(): DingTalkApiClient {+ if (!this.api) throw new Error("DINGTALK_NOT_CONNECTED");+ return this.api;+ }++ private rejectPendingReplies(code: string): void {+ for (const pending of this.pendingReplies.values()) {+ clearTimeout(pending.timer);+ pending.reject(new Error(code));+ }+ this.pendingReplies.clear();+ }++ private async runInAccountScope<T>(operation: () => Promise<T>): Promise<T> {+ const scope = this.host.accountScope;+ if (!scope) return operation();+ const token = scope.capture();+ if (token === null)+ throw new Error("[IM_NOT_READY] IM account is not active");+ return scope.run(token, operation);+ }++ private async runInCapturedAccountScope<T>(+ token: unknown,+ operation: () => Promise<T>,+ ): Promise<T> {+ const scope = this.host.accountScope;+ if (!scope) return operation();+ if (token === null || !scope.isCurrent(token)) {+ throw new Error("[IM_NOT_READY] IM account changed");+ }+ return scope.run(token, operation);+ }+}++export function createDingTalkIM(+ host: IMHost,+ options?: DingTalkIMOptions,+): DingTalkIM {+ return new DingTalkIM(host, options);+}++function defaultClientFactory(credentials: Credentials): DingTalkStreamClient {+ return new DWClient({+ clientId: credentials.appKey,+ clientSecret: credentials.appSecret,+ keepAlive: true,+ debug: false,+ });+}++function chunkText(text: string): string[] {+ const normalized = text.trim() || "(空回复)";+ const chunks: string[] = [];+ let remaining = normalized;+ while (remaining.length > OUTBOUND_CHUNK_SIZE) {+ let splitAt = remaining.lastIndexOf("\n", OUTBOUND_CHUNK_SIZE);+ if (splitAt < OUTBOUND_CHUNK_SIZE / 2) splitAt = OUTBOUND_CHUNK_SIZE;+ if (+ splitAt > 0 &&+ /[\uD800-\uDBFF]/.test(remaining[splitAt - 1] ?? "") &&+ /[\uDC00-\uDFFF]/.test(remaining[splitAt] ?? "")+ ) {+ splitAt -= 1;+ }+ chunks.push(remaining.slice(0, splitAt));+ remaining = remaining.slice(splitAt).replace(/^\n+/, "");+ }+ if (remaining) chunks.push(remaining);+ return chunks;+}++function normalizeFinalText(text: string): string {+ return text.trim() || "✅ 本轮已完成,没有文本输出。";+}++function safeConnectionError(error: unknown): string {+ const message = error instanceof Error ? error.message : String(error);+ if (message === "DINGTALK_CONNECTION_FAILED") {+ return "DINGTALK_CONNECTION_FAILED";+ }+ return "DINGTALK_CONNECTION_ERROR";+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++async function waitForRegistration(+ client: DingTalkStreamClient,+): Promise<boolean> {+ const deadline = Date.now() + REGISTRATION_TIMEOUT_MS;+ while (client.connected && !client.registered && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ return client.connected && client.registered;+}diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.tsindex db58804dc0..31f83f1a32 100644--- a/packages/lizi-im/src/index.ts+++ b/packages/lizi-im/src/index.ts@@ -49,6 +49,17 @@ export {decodeMessageId as decodeTelegramMessageId,} from './telegram/codec.js';+export { DingTalkIM, createDingTalkIM } from './dingtalk/index.js';+export type {+ DingTalkIMOptions,+ DingTalkPublicState,+ DingTalkStreamClient,+} from './dingtalk/index.js';+export {+ decodeLaneUserId as decodeDingTalkLaneUserId,+ encodeLaneUserId as encodeDingTalkLaneUserId,+} from './dingtalk/codec.js';+export type {IdentityKey,BindingStore,diff --git a/packages/lizi-im/src/types.ts b/packages/lizi-im/src/types.tsindex 58c6f9b9c6..5f19cb86a8 100644--- a/packages/lizi-im/src/types.ts+++ b/packages/lizi-im/src/types.ts@@ -85,7 +85,7 @@ export interface IMHost {export interface IMHostMediaCache {/** 图片字节入 host 总仓;返回仓内绝对路径(喂 agent)+ 渲染 URL(cindy-media://)。 */cacheImage(params: {- integration: 'feishu' | 'discord' | 'telegram';+ integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk';/** 平台侧稳定 token(feishu image_key / discord attachment id / telegram file_id),host 据此免重下。 */token: string;buffer: Uint8Array;@@ -93,7 +93,7 @@ export interface IMHostMediaCache {}): Promise<{ absPath: string; url: string }>;/** 按 token 查已缓存图片;未缓存返回 null(调用方去真下载)。 */getCachedImage(- integration: 'feishu' | 'discord' | 'telegram',+ integration: 'feishu' | 'discord' | 'telegram' | 'dingtalk',token: string,): Promise<{ absPath: string; url: string; mimeType: string } | null>;/** host 托管媒体 URL(cindy-media://)→ 绝对路径;认不出返回 null(出站上传用)。 */diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex cb08740fcb..6fd5f8c379 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -821,7 +821,7 @@ export interface SendOptions {export type TurnPermissionOrigin =| { kind: 'desktop' }- | { kind: 'im'; channel: 'feishu' | 'discord' | 'slack' | 'wechat' | 'telegram'; taskId?: string }+ | { kind: 'im'; channel: 'feishu' | 'discord' | 'slack' | 'wechat' | 'telegram' | 'dingtalk'; taskId?: string }| { kind: 'scheduler' }| { kind: 'hook'; source: string };diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0d844d5ddd..2dee487891 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -958,6 +958,9 @@ importers:'@larksuiteoapi/node-sdk':specifier: ^1.60.0version: 1.71.1+ dingtalk-stream:+ specifier: ^2.1.5+ version: 2.1.5discord.js:specifier: ^14.16.0version: 14.27.0@@ -5887,6 +5890,9 @@ packages:resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==}+ resolution: {integrity: sha512-6H3tSc/mE6hMj4RBB5ntkI4ycC498RobmtMxfLS8eBTRPjBZlhUdDYEHA0asOoTLSzC2PHqupr4D4HVoaU7bRQ==}+resolution: {integrity: sha512-J7/et3WlGUCxjdnD3HAAzQ6nsnc0WL6DD7WcwJb7c39iH1+AWfg+9OqzJNaI6PkBwBvm1mhZNL9iY/nRiZXlPg==}@@ -12699,7 +12705,7 @@ snapshots:'@larksuiteoapi/[email protected]':dependencies:- axios: 1.18.1+ axios: 1.18.1([email protected])lodash.identity: 3.0.0lodash.merge: 4.6.2lodash.pickby: 4.6.0@@ -14876,9 +14882,9 @@ snapshots:postcss: 8.5.19postcss-value-parser: 4.2.0dependencies:- follow-redirects: 1.16.0+ follow-redirects: 1.16.0([email protected])form-data: 4.0.6https-proxy-agent: 5.0.1proxy-from-env: 2.1.0@@ -15832,6 +15838,16 @@ snapshots:+ dependencies:+ axios: 1.18.1([email protected])+ debug: 4.4.3+ ws: 8.21.1+ transitivePeerDependencies:+ - bufferutil+ - supports-color+ - utf-8-validate+dependencies:buffer-equal: 1.0.1@@ -16953,7 +16969,9 @@ snapshots:- [email protected]: {}+ optionalDependencies:+ debug: 4.4.3