Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(datasource): add Tencent IMA datasource
joeyczheng664d193ca7b0
diff --git a/frontend/src/assets/img/datasource-ima.png b/frontend/src/assets/img/datasource-ima.pngnew file mode 100644index 000000000..8e70f2f5aBinary files /dev/null and b/frontend/src/assets/img/datasource-ima.png differdiff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vueindex f2f52f741..dbf7963b4 100644--- a/frontend/src/components/doc-content.vue+++ b/frontend/src/components/doc-content.vue@@ -936,6 +936,7 @@ const channelLabelMap: Record<string, string> = {dingtalk: 'knowledgeBase.channelDingtalk',slack: 'knowledgeBase.channelSlack',im: 'knowledgeBase.channelIm',+ ima: 'knowledgeBase.channelIma',};const getChannelLabel = (channel: string) => {diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 8e981a89b..99bdea59b 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -466,6 +466,7 @@ export default {channelIm: 'IM Channel',channelNotion: 'Notion',channelYuque: 'Yuque',+ channelIma: 'Tencent IMA',channelUpload: 'Upload',channelManual: 'Manual',channelUrl: 'Web',@@ -5475,6 +5476,7 @@ export default {lark_drive: 'Lark Drive',notion: 'Notion',yuque: 'Yuque',+ ima: 'Tencent IMA',rss: 'RSS / Atom Feed'},connectorDesc: {@@ -5484,6 +5486,7 @@ export default {lark_drive: 'Sync documents, spreadsheets and files from a Lark Drive folder (Feishu international)',notion: 'Sync pages and databases from Notion',yuque: 'Sync documents from Yuque knowledge bases',+ ima: 'Sync documents, notes and files from Tencent IMA knowledge bases',rss: 'Sync articles from RSS / Atom feeds'},drive: {@@ -5504,6 +5507,8 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ imaClientId: 'IMA ClientID',+ imaApiKey: 'IMA APIKey',baseUrl: 'Base URL (optional)',baseUrlHint: 'Leave empty to use the default public cloud address. For private/enterprise deployments or when accessing via reverse proxy, enter your custom address (e.g. https://api-proxy.example.com).',feedUrls: 'Feed URLs',@@ -5547,6 +5552,14 @@ export default {prereqStep3Brief_lark_drive: 'Configure app permissions',prereqStep3Desc_lark_drive: 'Enable drive:drive:readonly, drive:export:readonly, docx:document:readonly permissions',prereqOpenConsole_yuque: 'Open Yuque Token settings',+ prereqBarText_ima: 'First time? Click to see the Tencent IMA OpenAPI setup guide',+ prereqStep1Brief_ima: 'Enable IMA agent OpenAPI access',+ prereqStep1Desc_ima: 'Sign in to https://ima.qq.com/agent-interface and apply for OpenAPI access',+ prereqStep2Brief_ima: 'Obtain the ClientID and APIKey',+ prereqStep2Desc_ima: 'Copy the ima-openapi-clientid and ima-openapi-apikey credentials from the agent-interface page',+ prereqStep3Brief_ima: 'Grant the credential access to the target knowledge bases',+ prereqStep3Desc_ima: 'In the IMA client, authorize the credential for the knowledge bases you want to sync; unauthorized bases will not appear in the list',+ prereqOpenConsole_ima: 'Open Tencent IMA OpenAPI console',prereqBotBrief: 'Add "Bot" capability to your app',prereqBotDesc: 'Open Platform > Add App Capability > Bot > create version and publish',prereqPermBrief: 'Grant API permissions',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex d60272edc..796cbf9ff 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -644,6 +644,14 @@ export default {prereqStep3Brief_lark_drive: "앱 권한 구성",prereqStep3Desc_lark_drive: "drive:drive:readonly, drive:export:readonly, docx:document:readonly 권한 활성화",prereqOpenConsole_yuque: 'Yuque Token 설정으로 이동',+ prereqBarText_ima: '처음 사용하시나요? 클릭하여 Tencent IMA OpenAPI 설정 가이드를 확인하세요',+ prereqStep1Brief_ima: 'IMA 에이전트 OpenAPI 액세스 활성화',+ prereqStep1Desc_ima: 'https://ima.qq.com/agent-interface 에 로그인하여 OpenAPI 액세스를 신청하세요',+ prereqStep2Brief_ima: 'ClientID 및 APIKey 획득',+ prereqStep2Desc_ima: '에이전트 접속 페이지에서 ima-openapi-clientid 와 ima-openapi-apikey 자격 증명을 복사하세요',+ prereqStep3Brief_ima: '대상 지식베이스에 자격 증명 권한 부여',+ prereqStep3Desc_ima: 'IMA 클라이언트에서 동기화하려는 지식베이스에 대해 자격 증명을 승인하세요. 승인되지 않은 지식베이스는 목록에 나타나지 않습니다',+ prereqOpenConsole_ima: 'Tencent IMA OpenAPI 콘솔로 이동',prereqBotBrief: '앱에 \'봇\' 기능 추가',prereqBotDesc: '오픈 플랫폼 → 앱 기능 추가 → 봇 → 버전 생성 후 게시',prereqPermBrief: 'API 권한 활성화',@@ -680,6 +688,8 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ imaClientId: 'IMA ClientID',+ imaApiKey: 'IMA APIKey',baseUrl: 'Base URL',baseUrlHint: "비워두면 기본 퍼블릭 클라우드 주소가 사용됩니다. 프라이빗/엔터프라이즈 배포거나 리버스 프록시를 통해 액세스해야 하는 경우 사용자 정의 주소를 입력하세요 (예: https://api-proxy.example.com)",feedUrls: '피드 주소',@@ -694,6 +704,7 @@ export default {lark_drive: "Lark 드라이브 폴더에서 문서, 스프레드시트, 파일 동기화",notion: 'Notion에서 페이지 및 데이터베이스 동기화',yuque: '위큐 지식베이스에서 문서 동기화',+ ima: 'Tencent IMA 지식베이스에서 문서, 노트 및 파일 동기화',rss: 'RSS / Atom 피드에서 글 동기화'},connector: {@@ -703,6 +714,7 @@ export default {lark_drive: "Lark 드라이브",notion: 'Notion',yuque: '위큐 (Yuque)',+ ima: 'Tencent IMA',rss: 'RSS / Atom 피드'},logDetail: {@@ -5588,6 +5600,7 @@ export default {channelIm: 'IM 채널',channelNotion: 'Notion',channelYuque: 'Yuque',+ channelIma: 'Tencent IMA',channelUpload: '업로드',channelManual: '수동',channelUrl: '웹',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex d8b6569da..a19624b8f 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -620,6 +620,14 @@ export default {prereqStep3Brief_yuque: '(Опционально) Для Enterprise укажите Base URL',prereqStep3Desc_yuque: 'Пользователям публичного облака указывать не нужно. Для Yuque Enterprise или приватного развёртывания укажите корпоративный домен',prereqOpenConsole_yuque: 'Перейти к настройкам Yuque Token',+ prereqBarText_ima: 'В первый раз? Нажмите, чтобы увидеть руководство по настройке Tencent IMA OpenAPI',+ prereqStep1Brief_ima: 'Включите доступ к IMA agent OpenAPI',+ prereqStep1Desc_ima: 'Войдите на https://ima.qq.com/agent-interface и подайте заявку на доступ к OpenAPI',+ prereqStep2Brief_ima: 'Получите ClientID и APIKey',+ prereqStep2Desc_ima: 'Скопируйте учётные данные ima-openapi-clientid и ima-openapi-apikey на странице agent-interface',+ prereqStep3Brief_ima: 'Предоставьте учётным данным доступ к целевым базам знаний',+ prereqStep3Desc_ima: 'В клиенте IMA авторизуйте учётные данные для баз знаний, которые нужно синхронизировать; неавторизованные базы в списке не отобразятся',+ prereqOpenConsole_ima: 'Открыть консоль Tencent IMA OpenAPI',prereqStep1Brief_feishu: 'Создать частное приложение Feishu',prereqStep1Desc_feishu: 'Войдите в Feishu Open Platform → Создать корпоративное частное приложение',prereqStep2Brief_feishu: 'Добавить возможность бота',@@ -680,6 +688,8 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ imaClientId: 'IMA ClientID',+ imaApiKey: 'IMA APIKey',baseUrl: 'Base URL',baseUrlHint: 'Оставьте пустым, чтобы использовать адрес общедоступного облака по умолчанию. Для частных/корпоративных развертываний или при доступе через обратный прокси введите ваш собственный адрес (например, https://api-proxy.example.com)',feedUrls: 'Адреса лент',@@ -694,6 +704,7 @@ export default {lark_drive: 'Синхронизация документов, таблиц и файлов из папки Lark Drive',notion: 'Синхронизация страниц и баз данных из Notion',yuque: 'Синхронизация документов из баз знаний Yuque',+ ima: 'Синхронизация документов, заметок и файлов из баз знаний Tencent IMA',rss: 'Синхронизация статей из лент RSS / Atom'},connector: {@@ -703,6 +714,7 @@ export default {lark_drive: 'Lark Drive',notion: 'Notion',yuque: 'Yuque (Юйцюэ)',+ ima: 'Tencent IMA',rss: 'RSS / Atom лента'},logDetail: {@@ -5588,6 +5600,7 @@ export default {channelIm: 'IM канал',channelNotion: 'Notion',channelYuque: 'Yuque',+ channelIma: 'Tencent IMA',channelUpload: 'Загрузка',channelManual: 'Вручную',channelUrl: 'Веб',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 5347e1c41..a6bc17785 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -620,6 +620,14 @@ export default {prereqStep3Brief_yuque: '(可选)企业版填写 Base URL',prereqStep3Desc_yuque: '公有云用户无需填写;语雀企业版或私有部署请填写企业域名',prereqOpenConsole_yuque: '前往语雀 Token 设置',+ prereqBarText_ima: '首次使用?点击查看腾讯 IMA OpenAPI 授权指引',+ prereqStep1Brief_ima: '开通 IMA 智能体接入',+ prereqStep1Desc_ima: '登录 https://ima.qq.com/agent-interface 并申请 OpenAPI 接入',+ prereqStep2Brief_ima: '获取 ClientID 与 APIKey',+ prereqStep2Desc_ima: '在智能体接入页复制 ima-openapi-clientid 与 ima-openapi-apikey 两个凭证',+ prereqStep3Brief_ima: '授权目标知识库',+ prereqStep3Desc_ima: '在 IMA 客户端为该凭证授权需要同步的知识库,未授权的知识库不会出现在列表中',+ prereqOpenConsole_ima: '前往 IMA OpenAPI 控制台',prereqStep1Brief_feishu: "创建飞书自建应用",prereqStep1Desc_feishu: "登录飞书开放平台 → 创建企业自建应用",prereqStep2Brief_feishu: "添加机器人能力",@@ -680,6 +688,8 @@ export default {appSecret: 'App Secret',integrationToken: 'Integration Token',apiToken: 'API Token',+ imaClientId: 'IMA ClientID',+ imaApiKey: 'IMA APIKey',baseUrl: 'Base URL(可选)',baseUrlHint: '留空将使用默认公有云地址;如果是私有部署/企业内网部署,或需要通过反向代理访问,请填写自定义地址(例如 https://api-proxy.example.com)',feedUrls: '订阅源地址',@@ -694,6 +704,7 @@ export default {lark_drive: "同步 Lark 云盘文件夹中的文档、表格、文件(飞书国际版)",notion: '同步 Notion 中的页面和数据库',yuque: '同步语雀知识库中的文档',+ ima: '同步腾讯 IMA 知识库中的文档、笔记与文件',rss: '同步 RSS / Atom 订阅源中的文章'},connector: {@@ -703,6 +714,7 @@ export default {lark_drive: "Lark 云盘",notion: 'Notion',yuque: '语雀',+ ima: '腾讯 IMA',rss: 'RSS / Atom 订阅'},logDetail: {@@ -5588,6 +5600,7 @@ export default {channelIm: 'IM 渠道',channelNotion: 'Notion',channelYuque: '语雀',+ channelIma: '腾讯 IMA',channelUpload: '上传',channelManual: '手动',channelUrl: '网页',diff --git a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue b/frontend/src/views/chat/components/tool-results/DocumentInfo.vueindex a8d1dc3f8..be30673a0 100644--- a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue+++ b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue@@ -111,6 +111,7 @@ const channelLabelMap: Record<string, string> = {dingtalk: 'knowledgeBase.channelDingtalk',slack: 'knowledgeBase.channelSlack',im: 'knowledgeBase.channelIm',+ ima: 'knowledgeBase.channelIma',};const getChannelLabel = (channel: string) => {diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vueindex 9ef0ce596..8181faa58 100644--- a/frontend/src/views/knowledge/KnowledgeBase.vue+++ b/frontend/src/views/knowledge/KnowledgeBase.vue@@ -599,6 +599,7 @@ const sourceOptions = computed(() => [{ label: t('knowledgeBase.channelFeishuDrive'), value: 'feishu_drive' },{ label: t('knowledgeBase.channelNotion'), value: 'notion' },{ label: t('knowledgeBase.channelYuque'), value: 'yuque' },+ { label: t('knowledgeBase.channelIma'), value: 'ima' },{ label: t('knowledgeBase.channelWechat'), value: 'wechat' },{ label: t('knowledgeBase.channelWecom'), value: 'wecom' },{ label: t('knowledgeBase.channelDingtalk'), value: 'dingtalk' },diff --git a/frontend/src/views/knowledge/components/DocumentCardView.vue b/frontend/src/views/knowledge/components/DocumentCardView.vueindex dcf35c70a..b3e5342ea 100644--- a/frontend/src/views/knowledge/components/DocumentCardView.vue+++ b/frontend/src/views/knowledge/components/DocumentCardView.vue@@ -157,6 +157,7 @@ const channelLabelMap: Record<string, string> = {dingtalk: 'knowledgeBase.channelDingtalk',slack: 'knowledgeBase.channelSlack',im: 'knowledgeBase.channelIm',+ ima: 'knowledgeBase.channelIma',};const getChannelLabel = (channel: string) => {diff --git a/frontend/src/views/knowledge/components/DocumentListView.vue b/frontend/src/views/knowledge/components/DocumentListView.vueindex 7bb6bfb80..92348c32c 100644--- a/frontend/src/views/knowledge/components/DocumentListView.vue+++ b/frontend/src/views/knowledge/components/DocumentListView.vue@@ -114,6 +114,7 @@ const getSourceInfo = (item: KnowledgeItem): { icon: string; label: string } =>if (ch === 'lark_drive') return { icon: 'cloud-download', label: t('knowledgeBase.channelLarkDrive') };if (ch === 'notion') return { icon: 'cloud-download', label: t('knowledgeBase.channelNotion') };if (ch === 'yuque') return { icon: 'cloud-download', label: t('knowledgeBase.channelYuque') };+ if (ch === 'ima') return { icon: 'cloud-download', label: t('knowledgeBase.channelIma') };if (ch === 'wechat') return { icon: 'cloud-download', label: t('knowledgeBase.channelWechat') };if (ch === 'wecom') return { icon: 'cloud-download', label: t('knowledgeBase.channelWecom') };if (ch === 'dingtalk') return { icon: 'cloud-download', label: t('knowledgeBase.channelDingtalk') };diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vueindex cd3cf4ccb..2346cde42 100644--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue@@ -585,6 +585,21 @@ const connectorDefs = computed<ConnectorDef[]>(() => [{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://www.yuque.com', optional: true, hintKey: 'datasource.field.baseUrlHint' },],},+ {+ // Tencent IMA (ima.qq.com). Uses the OpenAPI at /openapi/wiki/v1 with two+ // static headers (ima-openapi-clientid + ima-openapi-apikey); no OAuth.+ type: 'ima',+ available: true,+ docUrl: 'https://ima.qq.com/agent-interface',+ permissionDocUrl: 'https://ima.qq.com/agent-interface',+ permissionPageUrl: 'https://ima.qq.com/agent-interface',+ requiredPermissions: [],+ fields: [+ { key: 'client_id', labelKey: 'datasource.field.imaClientId', placeholder: '', secret: true },+ { key: 'api_key', labelKey: 'datasource.field.imaApiKey', placeholder: '', secret: true },+ { key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://ima.qq.com', optional: true, hintKey: 'datasource.field.baseUrlHint' },+ ],+ },{type: 'rss',available: true,diff --git a/frontend/src/views/knowledge/settings/DataSourceSettings.vue b/frontend/src/views/knowledge/settings/DataSourceSettings.vueindex ca727c341..d8ed8ed5a 100644--- a/frontend/src/views/knowledge/settings/DataSourceSettings.vue+++ b/frontend/src/views/knowledge/settings/DataSourceSettings.vue@@ -464,6 +464,7 @@ onBeforeUnmount(stopPolling)&--feishu .ds-card__badge,&--notion .ds-card__badge,&--yuque .ds-card__badge,+ &--ima .ds-card__badge,&--rss .ds-card__badge {background: var(--td-bg-color-container, #fff);box-shadow: inset 0 0 0 1px var(--td-component-stroke);diff --git a/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue b/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vueindex 163c38ea1..a3cf664a6 100644--- a/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue+++ b/frontend/src/views/knowledge/settings/DataSourceTypeIcon.vue@@ -23,6 +23,8 @@ function fallbackText(type: string) {return 'N'case 'yuque':return 'Y'+ case 'ima':+ return 'I'default:return type.slice(0, 1).toUpperCase() || '?'}diff --git a/frontend/src/views/knowledge/settings/datasourceIcons.ts b/frontend/src/views/knowledge/settings/datasourceIcons.tsindex 670636f8c..deae26174 100644--- a/frontend/src/views/knowledge/settings/datasourceIcons.ts+++ b/frontend/src/views/knowledge/settings/datasourceIcons.ts@@ -3,6 +3,7 @@ import larkIcon from '@/assets/img/datasource-lark.svg'import notionIcon from '@/assets/img/datasource-notion.ico'import yuqueIcon from '@/assets/img/datasource-yuque.ico'import rssIcon from '@/assets/img/datasource-rss.svg'+import imaIcon from '@/assets/img/datasource-ima.png'export const datasourceIconMap: Record<string, string> = {feishu: feishuIcon,@@ -13,6 +14,7 @@ export const datasourceIconMap: Record<string, string> = {notion: notionIcon,yuque: yuqueIcon,rss: rssIcon,+ ima: imaIcon,}export function getDatasourceIconUrl(type: string): string | undefined {diff --git a/internal/container/container.go b/internal/container/container.goindex daef81526..aaf2a1faa 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -57,6 +57,7 @@ import ("github.com/Tencent/WeKnora/internal/datasource/connector/feishu/core""github.com/Tencent/WeKnora/internal/datasource/connector/feishu/drive""github.com/Tencent/WeKnora/internal/datasource/connector/feishu/wiki"+ imaConnector "github.com/Tencent/WeKnora/internal/datasource/connector/ima"notionConnector "github.com/Tencent/WeKnora/internal/datasource/connector/notion"rssConnector "github.com/Tencent/WeKnora/internal/datasource/connector/rss"yuqueConnector "github.com/Tencent/WeKnora/internal/datasource/connector/yuque"@@ -1653,6 +1654,9 @@ func initConnectorRegistry() (*datasource.ConnectorRegistry, error) {if err := registry.Register(yuqueConnector.NewConnector()); err != nil {errs = errors.Join(errs, fmt.Errorf("register yuque connector: %w", err))}+ if err := registry.Register(imaConnector.NewConnector()); err != nil {+ errs = errors.Join(errs, fmt.Errorf("register ima connector: %w", err))+ }if err := registry.Register(rssConnector.NewConnector()); err != nil {errs = errors.Join(errs, fmt.Errorf("register rss connector: %w", err))}diff --git a/internal/datasource/connector.go b/internal/datasource/connector.goindex bce382eb4..9e1bec4b9 100644--- a/internal/datasource/connector.go+++ b/internal/datasource/connector.go@@ -205,6 +205,14 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{AuthType: "api_key",Capabilities: []string{"incremental"},},+ types.ConnectorTypeIMA: {+ Type: types.ConnectorTypeIMA,+ Name: "Tencent IMA (ima.qq.com)",+ Description: "Sync knowledge bases and documents from Tencent IMA",+ Priority: 3,+ AuthType: "api_key",+ Capabilities: []string{"incremental", "deletion_sync"},+ },types.ConnectorTypeGitHub: {Type: types.ConnectorTypeGitHub,Name: "GitHub",diff --git a/internal/datasource/connector/ima/client.go b/internal/datasource/connector/ima/client.gonew file mode 100644index 000000000..95a8395e5--- /dev/null+++ b/internal/datasource/connector/ima/client.go@@ -0,0 +1,358 @@+package ima++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "sync"+ "time"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/logger"+)++const (+ defaultTimeout = 60 * time.Second+ defaultPageSize = 50+ userAgent = "WeKnora-IMA-Connector/1.0"++ // IMA hard limit: get_knowledge_list max limit=50; search_knowledge_base max=20.+ searchPageSize = 20++ // Default per-item download timeout — IMA COS URLs can be slow for large PDFs.+ downloadTimeout = 120 * time.Second++ // Max body we accept from get_media_info-URLs. 200MB matches IMA's largest+ maxDownloadBytes = 200 * 1024 * 1024+)++// client wraps the IMA OpenAPI. It is safe for concurrent use.+type client struct {+ baseURL string+ clientID string+ apiKey string+ httpClient *http.Client+ // downloadClient is a separate client with a longer timeout for pulling+ // media bodies from COS/CDN URLs returned by get_media_info.+ downloadClient *http.Client+ logCredentialOnce sync.Once+}++// newClient constructs a client with a normalized base URL.+func newClient(cfg *Config) *client {+ return &client{+ baseURL: cfg.GetBaseURL(),+ clientID: cfg.ClientID,+ apiKey: cfg.APIKey,+ httpClient: datasource.NewConnectorHTTPClient(defaultTimeout),+ downloadClient: datasource.NewConnectorHTTPClient(downloadTimeout),+ }+}++// callAPI executes an authenticated POST to /openapi/wiki/v1/<action>.+// It parses the standard {code, msg, data} envelope and unmarshals `data`+// into `result`. A non-zero business code is returned as a plain error so the+// caller can surface `msg` to the user+func (c *client) callAPI(ctx context.Context, action string, req interface{}, result interface{}) error {+ const (+ maxRetries = 3+ max5xxRetries = 1+ retry5xxDelay = 2 * time.Second+ )+ backoff := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second}++ c.logCredentialOnce.Do(func() {+ logger.Infof(ctx, "[IMA] client configured client_id=%s api_key=%s base=%s",+ redact(c.clientID), redact(c.apiKey), c.baseURL)+ })++ var body []byte+ if req != nil {+ b, err := json.Marshal(req)+ if err != nil {+ return fmt.Errorf("marshal request: %w", err)+ }+ body = b+ } else {+ body = []byte("{}")+ }++ url := c.baseURL + apiBasePath + "/" + action++ var lastErr error+ for attempt := 0; attempt <= maxRetries; attempt++ {+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return fmt.Errorf("create request: %w", err)+ }+ httpReq.Header.Set("ima-openapi-clientid", c.clientID)+ httpReq.Header.Set("ima-openapi-apikey", c.apiKey)+ httpReq.Header.Set("Content-Type", "application/json; charset=utf-8")+ httpReq.Header.Set("User-Agent", userAgent)++ if attempt == 0 {+ logger.Infof(ctx, "[IMA] POST %s", action)+ } else {+ logger.Infof(ctx, "[IMA] POST %s (retry %d/%d)", action, attempt, maxRetries)+ }++ resp, err := c.httpClient.Do(httpReq)+ if err != nil {+ lastErr = fmt.Errorf("execute request: %w", err)+ if attempt < maxRetries {+ if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {+ return sErr+ }+ continue+ }+ return lastErr+ }++ respBody, readErr := io.ReadAll(resp.Body)+ resp.Body.Close()+ if readErr != nil {+ lastErr = fmt.Errorf("read response: %w", readErr)+ if attempt < maxRetries {+ if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {+ return sErr+ }+ continue+ }+ return lastErr+ }++ bodyPreview := truncate(string(respBody), 500)+ logger.Infof(ctx, "[IMA] POST %s → status=%d bodyLen=%d body=%s",+ action, resp.StatusCode, len(respBody), bodyPreview)++ // HTTP-level auth failures: surface as ErrInvalidCredentials.+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ return fmt.Errorf("%w: status=%d body=%s",+ datasource.ErrInvalidCredentials, resp.StatusCode, bodyPreview)+ }++ if resp.StatusCode == http.StatusTooManyRequests {+ wait := backoff[minInt(attempt, len(backoff)-1)]+ lastErr = fmt.Errorf("ima rate limited: status=429 body=%s", bodyPreview)+ if attempt < maxRetries {+ if sErr := sleepCtx(ctx, wait); sErr != nil {+ return sErr+ }+ continue+ }+ return lastErr+ }++ if resp.StatusCode >= 500 && resp.StatusCode < 600 {+ lastErr = fmt.Errorf("ima server error: status=%d body=%s", resp.StatusCode, bodyPreview)+ if attempt < max5xxRetries {+ if sErr := sleepCtx(ctx, retry5xxDelay); sErr != nil {+ return sErr+ }+ continue+ }+ return lastErr+ }++ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("ima api http error: status=%d body=%s", resp.StatusCode, bodyPreview)+ }++ var env apiEnvelope+ if err := json.Unmarshal(respBody, &env); err != nil {+ return fmt.Errorf("decode envelope: %w", err)+ }++ // Business-level errors.+ // 110030 (无权限) / 110001 (参数非法) with common auth hint patterns are+ // mapped to ErrInvalidCredentials so the service marks the source in+ // `error` state and stops scheduling until re-authenticated.+ if env.Code != 0 {+ if env.Code == 110030 {+ return fmt.Errorf("%w: ima code=%d msg=%s",+ datasource.ErrInvalidCredentials, env.Code, env.Msg)+ }+ if env.Code == 110021 && attempt < maxRetries {+ lastErr = fmt.Errorf("ima rate limited: code=%d msg=%s", env.Code, env.Msg)+ if sErr := sleepCtx(ctx, backoff[minInt(attempt, len(backoff)-1)]); sErr != nil {+ return sErr+ }+ continue+ }+ return fmt.Errorf("ima api error: code=%d msg=%s", env.Code, env.Msg)+ }++ if result != nil && len(env.Data) > 0 && string(env.Data) != "null" {+ if err := json.Unmarshal(env.Data, result); err != nil {+ return fmt.Errorf("decode data: %w", err)+ }+ }+ return nil+ }+ return lastErr+}++// SearchKnowledgeBase — POST /search_knowledge_base. Empty query returns the+// list of every knowledge base visible to the current token (see api.md §7).+func (c *client) SearchKnowledgeBase(+ ctx context.Context, query, cursor string, limit int,+) (*searchKnowledgeBaseResp, error) {+ if limit <= 0 || limit > searchPageSize {+ limit = searchPageSize+ }+ req := map[string]interface{}{+ "query": query,+ "cursor": cursor,+ "limit": uint64(limit),+ }+ var resp searchKnowledgeBaseResp+ if err := c.callAPI(ctx, "search_knowledge_base", req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// GetKnowledgeBase — POST /get_knowledge_base for a batch of ids (1-20).+func (c *client) GetKnowledgeBase(ctx context.Context, ids []string) (map[string]knowledgeBaseInfo, error) {+ if len(ids) == 0 {+ return map[string]knowledgeBaseInfo{}, nil+ }+ req := map[string]interface{}{"ids": ids}+ var resp getKnowledgeBaseResp+ if err := c.callAPI(ctx, "get_knowledge_base", req, &resp); err != nil {+ return nil, err+ }+ if resp.Infos == nil {+ resp.Infos = map[string]knowledgeBaseInfo{}+ }+ return resp.Infos, nil+}++// GetAddableKnowledgeBaseList — POST /get_addable_knowledge_base_list.+// Lists knowledge bases the current token has permission to add content to.+// This is the authoritative "what KBs can this credential see?" endpoint+// (see api.md §7). Used as the primary enumeration source in ListResources —+// search_knowledge_base with empty query has been observed to return an empty+// list even when the token owns KBs, so we prefer this endpoint.+func (c *client) GetAddableKnowledgeBaseList(+ ctx context.Context, cursor string, limit int,+) (*getAddableKnowledgeBaseListResp, error) {+ if limit <= 0 || limit > defaultPageSize {+ limit = defaultPageSize+ }+ req := map[string]interface{}{+ "cursor": cursor,+ "limit": uint64(limit),+ }+ var resp getAddableKnowledgeBaseListResp+ if err := c.callAPI(ctx, "get_addable_knowledge_base_list", req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// GetKnowledgeList — POST /get_knowledge_list. folderID may be empty for root.+func (c *client) GetKnowledgeList(+ ctx context.Context, kbID, folderID, cursor string, limit int,+) (*getKnowledgeListResp, error) {+ if limit <= 0 || limit > defaultPageSize {+ limit = defaultPageSize+ }+ req := map[string]interface{}{+ "cursor": cursor,+ "limit": uint64(limit),+ "knowledge_base_id": kbID,+ }+ if folderID != "" {+ req["folder_id"] = folderID+ }+ var resp getKnowledgeListResp+ if err := c.callAPI(ctx, "get_knowledge_list", req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// GetMediaInfo — POST /get_media_info. Returns URL access info and (for notes)+// the notebook_id under notebook_ext_info.+func (c *client) GetMediaInfo(ctx context.Context, mediaID string) (*getMediaInfoResp, error) {+ req := map[string]interface{}{"media_id": mediaID}+ var resp getMediaInfoResp+ if err := c.callAPI(ctx, "get_media_info", req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// DownloadURL fetches a URL returned by GetMediaInfo, respecting the auth+// headers IMA may return alongside it. Enforces maxDownloadBytes to avoid a+// runaway body blowing up sync memory.+func (c *client) DownloadURL(ctx context.Context, u urlInfo) ([]byte, string, error) {+ if u.URL == "" {+ return nil, "", fmt.Errorf("empty url")+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.URL, nil)+ if err != nil {+ return nil, "", fmt.Errorf("create download request: %w", err)+ }+ for k, v := range u.Headers {+ req.Header.Set(k, v)+ }+ req.Header.Set("User-Agent", userAgent)++ resp, err := c.downloadClient.Do(req)+ if err != nil {+ return nil, "", fmt.Errorf("download: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return nil, "", fmt.Errorf("download http error: status=%d", resp.StatusCode)+ }++ body, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadBytes+1))+ if err != nil {+ return nil, "", fmt.Errorf("read download body: %w", err)+ }+ if int64(len(body)) > maxDownloadBytes {+ return nil, "", fmt.Errorf("download body exceeds %d bytes", maxDownloadBytes)+ }+ return body, resp.Header.Get("Content-Type"), nil+}++// sleepCtx pauses for d, returning early if ctx is cancelled.+func sleepCtx(ctx context.Context, d time.Duration) error {+ t := time.NewTimer(d)+ defer t.Stop()+ select {+ case <-t.C:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+}++func truncate(s string, maxLen int) string {+ if len(s) <= maxLen {+ return s+ }+ return s[:maxLen] + "..."+}++// redact returns a masked form of a credential for logging (never log full).+func redact(t string) string {+ if len(t) < 12 {+ return "***"+ }+ return t[:6] + "..." + t[len(t)-4:]+}++func minInt(a, b int) int {+ if a < b {+ return a+ }+ return b+}diff --git a/internal/datasource/connector/ima/connector.go b/internal/datasource/connector/ima/connector.gonew file mode 100644index 000000000..b21a9c82f--- /dev/null+++ b/internal/datasource/connector/ima/connector.go@@ -0,0 +1,514 @@+package ima++import (+ "context"+ "encoding/json"+ "fmt"+ "sort"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+)++// Compile-time proof that *Connector satisfies the datasource.Connector interface.+var _ datasource.Connector = (*Connector)(nil)++// Connector implements datasource.Connector for Tencent IMA (ima.qq.com).+type Connector struct{}++// NewConnector creates a new IMA connector.+func NewConnector() *Connector { return &Connector{} }++// Type returns the connector type identifier.+func (c *Connector) Type() string { return types.ConnectorTypeIMA }++// Validate verifies the credentials by calling get_addable_knowledge_base_list+// — the endpoint most likely to succeed even when the token has zero KBs, and+// the same one ListResources uses. It returns 110030 (无权限) when the token+// itself is invalid, which client.callAPI already maps to ErrInvalidCredentials.+func (c *Connector) Validate(ctx context.Context, config *types.DataSourceConfig) error {+ cfg, err := parseIMAConfig(config)+ if err != nil {+ return err+ }+ cli := newClient(cfg)+ if _, err := cli.GetAddableKnowledgeBaseList(ctx, "", defaultPageSize); err != nil {+ return fmt.Errorf("ima connection failed: %w", err)+ }+ return nil+}++// ResolveResourceAncestors: IMA knowledge bases are exposed as a flat list of+// top-level resources, so a lazy-loaded picker has no ancestors to reveal.+func (c *Connector) ResolveResourceAncestors(+ ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,+) ([]string, error) {+ return []string{}, nil+}++// ListResources returns the flat list of knowledge bases the token can read.+// parentID is honoured only for the "no children" contract — see the note on+// Connector.ListResources in internal/datasource/connector.go.+//+// Primary source is get_addable_knowledge_base_list, which returns the KBs the+// current OpenAPI credential has permission to operate on. When that endpoint+// returns an empty list (e.g. a legacy tenant only exposes read scopes) we+// fall back to search_knowledge_base with an empty query so users still see+// something to pick.+func (c *Connector) ListResources(+ ctx context.Context, config *types.DataSourceConfig, parentID string,+) ([]types.Resource, error) {+ if parentID != "" {+ return []types.Resource{}, nil+ }++ cfg, err := parseIMAConfig(config)+ if err != nil {+ return nil, err+ }+ cli := newClient(cfg)++ type kbLite struct {+ ID string+ Name string+ CoverURL string+ }+ var bases []kbLite++ cursor := ""+ for {+ resp, err := cli.GetAddableKnowledgeBaseList(ctx, cursor, defaultPageSize)+ if err != nil {+ return nil, fmt.Errorf("get_addable_knowledge_base_list: %w", err)+ }+ for _, b := range resp.AddableKnowledgeBaseList {+ bases = append(bases, kbLite{ID: b.ID, Name: b.Name})+ }+ if resp.IsEnd || resp.NextCursor == "" {+ break+ }+ cursor = resp.NextCursor+ }+ logger.Infof(ctx, "[IMA] get_addable_knowledge_base_list returned %d knowledge bases", len(bases))++ if len(bases) == 0 {+ cursor = ""+ for {+ resp, err := cli.SearchKnowledgeBase(ctx, "", cursor, searchPageSize)+ if err != nil {+ return nil, fmt.Errorf("search_knowledge_base fallback: %w", err)+ }+ for _, b := range resp.InfoList {+ bases = append(bases, kbLite{ID: b.ID, Name: b.Name, CoverURL: b.CoverURL})+ }+ if resp.IsEnd || resp.NextCursor == "" {+ break+ }+ cursor = resp.NextCursor+ }+ logger.Infof(ctx, "[IMA] search_knowledge_base fallback returned %d knowledge bases", len(bases))+ }++ ids := make([]string, 0, len(bases))+ for _, b := range bases {+ ids = append(ids, b.ID)+ }+ details := map[string]knowledgeBaseInfo{}+ for i := 0; i < len(ids); i += 20 {+ end := i + 20+ if end > len(ids) {+ end = len(ids)+ }+ batch, err := cli.GetKnowledgeBase(ctx, ids[i:end])+ if err != nil {+ logger.Warnf(ctx, "[IMA] get_knowledge_base batch failed (skipping enrichment): %v", err)+ continue+ }+ for k, v := range batch {+ details[k] = v+ }+ }++ out := make([]types.Resource, 0, len(bases))+ for _, b := range bases {+ desc := ""+ coverURL := b.CoverURL+ if d, ok := details[b.ID]; ok {+ desc = d.Description+ if coverURL == "" {+ coverURL = d.CoverURL+ }+ }+ out = append(out, types.Resource{+ ExternalID: b.ID,+ Name: b.Name,+ Type: "knowledge_base",+ Description: desc,+ URL: cfg.GetBaseURL(),+ Metadata: map[string]interface{}{+ "cover_url": coverURL,+ },+ })+ }+ sort.Slice(out, func(i, j int) bool { return out[i].ExternalID < out[j].ExternalID })+ logger.Infof(ctx, "[IMA] ListResources returning %d knowledge bases to UI", len(out))+ return out, nil+}++// FetchAll performs a full sync of every knowledge base in resourceIDs.+func (c *Connector) FetchAll(+ ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,+) ([]types.FetchedItem, error) {+ items, _, err := c.walk(ctx, config, resourceIDs, nil, false)+ return items, err+}++// FetchIncremental syncs new / replaced / removed items against the cursor.+//+// Each IMA item is identified by a stable logical_key (see logicalKey), NOT by+// media_id — because IMA reassigns media_id whenever a same-named file is+// replaced in place, and we want that replacement to surface as an UPDATE to+// the same knowledge item rather than a delete-plus-insert pair.+//+// Emitted this cycle:+//+// - logical_key new since last sync → add (new content)+// - logical_key present, media_id changed → update (re-fetched content;+// ingest layer's existing+// external_id match triggers+// delete-and-recreate)+// - logical_key unchanged, media_id unchanged → skip+// - logical_key present last sync, absent this sync → IsDeleted tombstone+//+// LIMITATION: IMA still exposes no per-item updated_at, so an in-place edit+// that keeps the SAME media_id (same file bytes replaced under the hood by+// IMA, if that ever happens) is invisible to us. Users needing a full content+// refresh should periodically run a Full sync.+func (c *Connector) FetchIncremental(+ ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor,+) ([]types.FetchedItem, *types.SyncCursor, error) {+ resourceIDs := config.ResourceIDs+ if len(resourceIDs) == 0 {+ return nil, nil, fmt.Errorf("no resource IDs (knowledge base IDs) configured")+ }++ var prev *imaCursor+ if cursor != nil && cursor.ConnectorCursor != nil {+ var p imaCursor+ b, _ := json.Marshal(cursor.ConnectorCursor)+ _ = json.Unmarshal(b, &p)+ prev = &p+ }++ items, newCursor, err := c.walk(ctx, config, resourceIDs, prev, true)+ if err != nil {+ return nil, nil, err+ }++ cursorMap := make(map[string]interface{})+ b, _ := json.Marshal(newCursor)+ _ = json.Unmarshal(b, &cursorMap)++ return items, &types.SyncCursor{+ LastSyncTime: newCursor.LastSyncTime,+ ConnectorCursor: cursorMap,+ }, nil+}++// walk is the shared implementation for FetchAll / FetchIncremental.+// When incremental is false, prev is ignored and returned cursor is nil.+func (c *Connector) walk(+ ctx context.Context,+ config *types.DataSourceConfig,+ resourceIDs []string,+ prev *imaCursor,+ incremental bool,+) ([]types.FetchedItem, *imaCursor, error) {+ cfg, err := parseIMAConfig(config)+ if err != nil {+ return nil, nil, err+ }+ cli := newClient(cfg)++ newCursor := &imaCursor{+ LastSyncTime: time.Now(),+ KBLogical: make(map[string]map[string]string),+ KBMedia: make(map[string]map[string]string),+ }+ var out []types.FetchedItem++ for _, kbID := range resourceIDs {+ files, folderPath, err := listAllKBFiles(ctx, cli, kbID)+ if err != nil {+ return nil, nil, fmt.Errorf("list KB %s: %w", kbID, err)+ }++ currentLogical := make(map[string]string, len(files))+ currentMedia := make(map[string]string, len(files))+ keys := make([]string, len(files))+ for i, f := range files {+ // f.MediaType is 0 in list responses (IMA omits it there); we rely on+ // (kb_id, parent_folder_id, title) which IMA enforces uniqueness on+ // via check_repeated_names. Encoding media_type as 0 is fine as long+ // as it stays consistent across syncs — which it does, since 0 is a+ // constant here.+ key := logicalKey(kbID, f.ParentFolderID, f.Title, f.MediaType)+ keys[i] = key+ currentLogical[key] = f.MediaID+ currentMedia[f.MediaID] = f.Title+ }+ newCursor.KBLogical[kbID] = currentLogical+ newCursor.KBMedia[kbID] = currentMedia++ replaced := 0+ for i, f := range files {+ key := keys[i]++ // Incremental skip / replacement detection.+ if incremental && prev != nil && prev.KBLogical != nil {+ if prevSet, ok := prev.KBLogical[kbID]; ok {+ if prevMediaID, seen := prevSet[key]; seen {+ if prevMediaID == f.MediaID {+ continue // unchanged+ }+ replaced++ // media_id changed → replacement, fall through to re-fetch+ }+ }+ }++ item, ok := fetchOneMedia(ctx, cli, cfg, kbID, key, f, folderPath)+ if !ok {+ continue+ }+ out = append(out, item)+ }++ // Deletion detection (incremental only) — based on logical_key vanishing,+ // so a same-name replacement (media_id churns but logical_key stays)+ // never fires a spurious delete.+ deleted := 0+ if incremental && prev != nil && prev.KBLogical != nil {+ if prevSet, ok := prev.KBLogical[kbID]; ok {+ for prevKey := range prevSet {+ if _, still := currentLogical[prevKey]; !still {+ out = append(out, types.FetchedItem{+ ExternalID: prevKey,+ IsDeleted: true,+ SourceResourceID: kbID,+ })+ deleted+++ }+ }+ }+ }++ logger.Infof(ctx, "[IMA] KB %s: total=%d replaced=%d deleted=%d",+ kbID, len(files), replaced, deleted)+ }++ if !incremental {+ return out, nil, nil+ }+ return out, newCursor, nil+}++// walkedFile is an internal representation of a knowledge item after we've+// resolved its folder location within the KB tree.+type walkedFile struct {+ knowledgeInfo+ // FolderPath is the "/A/B" style path (folder names, no leading slash)+ // of the containing folder — empty for root-level items.+ FolderPath string+}++// listAllKBFiles recursively enumerates a knowledge base into a flat list of+// files, resolving each item's folder path from the on-the-fly folder tree.+// folderPath maps folder_id → readable path (for metadata).+func listAllKBFiles(+ ctx context.Context, cli *client, kbID string,+) ([]walkedFile, map[string]string, error) {+ folderPath := map[string]string{}+ var out []walkedFile++ // BFS/DFS over folders. Start from root (empty folder_id).+ type todo struct {+ folderID string+ path string+ }+ stack := []todo{{folderID: "", path: ""}}++ for len(stack) > 0 {+ cur := stack[len(stack)-1]+ stack = stack[:len(stack)-1]++ cursor := ""+ for {+ resp, err := cli.GetKnowledgeList(ctx, kbID, cur.folderID, cursor, defaultPageSize)+ if err != nil {+ return nil, nil, err+ }+ for _, raw := range resp.KnowledgeList {+ // Probe each entry: an entry with a non-empty folder_id is a+ // folder; otherwise it's a knowledge item (file / note / etc.).+ var probe struct {+ FolderID string `json:"folder_id"`+ MediaID string `json:"media_id"`+ }+ _ = json.Unmarshal(raw, &probe)++ if probe.FolderID != "" && probe.MediaID == "" {+ var fi folderInfo+ if err := json.Unmarshal(raw, &fi); err != nil {+ continue+ }+ child := cur.path+ if child == "" {+ child = fi.Name+ } else {+ child = cur.path + "/" + fi.Name+ }+ folderPath[fi.FolderID] = child+ stack = append(stack, todo{folderID: fi.FolderID, path: child})+ continue+ }+ if probe.MediaID == "" {+ continue // unrecognized shape, skip defensively+ }+ var ki knowledgeInfo+ if err := json.Unmarshal(raw, &ki); err != nil {+ continue+ }+ out = append(out, walkedFile{+ knowledgeInfo: ki,+ FolderPath: cur.path,+ })+ }+ if resp.IsEnd || resp.NextCursor == "" {+ break+ }+ cursor = resp.NextCursor+ }+ }+ return out, folderPath, nil+}++// fetchOneMedia calls get_media_info for a single item and, when possible,+// downloads its body. Returns false if the item should be skipped (unsupported+// media type, download error, note-type, etc.).+//+// externalID is the stable logical_key computed by the caller — same value+// across syncs even after an IMA same-name replacement mints a new media_id.+// The raw media_id is still preserved in metadata for observability.+func fetchOneMedia(+ ctx context.Context, cli *client, cfg *Config,+ kbID string, externalID string, f walkedFile, folderPath map[string]string,+) (types.FetchedItem, bool) {+ info, err := cli.GetMediaInfo(ctx, f.MediaID)+ if err != nil {+ logger.Warnf(ctx, "[IMA] get_media_info(%s) failed, skipping: %v", f.MediaID, err)+ return types.FetchedItem{}, false+ }++ if isSkippableMediaType(info.MediaType) {+ logger.Infof(ctx, "[IMA] skip media %s (title=%q media_type=%d): unsupported by wiki OpenAPI",+ f.MediaID, f.Title, info.MediaType)+ return types.FetchedItem{}, false+ }++ if info.URLInfo.URL == "" {+ logger.Warnf(ctx, "[IMA] media %s (title=%q) has no url_info.url, skipping", f.MediaID, f.Title)+ return types.FetchedItem{}, false+ }++ ext := extensionForMediaType(info.MediaType)+ if ext == "" {+ return types.FetchedItem{+ ExternalID: externalID,+ Title: f.Title,+ URL: info.URLInfo.URL,+ SourceResourceID: kbID,+ UpdatedAt: time.Now(),+ Metadata: baseMetadata(externalID, f, folderPath, info, kbID),+ }, true+ }++ body, ct, err := cli.DownloadURL(ctx, info.URLInfo)+ if err != nil {+ logger.Warnf(ctx, "[IMA] download media %s (title=%q) failed, skipping: %v", f.MediaID, f.Title, err)+ return types.FetchedItem{}, false+ }+ if ct == "" || strings.HasPrefix(ct, "application/octet-stream") {+ ct = mimeForExtension(ext)+ }++ fileName := sanitizeFileName(f.Title)+ if !strings.HasSuffix(strings.ToLower(fileName), "."+ext) {+ fileName = fileName + "." + ext+ }++ return types.FetchedItem{+ ExternalID: externalID,+ Title: f.Title,+ Content: body,+ ContentType: ct,+ FileName: fileName,+ URL: info.URLInfo.URL,+ UpdatedAt: time.Now(),+ SourceResourceID: kbID,+ Metadata: baseMetadata(externalID, f, folderPath, info, kbID),+ }, true+}++// baseMetadata builds the metadata map preserved on every ingested item.+// externalID (the caller's logical_key) is stored so operators can join the+// stable identity back to the raw media_id — useful when debugging why a+// same-name replacement showed up as an update instead of an add.+func baseMetadata(externalID string, f walkedFile, folderPath map[string]string, info *getMediaInfoResp, kbID string) map[string]string {+ m := map[string]string{+ "channel": types.ChannelIMA,+ "media_id": f.MediaID,+ "ima_logical_key": externalID,+ "knowledge_base_id": kbID,+ "folder_path": f.FolderPath,+ "media_type": fmt.Sprintf("%d", info.MediaType),+ }+ if f.ParentFolderID != "" {+ m["parent_folder_id"] = f.ParentFolderID+ }+ if fp, ok := folderPath[f.ParentFolderID]; ok && fp != "" {+ m["folder_path"] = fp+ }+ if info.NotebookExtInfo.NotebookID != "" {+ m["notebook_id"] = info.NotebookExtInfo.NotebookID+ }+ return m+}++// sanitizeFileName removes filesystem-hostile characters and truncates to a+// safe UTF-8 boundary.+func sanitizeFileName(name string) string {+ if name == "" {+ return "untitled"+ }+ replacer := strings.NewReplacer(+ "/", "_", "\\", "_", ":", "_", "*", "_",+ "?", "_", "\"", "_", "<", "_", ">", "_", "|", "_",+ )+ result := replacer.Replace(name)+ const maxBytes = 200+ if len(result) > maxBytes {+ result = result[:maxBytes]+ for len(result) > 0 {+ r, size := utf8.DecodeLastRuneInString(result)+ if r != utf8.RuneError || size != 1 {+ break+ }+ result = result[:len(result)-1]+ }+ }+ return result+}diff --git a/internal/datasource/connector/ima/types.go b/internal/datasource/connector/ima/types.gonew file mode 100644index 000000000..5c8feee1c--- /dev/null+++ b/internal/datasource/connector/ima/types.go@@ -0,0 +1,353 @@+package ima++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "strings"+ "time"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+)++// DefaultBaseURL is the IMA OpenAPI base URL. The Path prefix is baked into+// the client (see client.go); users only configure the host.+const DefaultBaseURL = "https://ima.qq.com"++// Base path for every OpenAPI request.+const apiBasePath = "/openapi/wiki/v1"++// Config holds IMA-specific configuration decoded from+// DataSourceConfig.Credentials. Both credentials are opaque strings and+// stored encrypted at rest by DataSourceConfig.ToJSON (see internal/types/datasource.go).+type Config struct {+ // ClientID: value of the `ima-openapi-clientid` request header,+ // obtained from https://ima.qq.com/agent-interface.+ ClientID string `json:"client_id"`++ // APIKey: value of the `ima-openapi-apikey` request header.+ APIKey string `json:"api_key"`++ // BaseURL lets users point at an on-prem / test IMA endpoint.+ // Defaults to https://ima.qq.com when empty.+ BaseURL string `json:"base_url,omitempty"`+}++// GetBaseURL returns the normalized base URL (empty → default, no trailing slash).+func (c *Config) GetBaseURL() string {+ url := strings.TrimSpace(c.BaseURL)+ if url == "" {+ return DefaultBaseURL+ }+ if !strings.Contains(url, "://") {+ url = "https://" + url+ }+ return strings.TrimRight(url, "/")+}++// parseIMAConfig extracts and validates IMA-specific configuration.+// Uses JSON marshal/unmarshal roundtrip so extra fields are ignored gracefully.+func parseIMAConfig(config *types.DataSourceConfig) (*Config, error) {+ if config == nil {+ return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig)+ }+ credBytes, err := json.Marshal(config.Credentials)+ if err != nil {+ return nil, fmt.Errorf("marshal credentials: %w", err)+ }+ var cfg Config+ if err := json.Unmarshal(credBytes, &cfg); err != nil {+ return nil, fmt.Errorf("parse ima credentials: %w", err)+ }+ if strings.TrimSpace(cfg.ClientID) == "" {+ return nil, fmt.Errorf("%w: client_id is required", datasource.ErrInvalidCredentials)+ }+ if strings.TrimSpace(cfg.APIKey) == "" {+ return nil, fmt.Errorf("%w: api_key is required", datasource.ErrInvalidCredentials)+ }+ if err := datasource.ValidateConnectorBaseURL(cfg.GetBaseURL()); err != nil {+ return nil, err+ }+ return &cfg, nil+}++// apiEnvelope is the uniform IMA response wrapper: `{ code, msg, data }`.+// A non-zero code is a business-level error and MUST be surfaced to the user+type apiEnvelope struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data json.RawMessage `json:"data"`+}++// KnowledgeBaseInfo mirrors IMA's KnowledgeBaseInfo (get_knowledge_base).+type knowledgeBaseInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+ CoverURL string `json:"cover_url"`+ Description string `json:"description"`+ RecommendedQuestions []string `json:"recommended_questions"`+}++// searchedKnowledgeBaseInfo — search_knowledge_base returns fewer fields.+type searchedKnowledgeBaseInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+ CoverURL string `json:"cover_url"`+}++// searchKnowledgeBaseResp — search_knowledge_base response.+type searchKnowledgeBaseResp struct {+ InfoList []searchedKnowledgeBaseInfo `json:"info_list"`+ IsEnd bool `json:"is_end"`+ NextCursor string `json:"next_cursor"`+}++// addableKnowledgeBaseInfo — get_addable_knowledge_base_list item.+// Contains only id + name (no cover_url), see api.md §7.+type addableKnowledgeBaseInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+}++// getAddableKnowledgeBaseListResp — get_addable_knowledge_base_list response.+// NOTE: the JSON field is `addable_knowledge_base_list`, not `info_list`.+type getAddableKnowledgeBaseListResp struct {+ AddableKnowledgeBaseList []addableKnowledgeBaseInfo `json:"addable_knowledge_base_list"`+ IsEnd bool `json:"is_end"`+ NextCursor string `json:"next_cursor"`+}++// getKnowledgeBaseResp — get_knowledge_base response (map keyed by id).+type getKnowledgeBaseResp struct {+ Infos map[string]knowledgeBaseInfo `json:"infos"`+}++// knowledgeInfo mirrors IMA's KnowledgeInfo (files, notes, etc.).+// IMPORTANT: IMA does not expose media_type in the list response, we must call+// get_media_info to discover it. However, folders are distinguished by presence+// of a non-empty folder_id — see folderInfo below.+type knowledgeInfo struct {+ MediaID string `json:"media_id"`+ Title string `json:"title"`+ ParentFolderID string `json:"parent_folder_id"`+ MediaType int32 `json:"media_type,omitempty"`+}++// folderInfo mirrors IMA's FolderInfo.+type folderInfo struct {+ FolderID string `json:"folder_id"`+ Name string `json:"name"`+ FileNumber json.Number `json:"file_number"`+ FolderNumber json.Number `json:"folder_number"`+ ParentFolderID string `json:"parent_folder_id"`+ IsTop bool `json:"is_top"`+}++// FileCount safely converts FileNumber to int64 (0 on empty/invalid).+func (f folderInfo) FileCount() int64 {+ if f.FileNumber == "" {+ return 0+ }+ n, err := f.FileNumber.Int64()+ if err != nil {+ return 0+ }+ return n+}++// FolderCount safely converts FolderNumber to int64 (0 on empty/invalid).+func (f folderInfo) FolderCount() int64 {+ if f.FolderNumber == "" {+ return 0+ }+ n, err := f.FolderNumber.Int64()+ if err != nil {+ return 0+ }+ return n+}++// getKnowledgeListResp — get_knowledge_list response.+// According to `references/api.md`, the response returns knowledge_list mixed+// with folders; we decode a loose JSON view so entries without a folder_id are+// treated as knowledge and those with folder_id are treated as folders.+type getKnowledgeListResp struct {+ // KnowledgeList is a loose slice of raw JSON objects because IMA returns+ // files and folders in the same array. We iterate and inspect fields.+ KnowledgeList []json.RawMessage `json:"knowledge_list"`+ IsEnd bool `json:"is_end"`+ NextCursor string `json:"next_cursor"`+ CurrentPath []folderInfo `json:"current_path"`+}++// urlInfo mirrors IMA's URLInfo (present on get_media_info for URL-backed media).+type urlInfo struct {+ URL string `json:"url"`+ Headers map[string]string `json:"headers"`+}++// notebookExtInfo — set on notes (media_type=11).+type notebookExtInfo struct {+ NotebookID string `json:"notebook_id"`+}++// getMediaInfoResp — get_media_info response.+type getMediaInfoResp struct {+ MediaType int32 `json:"media_type"`+ URLInfo urlInfo `json:"url_info"`+ NotebookExtInfo notebookExtInfo `json:"notebook_ext_info"`+}++// imaCursor tracks per-knowledge-base state seen during the last sync.+//+// Two parallel maps are kept, both keyed by kb_id:+//+// - KBLogical: { logical_key: media_id } — the authoritative source for+// both delete detection AND "replacement" detection. IMA reassigns+// media_id whenever a same-named file is replaced in place, so a logical+// key (see logicalKey) is what we treat as a document's stable identity.+// A logical_key present last sync but absent this sync ⇒ delete.+// A logical_key whose media_id changed ⇒ replacement (re-fetch content;+// the emitted FetchedItem carries the same ExternalID so the ingest+// layer's "existing external_id → delete-and-recreate" path (see+// datasource_service.go applyFetchedItem) treats it as an update.+//+// - KBMedia (legacy): { media_id: title } — retained so cursors persisted+// by older versions still deserialize; not consulted for new detection.+// New cursors write this too, purely for observability in logs.+type imaCursor struct {+ LastSyncTime time.Time `json:"last_sync_time"`+ KBLogical map[string]map[string]string `json:"kb_logical,omitempty"`+ KBMedia map[string]map[string]string `json:"kb_media,omitempty"`+}++// logicalKey derives a stable identity for an IMA item that survives+// same-name replacement (which mints a new media_id server-side).+//+// The key is a short SHA-256 hex over (kb_id, parent_folder_id, title,+// media_type). Rationale:+//+// - kb_id keeps identities isolated across knowledge bases (same file+// copied into two KBs is two distinct docs from WeKnora's perspective).+// - parent_folder_id + title anchor the doc to its folder location and+// display name — the tuple IMA's own check_repeated_names uses to gate+// uploads (see api.md), so IMA's own uniqueness constraint enforces+// this key's uniqueness inside a KB.+// - media_type distinguishes "notes.md" (Markdown) from "notes.md"+// (Word) in the same folder — pathologically rare but cheap to guard.+//+// Emitted as "ima_" + first 32 hex chars (128 bits) — small enough to fit+// well within Postgres varchar(64) external_id columns, still >> collision+// resistant for any realistic KB size.+func logicalKey(kbID, parentFolderID, title string, mediaType int32) string {+ h := sha256.New()+ // Delimiter can't appear in any component because it's neither a valid+ // IMA id character nor allowed in titles once we've folded to bytes.+ fmt.Fprintf(h, "%s\x1f%s\x1f%s\x1f%d", kbID, parentFolderID, title, mediaType)+ return "ima_" + hex.EncodeToString(h.Sum(nil))[:32]+}++// IMA MediaType enum (see api.md §MediaType).+const (+ mediaTypePDF int32 = 1+ mediaTypeWeb int32 = 2+ mediaTypeWord int32 = 3+ mediaTypePPT int32 = 4+ mediaTypeExcel int32 = 5+ mediaTypeMPArticle int32 = 6+ mediaTypeMarkdown int32 = 7+ mediaTypeImage int32 = 9+ mediaTypeNote int32 = 11+ mediaTypeAISession int32 = 12+ mediaTypeTXT int32 = 13+ mediaTypeXmind int32 = 14+ mediaTypeAudio int32 = 15+ mediaTypeVideo int32 = 16+ mediaTypeHTML int32 = 20+ mediaTypeEPUB int32 = 21+)++// extensionForMediaType maps IMA media types to a file extension.+// Returns "" when the media type has no downloadable body (web page, note, AI+// session, video-parse) — callers should skip those or treat them as URL-only.+func extensionForMediaType(t int32) string {+ switch t {+ case mediaTypePDF:+ return "pdf"+ case mediaTypeWord:+ return "docx"+ case mediaTypePPT:+ return "pptx"+ case mediaTypeExcel:+ return "xlsx"+ case mediaTypeMarkdown:+ return "md"+ case mediaTypeImage:+ return "png"+ case mediaTypeTXT:+ return "txt"+ case mediaTypeXmind:+ return "xmind"+ case mediaTypeAudio:+ return "mp3"+ case mediaTypeHTML:+ return "html"+ case mediaTypeEPUB:+ return "epub"+ default:+ return ""+ }+}++// mimeForExtension maps a file extension to a canonical MIME type.+// Used when the downloaded URL response omits (or misreports) Content-Type.+func mimeForExtension(ext string) string {+ switch strings.ToLower(strings.TrimPrefix(ext, ".")) {+ case "pdf":+ return "application/pdf"+ case "doc":+ return "application/msword"+ case "docx":+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ case "ppt":+ return "application/vnd.ms-powerpoint"+ case "pptx":+ return "application/vnd.openxmlformats-officedocument.presentationml.presentation"+ case "xls":+ return "application/vnd.ms-excel"+ case "xlsx":+ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+ case "md":+ return "text/markdown"+ case "txt":+ return "text/plain"+ case "html", "htm":+ return "text/html"+ case "png":+ return "image/png"+ case "jpg", "jpeg":+ return "image/jpeg"+ case "webp":+ return "image/webp"+ case "epub":+ return "application/epub+zip"+ case "xmind":+ return "application/x-xmind"+ case "mp3":+ return "audio/mpeg"+ case "m4a":+ return "audio/x-m4a"+ case "wav":+ return "audio/wav"+ case "aac":+ return "audio/aac"+ default:+ return "application/octet-stream"+ }+}++func isSkippableMediaType(t int32) bool {+ return t == mediaTypeNote || t == mediaTypeAISession || t == mediaTypeVideo+}diff --git a/internal/types/datasource.go b/internal/types/datasource.goindex 914e6b287..b53dd8e92 100644--- a/internal/types/datasource.go+++ b/internal/types/datasource.go@@ -36,6 +36,7 @@ const (ConnectorTypeSlack = "slack"ConnectorTypeIMAP = "imap"ConnectorTypeRSS = "rss"+ ConnectorTypeIMA = "ima"// Sync modesSyncModeIncremental = "incremental"diff --git a/internal/types/knowledge.go b/internal/types/knowledge.goindex 2133997ac..feb69d388 100644--- a/internal/types/knowledge.go+++ b/internal/types/knowledge.go@@ -35,6 +35,7 @@ const (ChannelNotion = "notion" // NotionChannelYuque = "yuque" // Yuque (语雀)ChannelRSS = "rss" // RSS / Atom feed+ ChannelIMA = "ima" // Tencent IMA (ima.qq.com))// Knowledge parse status constants