feat(plugin): plugin system foundation — builtin plugins, config schemas and workspace switches (#3711)

* feat(plugin): add plugin manifest, registry and builtin catalog
* feat(plugin): add config schemas with unified secret handling
* feat(frontend): render config schemas with SchemaForm
* feat(datasource): serve connector credential forms from the backend
* feat(im): describe IM platforms and credentials from the backend
* feat(frontend): render model vendor extra fields from the config schema
* feat(frontend): build the settings modal from an extension registry
* refactor(agent): register builtin tools and their chat views
* feat(plugin): let workspaces enable and disable plugins
* feat(plugin): add the runtime driver interface and gather builtins
main
lyingbug 2026-09-26 14:43:28 +08:00 committed by GitHub
parent 47773b5bd1
commit c91a8d11f8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
120 changed files with 8280 additions and 1742 deletions

View File

@ -1,3 +1,4 @@
import type { ConfigSchema } from '@/components/schema-form/schema'
import { get, post, put, del } from "../../utils/request";
// 智能体配置
@ -347,6 +348,35 @@ export interface IMChannelOverview {
updated_at: string;
}
// IMPlatformInfo describes one IM platform (internal/im.PlatformInfo): its
// connection modes, console links and the credential form.
export interface IMPlatformInfo {
id: string
name: string
names?: Record<string, string>
order: number
/** Supported connection modes, default first. */
modes: Array<IMChannel['mode']>
mode_labels?: Record<string, string>
mode_hint_key?: string
supports_thread: boolean
links?: Array<{ url: string; title: string; title_key?: string }>
config_schema?: ConfigSchema
}
/**
* One channel for the editor, credentials included: plain fields as stored,
* set secrets as "***". Send them back unchanged to keep the stored secret.
*/
export function getIMChannel(id: string) {
return get<{ data: IMChannel }>(`/api/v1/im-channels/${id}`);
}
/** The IM platforms this deployment has adapters for, in display order. */
export function listIMPlatforms() {
return get<{ data: IMPlatformInfo[] }>('/api/v1/im-channels/platforms');
}
export function listAllIMChannels() {
return get<{ data: IMChannelOverview[] }>('/api/v1/im-channels');
}

View File

@ -1,3 +1,4 @@
import type { ConfigSchema } from '@/components/schema-form/schema'
import { get, post, put, del } from '../../utils/request'
// --- Types ---
@ -72,6 +73,13 @@ export interface ConnectorMeta {
priority: number
auth_type: string
capabilities: string[]
// Setup guide next to the credential form.
doc_url?: string
permission_doc_url?: string
permission_page_url?: string
required_permissions?: string[]
// Credential form: describes config.credentials for this connector.
config_schema?: ConfigSchema
}
export interface Resource {
@ -88,8 +96,9 @@ export interface Resource {
// --- API calls ---
/** Connectors this deployment can create, with their credential forms. */
export function getConnectorTypes() {
return get('/api/v1/datasource/types')
return get<ConnectorMeta[]>('/api/v1/datasource/types')
}
export function listDataSources(kbId: string) {

View File

@ -1,3 +1,4 @@
import type { ConfigSchema } from '@/components/schema-form/schema';
import { get, post, put } from '../../utils/request';
import i18n from '@/i18n'
import type { ModelCapabilities, ModelSpecOverride, ReasoningEffortLevel } from '../model'
@ -661,6 +662,8 @@ export interface ModelProviderOption {
defaultUrls: Record<string, string>; // 按模型类型区分的默认 URL
modelTypes: string[]; // 支持的模型类型
extraFields?: ModelProviderExtraField[];
// extraFields as a config schema over extra_config (secrets included).
configSchema?: ConfigSchema;
credentialLabels?: ModelProviderCredentialLabel[];
models?: ModelCatalogEntry[];
thinking?: ModelProviderThinking;

View File

@ -0,0 +1,48 @@
import { get, put } from '@/utils/request'
import type { LocalizedText } from '@/utils/localizedText'
export type { LocalizedText } from '@/utils/localizedText'
export type ExtensionPoint = 'modelVendors' | 'connectors' | 'imChannels' | 'webSearch' | 'tools' | 'parsers'
export interface PluginContribution {
id: string
name: LocalizedText
description?: LocalizedText
icon?: string
aliases?: string[]
capabilities?: string[]
order?: number
}
/** A plugin's manifest (internal/plugin/manifest.Manifest). */
export interface PluginManifest {
schemaVersion: number
id: string
version: string
name: LocalizedText
description?: LocalizedText
publisher: { id: string; name?: string; url?: string }
icon?: string
builtin?: boolean
required?: boolean
runtime: { type: string }
contributes: Partial<Record<ExtensionPoint, PluginContribution[]>>
}
/** A plugin as the current workspace sees it. */
export interface TenantPlugin {
manifest: PluginManifest
enabled: boolean
updatedAt?: string
}
export function listPlugins() {
return get<{ data: TenantPlugin[] }>('/api/v1/plugins')
}
/** Turns a plugin on or off for the current workspace (Admin+). */
export function setPluginEnabled(id: string, enabled: boolean) {
return put<{ data: TenantPlugin }>(`/api/v1/plugins/${encodeURIComponent(id)}/enabled`, { enabled })
}

View File

@ -1,3 +1,4 @@
import type { ConfigSchema } from '@/components/schema-form/schema'
import { get, post, put, del } from '@/utils/request'
// WebSearchProviderEntity represents a configured web search provider instance
@ -37,6 +38,8 @@ export interface WebSearchProviderTypeInfo {
description?: string
docs_url?: string
config_fields?: WebSearchProviderConfigField[]
// The parameters form as a config schema; the settings drawer renders it.
config_schema?: ConfigSchema
}
export interface WebSearchProviderConfigField {

View File

@ -119,7 +119,7 @@
</template>
<t-option v-for="item in platformOptions" :key="item.value" :value="item.value" :label="item.label">
<div class="im-platform-select-option">
<img :src="item.logo" :alt="item.label" class="im-platform-select-option__icon" />
<img v-if="item.logo" :src="item.logo" :alt="item.label" class="im-platform-select-option__icon" />
<span>{{ item.label }}</span>
</div>
</t-option>
@ -146,28 +146,19 @@
<!-- Step 2: Connection -->
<div v-else-if="wizardStep === 1" class="im-step-body">
<section v-if="formData.platform !== 'wechat'" class="setting-drawer__section im-drawer__section">
<section v-if="connectionModes.length > 0" class="setting-drawer__section im-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('agentEditor.im.sectionAccess') }}</h4>
<div class="form-item">
<label class="form-label required">{{ $t('agentEditor.im.mode') }}</label>
<div class="option-chips">
<button type="button" class="option-chip"
:class="{ 'option-chip--active': formData.mode === 'websocket' }"
:disabled="formData.platform === 'mattermost'"
@click="formData.mode = 'websocket'">
{{ formData.platform === 'dingtalk' ? 'Stream' : 'WebSocket' }}
</button>
<button v-if="formData.platform !== 'dingtalk' && formData.platform !== 'qqbot'" type="button" class="option-chip" :class="{ 'option-chip--active': formData.mode === 'webhook' }"
@click="formData.mode = 'webhook'">
Webhook
<button v-for="mode in connectionModes" :key="mode" type="button" class="option-chip"
:class="{ 'option-chip--active': formData.mode === mode }"
@click="formData.mode = mode">
{{ modeLabel(mode) }}
</button>
</div>
<p class="form-desc">
{{ formData.platform === 'mattermost' ? $t('agentEditor.im.mattermostModeHint') :
formData.platform === 'yunzhijia' ? $t('agentEditor.im.yunzhijiaModeHint') :
$t('agentEditor.im.modeHint') }}
</p>
<p class="form-desc">{{ modeHint }}</p>
</div>
<div class="form-item">
@ -249,292 +240,19 @@
<section class="setting-drawer__section im-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('agentEditor.im.sectionCredentials') }}</h4>
<div class="drawer-form">
<!-- WeCom credentials -->
<template v-if="formData.platform === 'wecom'">
<div class="platform-link-hint">
<a href="https://work.weixin.qq.com/" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.wecomConsole') }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<template v-if="formData.mode === 'websocket'">
<div class="form-item">
<label class="form-label">Bot ID</label>
<t-input v-model="formData.credentials.bot_id" placeholder="Bot ID" />
</div>
<div class="form-item">
<label class="form-label">Bot Secret</label>
<t-input v-model="formData.credentials.bot_secret" type="password" placeholder="Bot Secret" />
</div>
<div class="form-item">
<label class="form-label">WebSocket Endpoint</label>
<t-input v-model="formData.credentials.ws_endpoint" placeholder="wss://openws.work.weixin.qq.com" />
<p class="form-desc">{{ $t('agentEditor.im.wecomWSEndpointHint') }}</p>
</div>
</template>
<template v-else>
<div class="form-item">
<label class="form-label">Corp ID</label>
<t-input v-model="formData.credentials.corp_id" placeholder="Corp ID" />
</div>
<div class="form-item">
<label class="form-label">Agent Secret</label>
<t-input v-model="formData.credentials.agent_secret" type="password" placeholder="Agent Secret" />
</div>
<div class="form-item">
<label class="form-label">Token</label>
<t-input v-model="formData.credentials.token" placeholder="Token" />
</div>
<div class="form-item">
<label class="form-label">EncodingAESKey</label>
<t-input v-model="formData.credentials.encoding_aes_key" placeholder="EncodingAESKey" />
</div>
<div class="form-item">
<label class="form-label">Corp Agent ID</label>
<t-input-number v-model="formData.credentials.corp_agent_id" placeholder="Corp Agent ID"
style="width: 100%;" />
</div>
<div class="form-item">
<label class="form-label">API Base URL</label>
<t-input v-model="formData.credentials.api_base_url" placeholder="https://qyapi.weixin.qq.com" />
<p class="form-desc">{{ $t('agentEditor.im.wecomAPIBaseURLHint') }}</p>
</div>
</template>
</template>
<div v-if="currentPlatform?.links?.length" class="platform-link-hint">
<a v-for="link in currentPlatform.links" :key="link.url" :href="link.url" target="_blank"
rel="noopener noreferrer" class="doc-link">
{{ link.title_key && te(link.title_key) ? t(link.title_key) : link.title }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<!-- Feishu / Lark credentials — same fields, different open platform -->
<template v-if="formData.platform === 'feishu' || formData.platform === 'lark'">
<div class="platform-link-hint">
<a :href="openPlatformConsole.url" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t(openPlatformConsole.labelKey) }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<div class="form-item">
<label class="form-label">App ID</label>
<t-input v-model="formData.credentials.app_id" placeholder="App ID" />
</div>
<div class="form-item">
<label class="form-label">App Secret</label>
<t-input v-model="formData.credentials.app_secret" type="password" placeholder="App Secret" />
</div>
<div class="form-item">
<label class="form-label">Base URL</label>
<t-input v-model="formData.credentials.api_base_url" placeholder="https://open.feishu.cn" />
<p class="form-desc">{{ $t('agentEditor.im.feishuAPIBaseURLHint') }}</p>
</div>
<template v-if="formData.mode === 'webhook'">
<div class="form-item">
<label class="form-label">Verification Token</label>
<t-input v-model="formData.credentials.verification_token" placeholder="Verification Token" />
</div>
<div class="form-item">
<label class="form-label">Encrypt Key</label>
<t-input v-model="formData.credentials.encrypt_key" type="password" placeholder="Encrypt Key" />
</div>
</template>
</template>
<!-- Slack credentials -->
<template v-if="formData.platform === 'slack'">
<div class="platform-link-hint">
<a href="https://api.slack.com/apps" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.slackConsole') }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<template v-if="formData.mode === 'websocket'">
<div class="form-item">
<label class="form-label">App Token</label>
<t-input v-model="formData.credentials.app_token" type="password" placeholder="xapp-..." />
</div>
<div class="form-item">
<label class="form-label">Bot Token</label>
<t-input v-model="formData.credentials.bot_token" type="password" placeholder="xoxb-..." />
</div>
</template>
<template v-else>
<div class="form-item">
<label class="form-label">Bot Token</label>
<t-input v-model="formData.credentials.bot_token" type="password" placeholder="xoxb-..." />
</div>
<div class="form-item">
<label class="form-label">Signing Secret</label>
<t-input v-model="formData.credentials.signing_secret" type="password" placeholder="Signing Secret" />
</div>
</template>
</template>
<!-- Telegram credentials -->
<template v-if="formData.platform === 'telegram'">
<div class="platform-link-hint">
<a href="https://t.me/BotFather" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.telegramConsole') }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<div class="form-item">
<label class="form-label">Bot Token</label>
<t-input v-model="formData.credentials.bot_token" type="password" placeholder="123456789:AABBccdd..." />
</div>
<template v-if="formData.mode === 'webhook'">
<div class="form-item">
<label class="form-label">Secret Token</label>
<t-input v-model="formData.credentials.secret_token" type="password"
placeholder="Secret Token (optional)" />
</div>
</template>
</template>
<!-- DingTalk credentials -->
<template v-if="formData.platform === 'dingtalk'">
<div class="platform-link-hint">
<a href="https://open.dingtalk.com/" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.dingtalkConsole') }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<div class="form-item">
<label class="form-label">Client ID (AppKey)</label>
<t-input v-model="formData.credentials.client_id" placeholder="Client ID / AppKey" />
</div>
<div class="form-item">
<label class="form-label">Client Secret (AppSecret)</label>
<t-input v-model="formData.credentials.client_secret" type="password"
placeholder="Client Secret / AppSecret" />
</div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.dingtalkCardTemplateId') }}</label>
<t-input v-model="formData.credentials.card_template_id"
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.schema" />
<p class="form-desc">{{ $t('agentEditor.im.dingtalkCardTemplateIdHint') }}</p>
</div>
</template>
<!-- QQBot credentials -->
<template v-if="formData.platform === 'qqbot'">
<div class="platform-link-hint">
<a href="https://q.qq.com/" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.qqbotConsole') }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<div class="form-item">
<label class="form-label">App ID</label>
<t-input v-model="formData.credentials.app_id" placeholder="QQBot App ID" />
</div>
<div class="form-item">
<label class="form-label">App Secret</label>
<t-input v-model="formData.credentials.client_secret" type="password" placeholder="QQBot App Secret" />
</div>
<div class="form-item">
<label class="form-label">API Base URL</label>
<t-input v-model="formData.credentials.api_base_url" placeholder="https://api.sgroup.qq.com" />
<p class="form-desc">{{ $t('agentEditor.im.qqbotAPIBaseURLHint') }}</p>
</div>
<div class="form-item">
<label class="form-label">Gateway URL</label>
<t-input v-model="formData.credentials.gateway_url" placeholder="wss://api.sgroup.qq.com/websocket/" />
<p class="form-desc">{{ $t('agentEditor.im.qqbotGatewayURLHint') }}</p>
</div>
</template>
<!-- Mattermost credentials -->
<template v-if="formData.platform === 'mattermost'">
<div class="platform-link-hint">
<a href="https://developers.mattermost.com/integrate/webhooks/outgoing/" target="_blank"
rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.mattermostConsole') }}
<t-icon name="link" class="link-icon" />
</a>
<span class="hint-text">{{ $t('agentEditor.im.consoleTip') }}</span>
</div>
<div class="form-item">
<label class="form-label">Site URL</label>
<t-input v-model="formData.credentials.site_url" placeholder="https://mattermost.example.com" />
</div>
<div class="form-item">
<label class="form-label">Bot Token</label>
<t-input v-model="formData.credentials.bot_token" type="password" placeholder="Bot Token" />
</div>
<div class="form-item">
<label class="form-label">Outgoing Webhook Token</label>
<t-input v-model="formData.credentials.outgoing_token" type="password"
placeholder="Token from Outgoing Webhook" />
</div>
<div class="form-item">
<label class="form-label">Bot User ID</label>
<t-input v-model="formData.credentials.bot_user_id" placeholder="Optional — filter bot self-messages" />
</div>
<div class="settings-group">
<div class="setting-row setting-row--last">
<div class="setting-info">
<label>{{ $t('agentEditor.im.mattermostPostToMain') }}</label>
<p class="desc">{{ $t('agentEditor.im.mattermostPostToMainHint') }}</p>
</div>
<div class="setting-control">
<t-switch :value="!!formData.credentials.post_to_main" size="small"
@change="(v: boolean) => { formData.credentials.post_to_main = v }" />
</div>
</div>
</div>
</template>
<!-- Yunzhijia credentials -->
<template v-if="formData.platform === 'yunzhijia'">
<div class="form-item">
<label class="form-label required">{{ $t('agentEditor.im.yunzhijiaSendMsgUrl') }}</label>
<t-input v-model="formData.credentials.send_msg_url"
placeholder="https://www.yunzhijia.com/gateway/robot/webhook/send?yzjtype=0&yzjtoken=..." />
<p class="form-desc">
{{ $t('agentEditor.im.yunzhijiaSendMsgUrlHint') }}
<a href="https://www.yunzhijia.com/opendocs/docs.html#/guide/im/robot" target="_blank"
rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.yunzhijiaRobotDoc') }}
</a>
</p>
</div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaSecret') }}</label>
<t-input v-model="formData.credentials.secret" type="password"
:placeholder="$t('agentEditor.im.yunzhijiaSecretPlaceholder')" />
<p class="form-desc">{{ $t('agentEditor.im.yunzhijiaSecretHint') }}</p>
</div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaAppId') }}</label>
<t-input v-model="formData.credentials.app_id"
:placeholder="$t('agentEditor.im.yunzhijiaAppIdPlaceholder')" />
<p class="form-desc">
{{ $t('agentEditor.im.yunzhijiaAppCredentialHint') }}
<a href="https://www.yunzhijia.com/developers/" target="_blank" rel="noopener noreferrer"
class="doc-link">
{{ $t('agentEditor.im.yunzhijiaImageDoc') }}
</a>
</p>
</div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaAppSecret') }}</label>
<t-input v-model="formData.credentials.app_secret" type="password"
:placeholder="$t('agentEditor.im.yunzhijiaAppSecretPlaceholder')" />
</div>
<div class="form-item">
<label class="form-label">{{ $t('agentEditor.im.yunzhijiaTimeout') }}</label>
<t-input-number v-model="formData.credentials.timeout_seconds" placeholder="10" :min="1" :max="60"
style="width: 100%;" />
<p class="form-desc">{{ $t('agentEditor.im.yunzhijiaTimeoutHint') }}</p>
</div>
<div class="form-item">
<label class="form-label required">{{ $t('agentEditor.im.yunzhijiaAllowedHostSuffix') }}</label>
<t-input v-model="formData.credentials.allowed_webhook_host_suffix" placeholder="yunzhijia.com" />
<p class="form-desc">{{ $t('agentEditor.im.yunzhijiaAllowedHostSuffixHint') }}</p>
</div>
</template>
<!-- Credentials from the platform's config schema; mode-specific fields follow formData.mode. -->
<SchemaForm v-if="currentPlatform?.config_schema" v-model="formData.credentials"
:schema="currentPlatform.config_schema" :context="{ mode: formData.mode }"
:errors="credentialErrors" />
<!-- WeChat credentials (QR code binding) -->
<template v-if="formData.platform === 'wechat'">
@ -594,13 +312,16 @@ import { copyWithToast } from '@/utils/clipboard';
import { normalizeOptionalString } from '@/utils/optionalString';
import {
listIMChannels, createIMChannel, updateIMChannel, deleteIMChannel, toggleIMChannel,
getWeChatQRCode, pollWeChatQRCodeStatus, listAllIMChannels,
type IMChannelOverview, type CustomAgent,
getWeChatQRCode, pollWeChatQRCodeStatus, listAllIMChannels, listIMPlatforms, getIMChannel,
type IMChannelOverview, type CustomAgent, type IMPlatformInfo,
} from '@/api/agent';
import { useChatResourcesStore } from '@/stores/chatResources';
import type { IMChannel } from '@/api/agent';
import { useAuthStore } from '@/stores/auth';
import SettingDrawer from '@/components/settings/SettingDrawer.vue';
import SchemaForm from '@/components/schema-form/SchemaForm.vue';
import { applyDefaults, schemaAt, validateConfig, type FieldError } from '@/components/schema-form/schema';
import { useSchemaText } from '@/components/schema-form/useSchemaText';
import IntegrationsAgentFilter from '@/components/IntegrationsAgentFilter.vue';
import wecomLogo from '@/assets/img/im/wecom.svg';
import feishuLogo from '@/assets/img/im/feishu.svg';
@ -631,8 +352,43 @@ const PLATFORM_LOGO: Record<string, string> = {
const platformLogo = (platform: string): string => (platform ? PLATFORM_LOGO[platform] || '' : '');
const { t } = useI18n();
const { t, te, locale } = useI18n();
const authStore = useAuthStore();
const schemaText = useSchemaText();
// Platforms with a registered adapter, from the backend: modes, links and
// the credential form of each.
const platforms = ref<IMPlatformInfo[]>([]);
async function loadPlatforms() {
try {
const res = await listIMPlatforms();
platforms.value = res.data || [];
} catch (e: any) {
MessagePlugin.error(e?.message || t('common.operationFailed'));
}
}
const currentPlatform = computed(() => platforms.value.find((p) => p.id === formData.value.platform));
// Modes offered as chips; long polling (WeChat) runs without a choice.
const connectionModes = computed(() =>
(currentPlatform.value?.modes || []).filter((m) => m !== 'longpoll'),
);
function modeLabel(mode: string): string {
const custom = currentPlatform.value?.mode_labels?.[mode];
if (custom) return custom;
return mode === 'webhook' ? 'Webhook' : 'WebSocket';
}
const modeHint = computed(() => {
const key = currentPlatform.value?.mode_hint_key;
return key && te(key) ? t(key) : t('agentEditor.im.modeHint');
});
// Field errors of the last save attempt, shown under each credential.
const credentialErrors = ref<FieldError[]>([]);
const filterAgentId = defineModel<string>('filterAgentId', { default: '' });
@ -668,18 +424,9 @@ const drawerConfirmText = computed(() =>
wizardStep.value < stepTitles.value.length - 1 ? t('common.next') : t('common.save'),
);
const platformOptions = computed(() => ([
{ value: 'wecom' as IMPlatform, label: t('agentEditor.im.wecom'), logo: wecomLogo },
{ value: 'feishu' as IMPlatform, label: t('agentEditor.im.feishu'), logo: feishuLogo },
{ value: 'lark' as IMPlatform, label: t('agentEditor.im.lark'), logo: larkLogo },
{ value: 'slack' as IMPlatform, label: t('agentEditor.im.slack'), logo: slackLogo },
{ value: 'telegram' as IMPlatform, label: t('agentEditor.im.telegram'), logo: telegramLogo },
{ value: 'dingtalk' as IMPlatform, label: t('agentEditor.im.dingtalk'), logo: dingtalkLogo },
{ value: 'mattermost' as IMPlatform, label: t('agentEditor.im.mattermost'), logo: mattermostLogo },
{ value: 'wechat' as IMPlatform, label: t('agentEditor.im.wechat'), logo: wechatLogo },
{ value: 'qqbot' as IMPlatform, label: t('agentEditor.im.qqbot'), logo: qqbotLogo },
{ value: 'yunzhijia' as IMPlatform, label: t('agentEditor.im.yunzhijia'), logo: yunzhijiaLogo },
]));
const platformOptions = computed(() =>
platforms.value.map((p) => ({ value: p.id as IMPlatform, label: platformLabel(p.id), logo: platformLogo(p.id) })),
);
const localeOptions = computed(() => ([
{ value: '' as IMLocale, label: t('agentEditor.im.replyLanguageDefault') },
@ -690,14 +437,6 @@ const localeOptions = computed(() => ([
{ value: 'ru-RU' as IMLocale, label: 'Русский' },
]));
// Feishu and Lark are the same product on separate clouds, so each has its own
// open platform console. Bots must be created on the one matching the channel.
const openPlatformConsole = computed(() =>
formData.value.platform === 'lark'
? { url: 'https://open.larksuite.com/', labelKey: 'agentEditor.im.larkConsole' }
: { url: 'https://open.feishu.cn/', labelKey: 'agentEditor.im.feishuConsole' },
);
const drawerTitle = computed(() => {
if (editingChannel.value) {
return formData.value.name?.trim() || t('agentEditor.im.unnamed');
@ -787,7 +526,9 @@ function agentForChannel(channel: IMChannel | IMChannelOverview): CustomAgent |
function platformLabel(platform: string): string {
const key = `agentEditor.im.${platform}`;
return t(key);
if (te(key)) return t(key);
const info = platforms.value.find((p) => p.id === platform);
return info?.names?.[locale.value] || info?.name || platform;
}
function defaultChannelName(platform: string = formData.value.platform): string {
@ -799,19 +540,15 @@ function resolvedChannelName(): string {
}
function platformSupportsThread(platform: string): boolean {
return ['slack', 'mattermost', 'feishu', 'lark', 'telegram', 'yunzhijia'].includes(platform);
return !!platforms.value.find((p) => p.id === platform)?.supports_thread;
}
watch(
() => formData.value.platform,
(p) => {
if (p === 'dingtalk' || p === 'qqbot') formData.value.mode = 'websocket';
if (p === 'mattermost') {
formData.value.mode = 'webhook';
if (typeof formData.value.credentials.post_to_main !== 'boolean') {
formData.value.credentials.post_to_main = false;
}
}
const modes = currentPlatform.value?.modes || [];
if (modes.length > 0 && !modes.includes(formData.value.mode)) formData.value.mode = modes[0];
applyCredentialDefaults();
if (!platformSupportsThread(p)) {
formData.value.session_mode = 'user';
}
@ -828,43 +565,52 @@ const wechatBound = computed(() => {
function onPlatformChange(val: string | number | boolean) {
if (editingChannel.value) return;
formData.value.credentials = defaultCredentials();
credentialErrors.value = [];
stopWeChatPolling();
wechatQRContent.value = '';
wechatQRImgUrl.value = '';
wechatQRCode.value = '';
wechatQRStatus.value = '';
// WeChat uses fixed mode/output
if (val === 'wechat') {
formData.value.mode = 'longpoll';
formData.value.output_mode = 'full';
} else if (val === 'mattermost' || val === 'yunzhijia') {
formData.value.mode = 'webhook';
formData.value.output_mode = 'stream';
if (val === 'yunzhijia') {
formData.value.credentials = {
timeout_seconds: 10,
allowed_webhook_host_suffix: 'yunzhijia.com',
};
}
} else {
formData.value.mode = 'websocket';
formData.value.output_mode = 'stream';
}
// Each platform starts on its default mode; long polling (WeChat) only
// supports full output.
const info = platforms.value.find((p) => p.id === val);
formData.value.mode = info?.modes?.[0] || 'websocket';
formData.value.output_mode = formData.value.mode === 'longpoll' ? 'full' : 'stream';
applyCredentialDefaults();
if (!channelNameTouched.value) {
formData.value.name = defaultChannelName(String(val));
}
}
function normalizeYunzhijiaCredentials() {
if (formData.value.platform !== 'yunzhijia') return;
if (!formData.value.credentials.allowed_webhook_host_suffix) {
formData.value.credentials.allowed_webhook_host_suffix = 'yunzhijia.com';
}
if (!formData.value.credentials.timeout_seconds) {
formData.value.credentials.timeout_seconds = 10;
// Fills the platform's schema defaults (Yunzhijia's host suffix and timeout,
// Mattermost's post_to_main) into missing credentials.
function applyCredentialDefaults() {
const schema = currentPlatform.value?.config_schema;
if (!schema) return;
const filled = applyDefaults(schema, formData.value.credentials);
// Assign only on change: a no-op write would still trigger the watcher that
// clears the errors checkCredentials just set.
if (JSON.stringify(filled) !== JSON.stringify(formData.value.credentials)) {
formData.value.credentials = filled;
}
}
// Checks the credentials against the platform schema for the chosen mode,
// marking failing fields and warning with the first.
function checkCredentials(): boolean {
const schema = currentPlatform.value?.config_schema;
if (!schema) return true;
credentialErrors.value = validateConfig(schema, formData.value.credentials, {
context: { mode: formData.value.mode },
});
const first = credentialErrors.value[0];
if (!first) return true;
const field = schemaAt(schema, first.path);
const label = field ? schemaText(field, 'title') : first.path;
MessagePlugin.warning(`${label}: ${t(`schemaForm.errors.${first.code}`)}`);
return false;
}
async function startWeChatBinding() {
stopWeChatPolling();
wechatLoading.value = true;
@ -978,16 +724,15 @@ function openDrawer(channel: IMChannel | IMChannelOverview) {
async function editChannel(channel: IMChannel | IMChannelOverview) {
wizardStep.value = 0;
// List responses carry no credentials; load the channel with its
// credentials (secrets redacted) so the form shows what is configured and a
// save does not send an empty credential map.
let fullChannel: IMChannel | null = null;
if (!('credentials' in channel)) {
try {
const res = await listIMChannels(channel.agent_id);
fullChannel = (res.data || []).find((item) => item.id === channel.id) || null;
} catch {
fullChannel = null;
}
} else {
fullChannel = channel as IMChannel;
try {
const res = await getIMChannel(channel.id);
fullChannel = res.data || null;
} catch {
fullChannel = null;
}
if (!fullChannel) {
MessagePlugin.error(t('common.operationFailed'));
@ -1007,7 +752,8 @@ async function editChannel(channel: IMChannel | IMChannelOverview) {
knowledge_base_id: fullChannel.knowledge_base_id || '',
credentials: { ...fullChannel.credentials },
};
normalizeYunzhijiaCredentials();
applyCredentialDefaults();
credentialErrors.value = [];
showCreateDialog.value = true;
}
@ -1042,15 +788,8 @@ async function handleSave() {
MessagePlugin.warning(t('agentEditor.im.wechatScanBind'));
return;
}
if (formData.value.platform === 'yunzhijia') {
// normalize fills in the default allowed host suffix, so only the send URL
// needs explicit validation here.
normalizeYunzhijiaCredentials();
if (!String(formData.value.credentials.send_msg_url || '').trim()) {
MessagePlugin.warning(t('agentEditor.im.yunzhijiaSendMsgUrlRequired'));
return;
}
}
applyCredentialDefaults();
if (!checkCredentials()) return;
if (editingChannel.value) {
await updateIMChannel(editingChannel.value.id, {
@ -1115,8 +854,11 @@ async function handleDelete(id: string) {
onMounted(() => {
loadChannels();
loadPlatforms();
});
watch(() => formData.value.credentials, () => { credentialErrors.value = []; }, { deep: true });
watch(filterAgentId, (id) => {
if (!showCreateDialog.value && !editingChannel.value && id) {
formData.value.target_agent_id = id;

View File

@ -346,38 +346,14 @@
<div v-if="secretExtraField && !isEdit && formData.provider !== 'weknoracloud'" class="form-item">
<label class="form-label" :class="{ required: secretExtraField.required }">{{ extraFieldDisplayLabel(secretExtraField) }}</label>
<t-input v-model="formData.appSecret" type="password"
:placeholder="secretExtraField.placeholder || ''" autocomplete="new-password" spellcheck="false">
:placeholder="extraFieldDisplayPlaceholder(secretExtraField)" autocomplete="new-password" spellcheck="false">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
<p v-if="secretExtraField.placeholder" class="form-desc">{{ secretExtraField.placeholder }}</p>
<p v-if="extraFieldDisplayPlaceholder(secretExtraField)" class="form-desc">{{ extraFieldDisplayPlaceholder(secretExtraField) }}</p>
</div>
<!-- 厂商声明的其余额外字段:按 type 动态渲染,值存入 extra_config[key] -->
<div v-for="field in plainExtraFields" :key="field.key" class="form-item">
<label class="form-label" :class="{ required: field.required }">{{ extraFieldDisplayLabel(field) }}</label>
<div v-if="field.type === 'boolean'" class="vision-toggle">
<t-switch :model-value="extraConfigBool(field.key)"
@update:model-value="(v: boolean) => setExtraConfig(field.key, v ? 'true' : 'false')" />
<span v-if="extraFieldDisplayPlaceholder(field)" class="form-desc form-desc--inline">{{ extraFieldDisplayPlaceholder(field) }}</span>
</div>
<t-select v-else-if="field.type === 'select'" :model-value="formData.extraConfig[field.key] || ''"
:placeholder="extraFieldDisplayPlaceholder(field)" clearable
@update:model-value="(v: string) => setExtraConfig(field.key, v)">
<t-option v-for="opt in (field.options || [])" :key="opt.value" :value="opt.value"
:label="extraFieldDisplayOptionLabel(opt)" />
</t-select>
<t-input v-else-if="field.type === 'number'" :model-value="formData.extraConfig[field.key] || ''"
type="number" :placeholder="extraFieldDisplayPlaceholder(field)"
@update:model-value="(v: string | number) => setExtraConfig(field.key, String(v ?? ''))" />
<t-input v-else-if="field.type === 'password'" :model-value="formData.extraConfig[field.key] || ''"
type="password" :placeholder="extraFieldDisplayPlaceholder(field)" autocomplete="new-password" spellcheck="false"
@update:model-value="(v: string) => setExtraConfig(field.key, v)">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
<t-input v-else :model-value="formData.extraConfig[field.key] || ''"
:placeholder="extraFieldDisplayPlaceholder(field)"
@update:model-value="(v: string) => setExtraConfig(field.key, v)" />
</div>
<!-- 厂商声明的其余额外字段:按厂商 configSchema 渲染,值存入 extra_config[key] -->
<SchemaForm v-model="extraConfigModel" :schema="plainExtraSchema" />
<!-- 自定义 HTTP Header(类似 OpenAI Python SDK 的 extra_headers) -->
<div v-if="formData.provider !== 'weknoracloud'" class="form-item">
@ -612,7 +588,7 @@ import {
checkOllamaModels, checkRemoteModel, testEmbeddingModel, checkRerankModel, checkASRModel, listOllamaModels,
downloadOllamaModel, getDownloadProgress, checkOllamaStatus, resolveModelCatalog,
type OllamaModelInfo, type ModelProviderOption, type ModelProviderExtraField,
type ModelProviderExtraFieldOption, type ModelCatalogEntry,
type ModelCatalogEntry,
type ResolvedModelCatalog,
} from '@/api/initialization'
import {
@ -628,9 +604,9 @@ import { useModelProvidersStore } from '@/stores/modelProviders'
import {
credentialLabelForModelType,
extraFieldLabel,
extraFieldOptionLabel,
extraFieldPlaceholder,
extraFieldsForModelType,
plainExtraConfigSchema,
pickLocalized,
providerDescription,
providerIcon,
@ -640,6 +616,7 @@ import { levelLabelKey, supportedLevels } from '@/utils/reasoningEffort'
import { DEFAULT_MODEL_CONTEXT_WINDOW, formatTokenCount } from '@/utils/contextWindow'
import { copyWithToast } from '@/utils/clipboard'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import SchemaForm from '@/components/schema-form/SchemaForm.vue'
import CredentialResource, {
type CredentialFieldDef,
type CredentialResourceApi,
@ -797,8 +774,6 @@ const matchTriggerWidth = (triggerElement: HTMLElement) => ({
const extraFieldDisplayLabel = (field: ModelProviderExtraField) => extraFieldLabel(field, currentLocale.value)
const extraFieldDisplayPlaceholder = (field: ModelProviderExtraField) =>
extraFieldPlaceholder(field, currentLocale.value)
const extraFieldDisplayOptionLabel = (option: ModelProviderExtraFieldOption) =>
extraFieldOptionLabel(option, currentLocale.value)
/**
* Vendors whose API is not a bearer-token API name their first credential
@ -841,6 +816,22 @@ const secretExtraField = computed<ModelProviderExtraField | undefined>(() =>
const plainExtraFields = computed<ModelProviderExtraField[]>(() =>
visibleExtraFields.value.filter(field => !isSecretExtraField(field)),
)
// The same plain fields as a config schema, rendered by <SchemaForm>.
const plainExtraSchema = computed(() =>
plainExtraConfigSchema(selectedProvider.value?.configSchema, activeModelType.value, RESERVED_EXTRA_CONFIG_KEYS),
)
// extra_config is a map of strings; empty values are dropped as the user
// clears them, so a cleared field falls back to the vendor default.
const extraConfigModel = computed<Record<string, unknown>>({
get: () => formData.value.extraConfig || {},
set: (value) => {
const next: Record<string, string> = {}
for (const [key, v] of Object.entries(value)) {
if (v !== undefined && v !== null && v !== '') next[key] = String(v)
}
formData.value.extraConfig = next
},
})
/** extra_config keys that belong to the connection, not to the vendor. */
const VENDOR_NEUTRAL_EXTRA_CONFIG_KEYS = ['api', 'remote_model_name'] as const
@ -863,11 +854,6 @@ const setExtraConfig = (key: string, value: string | null | undefined) => {
formData.value.extraConfig = next
}
const extraConfigBool = (key: string) => {
const raw = (formData.value.extraConfig?.[key] || '').trim().toLowerCase()
return raw === 'true' || raw === '1' || raw === 'yes'
}
/** Pre-fill vendor defaults for fields the user has not touched. */
const applyExtraFieldDefaults = () => {
for (const field of plainExtraFields.value) {

View File

@ -872,34 +872,25 @@ test('every vendor-declared string in the form goes through a locale resolver',
const template = descriptor.template?.content ?? ''
assert.ok(template.length > 0, 'the editor template should have been parsed')
// `field` is the extra-field loop variable, so any read of its placeholder
// is a vendor string rendered without resolving the locale. One input
// branch per field type plus the secret field means it is easy to bind four
// and miss the fifth, which is exactly what happened.
for (const pattern of [
/:placeholder="field\.placeholder/,
/\{\{\s*field\.placeholder\s*\}\}/,
/v-if="field\.placeholder"/,
]) {
assert.equal(
pattern.test(template), false,
`template reads field.placeholder directly (${pattern}); use extraFieldDisplayPlaceholder`,
)
}
// Options: scope to the extra-field select, because `opt` is also the loop
// variable of the model-type list and the catalog model list, whose labels
// come from i18n and from the catalog's own names.
const optionLoop = /v-for="opt in \(field\.options \|\| \[\]\)"[^>]*/.exec(template)
assert.ok(optionLoop, 'the extra-field select should loop over field.options')
// Plain extra fields render through <SchemaForm>, which resolves x-i18n
// titles, placeholders and option labels (schema-form/schema.test.ts).
assert.match(
optionLoop[0], /:label="extraFieldDisplayOptionLabel\(opt\)"/,
'extra-field option labels must resolve the locale',
template, /<SchemaForm v-model="extraConfigModel" :schema="plainExtraSchema"/,
'plain extra fields should render from the vendor config schema',
)
// And the placeholder resolver is referenced, so the checks above cannot be
// satisfied by dropping the placeholders altogether.
assert.ok(template.includes('extraFieldDisplayPlaceholder('), 'placeholders must use the resolver')
// The secret field still has its own input (it fills the app_secret slot),
// so its placeholder must go through the resolver rather than be read raw.
for (const pattern of [/secretExtraField\.placeholder/, /field\.placeholder/]) {
assert.equal(
pattern.test(template), false,
`template reads a vendor placeholder directly (${pattern}); use extraFieldDisplayPlaceholder`,
)
}
assert.ok(
template.includes('extraFieldDisplayPlaceholder(secretExtraField)'),
'the secret field placeholder must use the resolver',
)
})
test('the chat protocol override is offered only on chat and vision rows', () => {

View File

@ -0,0 +1,100 @@
<template>
<div class="schema-form">
<SchemaFormFields
:schema="schema"
:value="modelValue ?? {}"
path=""
:group="group"
:secret-mode="secretMode"
:errors="errors"
:disabled="disabled"
:context="context"
@update:value="$emit('update:modelValue', $event)"
>
<template #secret="slotProps"><slot name="secret" v-bind="slotProps" /></template>
</SchemaFormFields>
</div>
</template>
<script setup lang="ts">
import type { ConfigSchema, ConfigValue, FieldError, SecretSlotProps } from './schema'
import SchemaFormFields from './SchemaFormFields.vue'
/**
* Renders a config schema (internal/plugin/configschema) as form fields.
*
* The root uses display: contents, so each field is a direct child of the
* surrounding drawer section and picks up its spacing. Pass `group` to render
* one x-group per section. With secretMode "slot", secret fields render the
* `secret` slot instead of an input, for forms whose secrets are edited
* through a /credentials subresource.
*/
withDefaults(
defineProps<{
schema: ConfigSchema
modelValue: ConfigValue | undefined
group?: string
secretMode?: 'input' | 'slot'
errors?: FieldError[]
disabled?: boolean
/** Values "$"-prefixed x-visible-if keys read, e.g. { mode } for IM credentials. */
context?: ConfigValue
}>(),
{ group: undefined, secretMode: 'input', errors: () => [], disabled: false, context: undefined },
)
defineEmits<{ 'update:modelValue': [value: ConfigValue] }>()
defineSlots<{ secret?: (props: SecretSlotProps) => unknown }>()
</script>
<style lang="less" scoped>
.schema-form {
display: contents;
}
// Same drawer form conventions as ModelEditorDialog / WebSearchSettings.
:deep(.form-item) {
margin-bottom: 0;
}
:deep(.form-label) {
display: block;
margin-bottom: 6px;
font-size: var(--app-text-md);
font-weight: 500;
color: var(--td-text-color-primary);
line-height: 1.4;
&.required::before {
content: '*';
color: var(--td-error-color);
margin-right: 4px;
font-weight: 500;
line-height: 1;
}
}
:deep(.form-desc),
:deep(.form-error) {
margin: 4px 0 0;
font-size: var(--app-text-sm);
line-height: 1.5;
}
:deep(.form-desc) {
color: var(--td-text-color-placeholder);
}
:deep(.form-error) {
color: var(--td-error-color);
}
:deep(.t-input),
:deep(.t-select),
:deep(.t-textarea),
:deep(.t-input-number) {
width: 100%;
font-size: var(--app-text-md);
}
</style>

View File

@ -0,0 +1,113 @@
<template>
<template v-for="field in fields" :key="field.key">
<!-- Nested objects render their fields inline, in their own order. -->
<SchemaFormFields
v-if="field.schema.type === 'object'"
:schema="field.schema"
:value="childObject(field.key)"
:path="join(field.key)"
:secret-mode="secretMode"
:errors="errors"
:disabled="disabled"
:context="context"
@update:value="set(field.key, $event)"
>
<template #secret="slotProps"><slot name="secret" v-bind="slotProps" /></template>
</SchemaFormFields>
<div v-else class="form-item" :data-field="join(field.key)">
<label class="form-label" :class="{ required: field.required }">{{ text(field.schema, 'title') || field.key }}</label>
<slot
v-if="field.schema['x-secret'] && secretMode === 'slot'"
name="secret"
:path="join(field.key)"
:schema="field.schema"
:label="text(field.schema, 'title') || field.key"
:required="field.required"
/>
<component
:is="resolveWidget(field.schema)"
v-else
:model-value="value[field.key]"
:schema="field.schema"
:placeholder="text(field.schema, 'placeholder')"
:disabled="disabled"
:required="field.required"
@update:model-value="set(field.key, $event)"
/>
<p v-if="errorFor(field.key)" class="form-error">{{ errorFor(field.key) }}</p>
<p v-else-if="text(field.schema, 'description')" class="form-desc">{{ text(field.schema, 'description') }}</p>
</div>
</template>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import {
HIDDEN_WIDGET,
inGroup,
isPlainObject,
isVisible,
orderedFields,
type ConfigSchema,
type ConfigValue,
type FieldError,
type SecretSlotProps,
} from './schema'
import { useSchemaText } from './useSchemaText'
import { resolveWidget } from './widgets'
const props = defineProps<{
schema: ConfigSchema
value: ConfigValue
/** Dotted path of this level; '' for the root. */
path: string
/** Only fields of this x-group are shown at the root level. */
group?: string
secretMode: 'input' | 'slot'
errors?: FieldError[]
disabled?: boolean
/** Values "$"-prefixed x-visible-if keys read. */
context?: ConfigValue
}>()
const emit = defineEmits<{ 'update:value': [value: ConfigValue] }>()
defineSlots<{ secret?: (props: SecretSlotProps) => unknown }>()
const { t, te } = useI18n()
const text = useSchemaText()
const fields = computed(() =>
orderedFields(props.schema).filter(
f =>
f.schema['x-widget'] !== HIDDEN_WIDGET &&
isVisible(f.schema, props.value, props.context) &&
(props.path !== '' || inGroup(f.schema, props.group)),
),
)
function join(key: string) {
return props.path ? `${props.path}.${key}` : key
}
function childObject(key: string): ConfigValue {
const v = props.value[key]
return isPlainObject(v) ? v : {}
}
function set(key: string, v: unknown) {
const next: ConfigValue = { ...props.value }
if (v === undefined) delete next[key]
else next[key] = v
emit('update:value', next)
}
function errorFor(key: string): string {
const e = props.errors?.find(err => err.path === join(key))
if (!e) return ''
const k = `schemaForm.errors.${e.code}`
return te(k) ? t(k) : e.message || e.code
}
</script>

View File

@ -0,0 +1,165 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
REDACTED_SECRET,
choicesOf,
inGroup,
isVisible,
orderedFields,
resolveText,
schemaAt,
secretPaths,
validateConfig,
applyDefaults,
type ConfigSchema,
type Translator,
} from './schema'
// Same shape as the backend's web search schema for Zhipu.
const zhipu: ConfigSchema = {
type: 'object',
required: ['api_key'],
properties: {
proxy_url: { type: 'string', format: 'uri', 'x-group': 'options', 'x-order': 50 },
api_key: {
type: 'string', 'x-secret': true, 'x-widget': 'password', 'x-group': 'credentials', 'x-order': 20,
'x-i18n-keys': { title: 'webSearchSettings.apiKeyLabel' }, title: 'API key',
},
extra_config: {
type: 'object', 'x-group': 'credentials', 'x-order': 40, required: ['content_size'],
properties: {
content_size: {
type: 'string', default: 'medium', title: 'Content size',
oneOf: [{ const: 'medium', title: 'Medium' }, { const: 'high', title: 'High' }],
},
},
},
},
}
const tr = (messages: Record<string, string>, locale = 'zh-CN'): Translator => ({
t: key => messages[key] ?? key,
te: key => key in messages,
locale,
})
test('orderedFields sorts by x-order then key and marks required fields', () => {
const fields = orderedFields(zhipu)
assert.deepEqual(fields.map(f => f.key), ['api_key', 'extra_config', 'proxy_url'])
assert.equal(fields[0].required, true)
assert.equal(fields[2].required, false)
const tie = orderedFields({ type: 'object', properties: { b: {}, a: {} } })
assert.deepEqual(tie.map(f => f.key), ['a', 'b'])
})
test('isVisible and inGroup', () => {
const token: ConfigSchema = { type: 'string', 'x-visible-if': { mode: 'token', port: 8080 } }
assert.equal(isVisible(token, { mode: 'token', port: 8080 }), true)
assert.equal(isVisible(token, { mode: 'basic', port: 8080 }), false)
assert.equal(isVisible(token, undefined), false)
assert.equal(isVisible({ type: 'string' }, undefined), true)
assert.equal(inGroup(zhipu.properties!.api_key, 'credentials'), true)
assert.equal(inGroup(zhipu.properties!.api_key, 'options'), false)
assert.equal(inGroup(zhipu.properties!.api_key, undefined), true)
assert.equal(inGroup({ type: 'string' }, ''), true)
})
test('resolveText prefers a known frontend key, then x-i18n, then plain text', () => {
const apiKey = zhipu.properties!.api_key
assert.equal(resolveText(apiKey, 'title', tr({ 'webSearchSettings.apiKeyLabel': 'API 密钥' })), 'API 密钥')
assert.equal(resolveText(apiKey, 'title', tr({})), 'API key')
const plugin: ConfigSchema = {
title: 'Region',
'x-placeholder': 'e.g. bj',
'x-i18n': { title: { 'zh-CN': '地域' }, placeholder: { 'zh-CN': '例如 bj' } },
}
assert.equal(resolveText(plugin, 'title', tr({})), '地域')
assert.equal(resolveText(plugin, 'title', tr({}, 'zh-TW')), '地域', 'same language falls back')
assert.equal(resolveText(plugin, 'title', tr({}, 'en-US')), 'Region')
assert.equal(resolveText(plugin, 'placeholder', tr({}, 'en-US')), 'e.g. bj')
assert.equal(resolveText(plugin, 'placeholder', tr({})), '例如 bj')
assert.equal(resolveText(plugin, 'description', tr({})), '')
})
test('applyDefaults fills missing values recursively without overwriting', () => {
assert.deepEqual(applyDefaults(zhipu, {}), { extra_config: { content_size: 'medium' } })
assert.deepEqual(
applyDefaults(zhipu, { proxy_url: 'http://p', extra_config: { content_size: 'high' } }),
{ proxy_url: 'http://p', extra_config: { content_size: 'high' } },
)
const input = { extra_config: {} }
applyDefaults(zhipu, input)
assert.deepEqual(input, { extra_config: {} }, 'input is not mutated')
})
test('choicesOf reads oneOf, then enum', () => {
assert.deepEqual(choicesOf(zhipu.properties!.extra_config.properties!.content_size).map(c => c.value), ['medium', 'high'])
assert.deepEqual(choicesOf({ enum: ['a', 'b'] }).map(c => c.schema.title), ['a', 'b'])
assert.deepEqual(choicesOf({ type: 'string' }), [])
})
test('secretPaths walks nested objects', () => {
const s: ConfigSchema = {
type: 'object',
properties: {
token: { type: 'string', 'x-secret': true },
auth: { type: 'object', properties: { password: { type: 'string', 'x-secret': true } } },
},
}
assert.deepEqual(secretPaths(s), ['auth.password', 'token'])
})
test('validateConfig mirrors the backend rules', () => {
assert.deepEqual(validateConfig(zhipu, { api_key: 'k', extra_config: { content_size: 'high' } }), [])
assert.deepEqual(
validateConfig(zhipu, { extra_config: { content_size: 'huge' }, proxy_url: 'not a url' }),
[
{ path: 'api_key', code: 'required' },
{ path: 'extra_config.content_size', code: 'enum' },
{ path: 'proxy_url', code: 'format' },
],
)
assert.deepEqual(
validateConfig(zhipu, { extra_config: { content_size: 'high' } }, { skipSecrets: true }),
[],
'secrets edited elsewhere are not required here',
)
assert.deepEqual(validateConfig(zhipu, { api_key: REDACTED_SECRET, extra_config: { content_size: 'high' } }), [])
const hidden: ConfigSchema = {
type: 'object',
required: ['mode', 'token'],
properties: {
mode: { type: 'string' },
token: { type: 'string', minLength: 8, 'x-visible-if': { mode: 'token' } },
size: { type: 'integer', minimum: 1, maximum: 10 },
},
}
assert.deepEqual(validateConfig(hidden, { mode: 'basic' }), [])
assert.deepEqual(validateConfig(hidden, { mode: 'token', token: 'short', size: 2.5 }), [
{ path: 'size', code: 'type' },
{ path: 'token', code: 'min_length' },
])
assert.deepEqual(validateConfig(hidden, { mode: 'basic', size: 11 }), [{ path: 'size', code: 'maximum' }])
})
test('schemaAt follows dotted paths', () => {
assert.equal(schemaAt(zhipu, 'extra_config.content_size')?.default, 'medium')
assert.equal(schemaAt(zhipu, 'api_key')?.['x-secret'], true)
assert.equal(schemaAt(zhipu, 'extra_config.missing'), undefined)
assert.equal(schemaAt(zhipu, 'api_key.deeper'), undefined)
})
test('"$" keys in x-visible-if read the context', () => {
const s: ConfigSchema = {
type: 'object',
required: ['signing_secret'],
properties: { signing_secret: { type: 'string', 'x-visible-if': { $mode: 'webhook' } } },
}
assert.equal(isVisible(s.properties!.signing_secret, {}, { mode: 'webhook' }), true)
assert.equal(isVisible(s.properties!.signing_secret, { mode: 'webhook' }, { mode: 'websocket' }), false)
assert.deepEqual(validateConfig(s, {}, { context: { mode: 'websocket' } }), [])
assert.deepEqual(validateConfig(s, {}, { context: { mode: 'webhook' } }), [{ path: 'signing_secret', code: 'required' }])
})

View File

@ -0,0 +1,289 @@
// Config schemas as the backend serves them (internal/plugin/configschema):
// a JSON Schema subset plus x- keywords for the form. This module is the
// pure part of <SchemaForm>: ordering, visibility, text lookup, defaults and
// validation, kept free of Vue so it runs under node:test.
export type SchemaType = 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array'
/** Text slots a field can localize. */
export type TextSlot = 'title' | 'description' | 'placeholder'
export interface ConfigSchema {
type?: SchemaType
title?: string
description?: string
properties?: Record<string, ConfigSchema>
required?: string[]
items?: ConfigSchema
default?: unknown
const?: unknown
enum?: unknown[]
oneOf?: ConfigSchema[]
minLength?: number
maxLength?: number
pattern?: string
minimum?: number
maximum?: number
format?: string
'x-secret'?: boolean
'x-widget'?: string
'x-placeholder'?: string
'x-i18n'?: Partial<Record<TextSlot, Record<string, string>>>
'x-i18n-keys'?: Partial<Record<TextSlot, string>>
'x-visible-if'?: Record<string, unknown>
'x-group'?: string
'x-order'?: number
'x-model-types'?: string[]
}
export type ConfigValue = Record<string, unknown>
/** Same codes as configschema.FieldError on the backend. */
export type FieldErrorCode =
| 'required' | 'type' | 'enum' | 'min_length' | 'max_length'
| 'pattern' | 'minimum' | 'maximum' | 'format'
export interface FieldError {
path: string
code: FieldErrorCode
message?: string
}
/** x-widget value that keeps a declared field out of the form. */
export const HIDDEN_WIDGET = 'hidden'
/** Same value the backend sends for a set secret. */
export const REDACTED_SECRET = '***'
/** Props of the `secret` slot of <SchemaForm> in secretMode "slot". */
export interface SecretSlotProps {
path: string
schema: ConfigSchema
label: string
required: boolean
}
export interface SchemaField {
key: string
schema: ConfigSchema
required: boolean
}
/** Properties in form order: x-order, then key. */
export function orderedFields(schema: ConfigSchema | undefined): SchemaField[] {
const props = schema?.properties ?? {}
const required = new Set(schema?.required ?? [])
return Object.keys(props)
.sort((a, b) => {
const oa = props[a]['x-order'] ?? 0
const ob = props[b]['x-order'] ?? 0
return oa !== ob ? oa - ob : a < b ? -1 : a > b ? 1 : 0
})
.map(key => ({ key, schema: props[key], required: required.has(key) }))
}
/** The schema node at a dotted path ("auth.token"), or undefined. */
export function schemaAt(schema: ConfigSchema, path: string): ConfigSchema | undefined {
let node: ConfigSchema | undefined = schema
for (const key of path.split('.')) {
node = node?.properties?.[key]
if (!node) return undefined
}
return node
}
/**
* x-visible-if: every listed sibling must equal the given value. Keys that
* start with "$" ("$mode") are read from context instead: values of the object
* the configuration lives in, such as an IM channel's mode.
*/
export function isVisible(
schema: ConfigSchema,
siblings: ConfigValue | undefined,
context?: ConfigValue,
): boolean {
const cond = schema['x-visible-if']
if (!cond) return true
return Object.entries(cond).every(([key, want]) => {
const got = key.startsWith('$') ? context?.[key.slice(1)] : siblings?.[key]
return looselyEqual(got, want)
})
}
/** Whether a field belongs to a group filter; no filter shows everything. */
export function inGroup(schema: ConfigSchema, group: string | undefined): boolean {
return group === undefined || (schema['x-group'] ?? '') === group
}
/** The choices a select can offer: oneOf entries, else enum values. */
export function choicesOf(schema: ConfigSchema): Array<{ value: unknown; schema: ConfigSchema }> {
if (schema.oneOf?.length) return schema.oneOf.map(c => ({ value: c.const, schema: c }))
return (schema.enum ?? []).map(v => ({ value: v, schema: { title: String(v) } }))
}
export interface Translator {
t: (key: string) => string
te: (key: string) => boolean
locale: string
}
/**
* Resolves a text slot: a frontend locale key when it exists, then the
* schema's own translation for the locale (or its language), then the plain
* text. Builtins lean on keys; plugins ship their text in x-i18n.
*/
export function resolveText(schema: ConfigSchema, slot: TextSlot, tr: Translator): string {
const key = schema['x-i18n-keys']?.[slot]
if (key && tr.te(key)) return tr.t(key)
const table = schema['x-i18n']?.[slot]
if (table) {
if (table[tr.locale]) return table[tr.locale]
const lang = tr.locale.split('-')[0]
const match = Object.keys(table).sort().find(k => k.split('-')[0] === lang && table[k])
if (match) return table[match]
}
if (slot === 'placeholder') return schema['x-placeholder'] ?? ''
return schema[slot] ?? ''
}
/**
* Fills defaults into a copy of value: missing scalars take their default and
* nested objects are filled recursively. Existing values are never replaced.
*/
export function applyDefaults(schema: ConfigSchema, value: ConfigValue | undefined): ConfigValue {
const out: ConfigValue = { ...(value ?? {}) }
for (const { key, schema: prop } of orderedFields(schema)) {
if (prop.type === 'object') {
const child = out[key]
out[key] = applyDefaults(prop, isPlainObject(child) ? child : undefined)
continue
}
if ((out[key] === undefined || out[key] === '') && prop.default !== undefined) {
out[key] = prop.default
}
}
return out
}
/** Dotted paths of every secret field. */
export function secretPaths(schema: ConfigSchema, prefix = ''): string[] {
const out: string[] = []
for (const { key, schema: prop } of orderedFields(schema)) {
const path = prefix ? `${prefix}.${key}` : key
if (prop['x-secret']) out.push(path)
if (prop.type === 'object') out.push(...secretPaths(prop, path))
}
return out
}
export interface ValidateOptions {
/** Skip secret fields entirely (they are edited elsewhere, e.g. /credentials). */
skipSecrets?: boolean
/** Values "$"-prefixed x-visible-if keys read (see isVisible). */
context?: ConfigValue
}
/**
* Mirrors configschema.Validate: required fields hidden by x-visible-if are
* not required, undeclared keys are allowed, and a redacted secret counts as
* present.
*/
export function validateConfig(
schema: ConfigSchema,
value: ConfigValue | undefined,
opts: ValidateOptions = {},
): FieldError[] {
const errors: FieldError[] = []
validateObject(schema, value ?? {}, '', errors, opts)
return errors
}
function validateObject(
schema: ConfigSchema,
value: ConfigValue,
path: string,
errors: FieldError[],
opts: ValidateOptions,
) {
for (const { key, schema: prop, required } of orderedFields(schema)) {
if (!isVisible(prop, value, opts.context)) continue
if (opts.skipSecrets && prop['x-secret']) continue
const fieldPath = path ? `${path}.${key}` : key
const v = value[key]
if (v === undefined || v === null || v === '') {
if (required) errors.push({ path: fieldPath, code: 'required' })
continue
}
validateValue(prop, v, fieldPath, errors, opts)
}
}
function validateValue(
schema: ConfigSchema,
v: unknown,
path: string,
errors: FieldError[],
opts: ValidateOptions,
) {
const add = (code: FieldErrorCode) => errors.push({ path, code })
switch (schema.type) {
case 'object':
if (!isPlainObject(v)) return add('type')
return validateObject(schema, v, path, errors, opts)
case 'array':
if (!Array.isArray(v)) return add('type')
v.forEach((item, i) => schema.items && validateValue(schema.items, item, `${path}[${i}]`, errors, opts))
return
case 'string': {
if (typeof v !== 'string') return add('type')
if (schema['x-secret'] && v === REDACTED_SECRET) return
const n = [...v].length
if (schema.minLength !== undefined && n < schema.minLength) add('min_length')
if (schema.maxLength !== undefined && n > schema.maxLength) add('max_length')
if (schema.pattern && !safeRegExp(schema.pattern)?.test(v)) add('pattern')
if (schema.format === 'uri' && !isAbsoluteURL(v)) add('format')
if (schema.format === 'email' && !/^[^\s@]+@[^\s@]+$/.test(v)) add('format')
break
}
case 'number':
case 'integer': {
if (typeof v !== 'number' || Number.isNaN(v)) return add('type')
if (schema.type === 'integer' && !Number.isInteger(v)) return add('type')
if (schema.minimum !== undefined && v < schema.minimum) add('minimum')
if (schema.maximum !== undefined && v > schema.maximum) add('maximum')
break
}
case 'boolean':
if (typeof v !== 'boolean') return add('type')
break
}
const choices = choicesOf(schema)
if (choices.length && !choices.some(c => looselyEqual(c.value, v))) add('enum')
}
function isAbsoluteURL(v: string): boolean {
try {
const u = new URL(v)
return !!u.protocol && !!u.host
} catch {
return false
}
}
function safeRegExp(pattern: string): RegExp | null {
try {
return new RegExp(pattern)
} catch {
return null
}
}
export function isPlainObject(v: unknown): v is ConfigValue {
return typeof v === 'object' && v !== null && !Array.isArray(v)
}
function looselyEqual(a: unknown, b: unknown): boolean {
if (typeof a === 'number' || typeof b === 'number') return Number(a) === Number(b) && a !== '' && b !== ''
if (isPlainObject(a) || Array.isArray(a)) return JSON.stringify(a) === JSON.stringify(b)
return a === b
}

View File

@ -0,0 +1,15 @@
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { resolveText, type ConfigSchema, type TextSlot, type Translator } from './schema'
/** Binds resolveText to the active vue-i18n locale. */
export function useSchemaText() {
const { t, te, locale } = useI18n()
const tr = computed<Translator>(() => ({
t: key => t(key),
te: key => te(key),
locale: locale.value,
}))
return (schema: ConfigSchema, slot: TextSlot) => resolveText(schema, slot, tr.value)
}

View File

@ -0,0 +1,116 @@
<template>
<div class="headers-widget">
<div v-for="(row, idx) in rows" :key="idx" class="headers-widget__row">
<t-input
v-model="row.key"
class="headers-widget__key"
:placeholder="t('model.editor.customHeadersKeyPlaceholder')"
:disabled="disabled"
autocomplete="off"
spellcheck="false"
@change="emitValue"
/>
<t-input
v-model="row.value"
class="headers-widget__value"
:placeholder="t('model.editor.customHeadersValuePlaceholder')"
:disabled="disabled"
autocomplete="off"
spellcheck="false"
@change="emitValue"
/>
<t-button
variant="text"
shape="square"
size="small"
class="headers-widget__remove"
:aria-label="t('common.delete')"
:disabled="disabled"
@click="remove(idx)"
>
<t-icon name="close" />
</t-button>
</div>
<t-button variant="text" size="small" theme="primary" :disabled="disabled" @click="add">
<template #icon><t-icon name="add" /></template>
{{ t('model.editor.customHeadersAdd') }}
</t-button>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { parseHeaders, serializeHeaders, type HeaderRow } from './headers'
import type { WidgetProps } from './types'
// Edits "Name: Value" lines (RSS auth headers) as key/value rows. Rows stay
// local so a half-typed row without a name survives; only named rows reach
// the stored value.
const props = defineProps<WidgetProps>()
const emit = defineEmits<{ 'update:modelValue': [value: unknown] }>()
const { t } = useI18n()
const rows = ref<HeaderRow[]>(parseHeaders(props.modelValue))
watch(
() => props.modelValue,
v => {
if ((v ?? '') !== serializeHeaders(rows.value)) rows.value = parseHeaders(v)
},
)
function emitValue() {
const text = serializeHeaders(rows.value)
emit('update:modelValue', text || undefined)
}
function add() {
rows.value.push({ key: '', value: '' })
}
function remove(idx: number) {
rows.value.splice(idx, 1)
emitValue()
}
</script>
<style lang="less" scoped>
.headers-widget {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.headers-widget__row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.headers-widget__key {
flex: 0 0 38%;
}
.headers-widget__value {
flex: 1;
}
.headers-widget__remove {
flex-shrink: 0;
width: 32px;
height: 32px;
padding: 0;
color: var(--td-text-color-placeholder);
border-radius: var(--app-radius-sm);
transition: all var(--app-motion-fast) ease;
&:hover {
background: var(--td-error-color-light);
color: var(--td-error-color);
}
}
</style>

View File

@ -0,0 +1,38 @@
<template>
<t-input-number
:model-value="numeric"
:placeholder="placeholder"
:disabled="disabled"
:min="schema.minimum"
:max="schema.maximum"
:decimal-places="schema.type === 'integer' ? 0 : undefined"
theme="normal"
@update:model-value="onChange"
/>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { WidgetProps } from './types'
const props = defineProps<WidgetProps>()
const emit = defineEmits<{ 'update:modelValue': [value: unknown] }>()
// A string-typed field (model vendor extra_config is a map of strings) keeps
// storing strings; the widget only changes how it is edited.
const numeric = computed(() => {
const v = props.modelValue
if (v === undefined || v === null || v === '') return undefined
const n = Number(v)
return Number.isNaN(n) ? undefined : n
})
function onChange(v: number | string | undefined) {
if (v === undefined || v === null || v === '') {
emit('update:modelValue', undefined)
return
}
emit('update:modelValue', props.schema.type === 'string' ? String(v) : Number(v))
}
</script>

View File

@ -0,0 +1,19 @@
<template>
<t-input
:model-value="(modelValue as string | undefined) ?? ''"
type="password"
autocomplete="new-password"
:placeholder="placeholder"
:disabled="disabled"
@update:model-value="$emit('update:modelValue', $event)"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</template>
<script setup lang="ts">
import type { WidgetProps } from './types'
defineProps<WidgetProps>()
defineEmits<{ 'update:modelValue': [value: unknown] }>()
</script>

View File

@ -0,0 +1,36 @@
<template>
<t-select
:model-value="modelValue as string | number | undefined"
:placeholder="placeholder"
:disabled="disabled"
:clearable="!required"
@update:model-value="$emit('update:modelValue', $event)"
>
<t-option
v-for="choice in choices"
:key="String(choice.value)"
:value="choice.value as string | number"
:label="choice.label"
/>
</t-select>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { choicesOf } from '../schema'
import { useSchemaText } from '../useSchemaText'
import type { WidgetProps } from './types'
const props = defineProps<WidgetProps>()
defineEmits<{ 'update:modelValue': [value: unknown] }>()
const text = useSchemaText()
const choices = computed(() =>
choicesOf(props.schema).map(c => ({
value: c.value,
label: text(c.schema, 'title') || String(c.value),
})),
)
</script>

View File

@ -0,0 +1,20 @@
<template>
<t-switch :model-value="checked" :disabled="disabled" @update:model-value="onChange" />
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { WidgetProps } from './types'
const props = defineProps<WidgetProps>()
const emit = defineEmits<{ 'update:modelValue': [value: unknown] }>()
// String-typed booleans ("true" / "false") are stored as strings.
const checked = computed(() => props.modelValue === true || props.modelValue === 'true')
function onChange(v: unknown) {
const on = v === true
emit('update:modelValue', props.schema.type === 'string' ? String(on) : on)
}
</script>

View File

@ -0,0 +1,16 @@
<template>
<t-input
:model-value="(modelValue as string | undefined) ?? ''"
:placeholder="placeholder"
:disabled="disabled"
:maxlength="schema.maxLength"
@update:model-value="$emit('update:modelValue', $event)"
/>
</template>
<script setup lang="ts">
import type { WidgetProps } from './types'
defineProps<WidgetProps>()
defineEmits<{ 'update:modelValue': [value: unknown] }>()
</script>

View File

@ -0,0 +1,17 @@
<template>
<t-textarea
:model-value="(modelValue as string | undefined) ?? ''"
:placeholder="placeholder"
:disabled="disabled"
:maxlength="schema.maxLength"
:autosize="{ minRows: 3, maxRows: 10 }"
@update:model-value="$emit('update:modelValue', $event)"
/>
</template>
<script setup lang="ts">
import type { WidgetProps } from './types'
defineProps<WidgetProps>()
defineEmits<{ 'update:modelValue': [value: unknown] }>()
</script>

View File

@ -0,0 +1,25 @@
export interface HeaderRow {
key: string
value: string
}
/** Parses "Name: Value" lines; lines without a colon keep an empty value. */
export function parseHeaders(text: unknown): HeaderRow[] {
if (typeof text !== 'string' || !text.trim()) return []
return text
.split('\n')
.filter(line => line.trim())
.map(line => {
const i = line.indexOf(':')
if (i < 0) return { key: line.trim(), value: '' }
return { key: line.slice(0, i).trim(), value: line.slice(i + 1).trim() }
})
}
/** Serializes rows back to "Name: Value" lines, skipping rows without a name. */
export function serializeHeaders(rows: HeaderRow[]): string {
return rows
.filter(r => r.key.trim())
.map(r => `${r.key.trim()}: ${r.value}`)
.join('\n')
}

View File

@ -0,0 +1,44 @@
import type { Component } from 'vue'
import type { ConfigSchema } from '../schema'
import HeadersWidget from './HeadersWidget.vue'
import NumberWidget from './NumberWidget.vue'
import PasswordWidget from './PasswordWidget.vue'
import SelectWidget from './SelectWidget.vue'
import SwitchWidget from './SwitchWidget.vue'
import TextWidget from './TextWidget.vue'
import TextareaWidget from './TextareaWidget.vue'
/**
* Form controls by x-widget name. Only the frontend registers widgets;
* plugins pick one by name, and anything richer belongs in a plugin page.
*/
const widgets = new Map<string, Component>([
['text', TextWidget],
['password', PasswordWidget],
['textarea', TextareaWidget],
['number', NumberWidget],
['select', SelectWidget],
['switch', SwitchWidget],
// "Name: Value" lines edited as rows (RSS auth headers).
['headers', HeadersWidget],
])
export function registerWidget(name: string, component: Component) {
widgets.set(name, component)
}
/** The widget name for a field: x-widget when known, else inferred. */
export function widgetName(schema: ConfigSchema): string {
const explicit = schema['x-widget']
if (explicit && widgets.has(explicit)) return explicit
if (schema['x-secret']) return 'password'
if (schema.oneOf?.length || schema.enum?.length) return 'select'
if (schema.type === 'boolean') return 'switch'
if (schema.type === 'number' || schema.type === 'integer') return 'number'
return 'text'
}
export function resolveWidget(schema: ConfigSchema): Component {
return widgets.get(widgetName(schema)) ?? TextWidget
}

View File

@ -0,0 +1,10 @@
import type { ConfigSchema } from '../schema'
/** Props every widget receives. Widgets emit update:modelValue. */
export interface WidgetProps {
modelValue: unknown
schema: ConfigSchema
placeholder?: string
disabled?: boolean
required?: boolean
}

View File

@ -0,0 +1,35 @@
<template>
<!-- 网络搜索:地球 -->
<svg v-if="icon.kind === 'builtin' && icon.name === 'globe'" width="17" height="17" viewBox="0 0 18 18" fill="none"
xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
</svg>
<!-- WeKnora Cloud:W -->
<svg v-else-if="icon.kind === 'builtin' && icon.name === 'weknora'" width="17" height="17" viewBox="0 0 18 18"
fill="none" xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<rect x="1.5" y="1.5" width="15" height="15" rx="3.5" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M4.5 5.5L6.5 12.5L9 7.5L11.5 12.5L13.5 5.5" stroke="currentColor" stroke-width="1.3"
stroke-linecap="round" stroke-linejoin="round" fill="none" />
</svg>
<!-- 沙箱:隔离运行窗口 -->
<svg v-else-if="icon.kind === 'builtin' && icon.name === 'sandbox'" width="17" height="17" viewBox="0 0 18 18"
fill="none" xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<rect x="2.5" y="3" width="13" height="12" rx="2" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M2.5 6.5h13" stroke="currentColor" stroke-width="1.2" />
<path d="M5.5 10h4M5.5 12.5h2.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
</svg>
<span v-else-if="icon.kind === 'emoji'" class="nav-icon nav-icon-emoji">{{ icon.value }}</span>
<t-icon v-else :name="icon.kind === 'tdesign' ? icon.name : 'setting'" class="nav-icon" />
</template>
<script setup lang="ts">
import type { SettingsNavIcon } from './settingsSections'
// Renders a settings section's sidebar icon. Styling comes from the
// .nav-icon rules of the settings modal.
defineProps<{ icon: SettingsNavIcon }>()
</script>

View File

@ -0,0 +1,101 @@
// Registers the builtin settings sections (settingsCatalog.ts) with their
// components, the same way a plugin registers its pages.
import type { Component } from 'vue'
import i18n from '@/i18n'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
import { hostSkillsOnly } from '@/utils/skillTarget'
import IntegrationSettingsSection from '@/views/integrations/IntegrationSettingsSection.vue'
import ChatHistorySettings from '@/views/settings/ChatHistorySettings.vue'
import EnvVarSettings from '@/views/settings/EnvVarSettings.vue'
import GeneralSettings from '@/views/settings/GeneralSettings.vue'
import MemorySettings from '@/views/settings/MemorySettings.vue'
import MemoryWorkspaceSettings from '@/views/settings/MemoryWorkspaceSettings.vue'
import ModelSettings from '@/views/settings/ModelSettings.vue'
import OllamaSettings from '@/views/settings/OllamaSettings.vue'
import ParserEngineSettings from '@/views/settings/ParserEngineSettings.vue'
import PluginCenter from '@/views/settings/PluginCenter.vue'
import SandboxSettings from '@/views/settings/SandboxSettings.vue'
import StorageBackendSettings from '@/views/settings/StorageBackendSettings.vue'
import SystemInfo from '@/views/settings/SystemInfo.vue'
import TenantInfo from '@/views/settings/TenantInfo.vue'
import TenantMembers from '@/views/settings/TenantMembers.vue'
import UserProfile from '@/views/settings/UserProfile.vue'
import VectorStoreSettings from '@/views/settings/VectorStoreSettings.vue'
import WebSearchSettings from '@/views/settings/WebSearchSettings.vue'
import WeKnoraCloudSettings from '@/views/settings/WeKnoraCloudSettings.vue'
import ModelCatalog from '@/views/system/ModelCatalog.vue'
import PlatformAPIKeys from '@/views/system/PlatformAPIKeys.vue'
import RuntimeQueues from '@/views/system/RuntimeQueues.vue'
import SystemAuditLog from '@/views/system/SystemAuditLog.vue'
import SystemSettings from '@/views/system/SystemSettings.vue'
import { CORE_PLUGIN_ID, settingsGroups, settingsSections } from '../settingsSections'
import { BUILTIN_SETTINGS_GROUPS, BUILTIN_SETTINGS_SECTIONS, type BuiltinSettingsSection } from './settingsCatalog'
const COMPONENTS: Record<string, Component> = {
general: GeneralSettings,
userprofile: UserProfile,
mymemory: MemorySettings,
envvars: EnvVarSettings,
tenant: TenantInfo,
members: TenantMembers,
chathistory: ChatHistorySettings,
memory: MemoryWorkspaceSettings,
models: ModelSettings,
ollama: OllamaSettings,
weknoracloud: WeKnoraCloudSettings,
vectorstore: VectorStoreSettings,
parser: ParserEngineSettings,
storage: StorageBackendSettings,
sandbox: SandboxSettings,
websearch: WebSearchSettings,
plugins: PluginCenter,
'system-global': SystemSettings,
'model-catalog': ModelCatalog,
'runtime-queues': RuntimeQueues,
'platform-api-keys': PlatformAPIKeys,
'system-audit-log': SystemAuditLog,
system: SystemInfo,
}
const t = (key: string) => i18n.global.t(key)
/** Host-only skill deployments name the page after the host's secrets. */
function envVarsLabel(): string {
const caps = useDeploymentCapabilitiesStore()
const hostSkills = hostSkillsOnly(caps.isSupported('settings.sandbox.remote'), caps.isSupported('settings.sandbox.host'))
const hostKey = 'envVarSettings.host.title'
return hostSkills && i18n.global.te(hostKey) ? t(hostKey) : t('envVarSettings.title')
}
function labelOf(section: BuiltinSettingsSection): () => string {
if (section.key === 'envvars') return envVarsLabel
return section.literal ? () => section.label : () => t(section.label)
}
let registered = false
/** Registers the builtin settings groups and sections once. */
export function registerBuiltinSettings() {
if (registered) return
registered = true
for (const group of BUILTIN_SETTINGS_GROUPS) {
settingsGroups.register({ key: group.key, order: group.order, label: () => t(group.label) })
}
for (const section of BUILTIN_SETTINGS_SECTIONS) {
const tab = section.integrationTab
settingsSections.register({
key: section.key,
group: section.group,
order: section.order,
label: labelOf(section),
icon: section.icon,
component: tab ? IntegrationSettingsSection : COMPONENTS[section.key],
props: tab ? () => ({ tab }) : undefined,
layout: section.layout,
pluginId: CORE_PLUGIN_ID,
access: section.access,
})
}
}

View File

@ -0,0 +1,119 @@
// The builtin settings sections as data: which page sits in which sidebar
// group, in what order, with what icon and access rules. Components are
// attached in settings.ts, so this file stays importable under node:test.
import { INTEGRATION_PREVIEW_ITEMS, INTEGRATION_TAB_CAPABILITY, INTEGRATION_TAB_MIN_ROLE } from '../../config/integrations'
import { SETTINGS_SECTION_CAPABILITY, skillSettingsSupported } from '../../config/deploymentCapabilities'
import { SETTINGS_SECTION_MIN_ROLE, SYSTEM_ADMIN_SETTINGS_SECTIONS } from '../../config/settingsAccess'
import { integrationSectionKey } from '../../config/settingsRoute'
import type { SettingsNavIcon, SettingsSection, SettingsSectionAccess } from '../settingsSections'
/** A sidebar group; `label` is a locale key. */
export interface BuiltinSettingsGroup {
key: string
order: number
label: string
}
/** A builtin section; `label` is a locale key unless `literal` is set. */
export interface BuiltinSettingsSection {
key: string
group: string
order: number
label: string
literal?: boolean
icon: SettingsNavIcon
layout?: SettingsSection['layout']
/** Integration tab rendered by IntegrationSettingsSection. */
integrationTab?: string
access: SettingsSectionAccess
}
/** Sidebar groups: account → workspace → models → integrations → data → plugins → system → platform. */
export const BUILTIN_SETTINGS_GROUPS: BuiltinSettingsGroup[] = [
{ key: 'account', order: 10, label: 'settings.navGroups.account' },
{ key: 'workspace', order: 20, label: 'settings.navGroups.workspace' },
{ key: 'models_runtime', order: 30, label: 'settings.navGroups.modelsRuntime' },
{ key: 'integrations', order: 40, label: 'integrations.title' },
{ key: 'data_extensions', order: 50, label: 'settings.navGroups.dataExtensions' },
{ key: 'plugins', order: 55, label: 'pluginCenter.navGroup' },
{ key: 'system_administration', order: 60, label: 'settings.navGroups.systemAdministration' },
{ key: 'platform', order: 70, label: 'settings.navGroups.platform' },
]
const icon = (name: string): SettingsNavIcon => ({ kind: 'tdesign', name })
/** Access for a workspace section, from the shared role and capability tables. */
function access(key: string): SettingsSectionAccess {
if (SYSTEM_ADMIN_SETTINGS_SECTIONS.has(key)) {
return { systemAdminOnly: true, capability: SETTINGS_SECTION_CAPABILITY[key] }
}
return { minRole: SETTINGS_SECTION_MIN_ROLE[key] ?? 'viewer', capability: SETTINGS_SECTION_CAPABILITY[key] }
}
type Row = Omit<BuiltinSettingsSection, 'group' | 'order' | 'access'> & { access?: SettingsSectionAccess }
const ROWS: Record<string, Row[]> = {
account: [
{ key: 'general', label: 'general.title', icon: icon('setting') },
{ key: 'userprofile', label: 'userProfile.title', icon: icon('user') },
{ key: 'mymemory', label: 'memorySettings.title', icon: icon('bookmark') },
// Label switches to envVarSettings.host.title on host-only skill setups.
{
key: 'envvars', label: 'envVarSettings.title', icon: icon('key'),
access: { minRole: SETTINGS_SECTION_MIN_ROLE.envvars, supported: skillSettingsSupported },
},
],
workspace: [
{ key: 'tenant', label: 'settings.tenantInfo', icon: icon('user-circle') },
{ key: 'members', label: 'tenantMember.title', icon: icon('usergroup'), layout: 'wide' },
{ key: 'chathistory', label: 'chatHistorySettings.title', icon: icon('chat') },
{ key: 'memory', label: 'memoryWorkspaceSettings.title', icon: icon('bulletpoint') },
],
models_runtime: [
{ key: 'models', label: 'settings.modelManagement', icon: icon('control-platform') },
{ key: 'ollama', label: 'Ollama', literal: true, icon: icon('server') },
{ key: 'weknoracloud', label: 'WeKnora Cloud', literal: true, icon: { kind: 'builtin', name: 'weknora' } },
],
integrations: INTEGRATION_PREVIEW_ITEMS.map((item) => ({
key: integrationSectionKey(item.key),
label: `integrations.tabs.${item.key}`,
icon: item.icon.type === 'icon' ? icon(item.icon.name) : { kind: 'emoji' as const, value: item.icon.value },
layout: 'full' as const,
integrationTab: item.key,
access: { minRole: INTEGRATION_TAB_MIN_ROLE[item.key], capability: INTEGRATION_TAB_CAPABILITY[item.key] },
})),
data_extensions: [
{ key: 'vectorstore', label: 'settings.vectorStoreEngine', icon: icon('data-base') },
{ key: 'parser', label: 'settings.parserEngine', icon: icon('file-search') },
{ key: 'storage', label: 'settings.storageEngine', icon: icon('cloud') },
{ key: 'sandbox', label: 'settings.sandbox.title', icon: { kind: 'builtin', name: 'sandbox' } },
{ key: 'websearch', label: 'settings.webSearchConfig', icon: { kind: 'builtin', name: 'globe' } },
],
// Everyone can see which plugins the workspace has; only admins switch them.
plugins: [
{ key: 'plugins', label: 'pluginCenter.title', icon: icon('app') },
],
system_administration: [
{ key: 'system-global', label: 'settings.system', icon: icon('server') },
{ key: 'model-catalog', label: 'modelCatalog.title', icon: icon('control-platform') },
{ key: 'runtime-queues', label: 'settings.taskQueue', icon: icon('queue') },
{ key: 'platform-api-keys', label: 'platformApiKeys.title', icon: icon('secured') },
{ key: 'system-audit-log', label: 'system.globalSettings.audit.tabLabel', icon: icon('history') },
],
platform: [
{ key: 'system', label: 'settings.versionInfo', icon: icon('info-circle') },
],
}
/** Every builtin section, in sidebar order within each group. */
export const BUILTIN_SETTINGS_SECTIONS: BuiltinSettingsSection[] = Object.entries(ROWS).flatMap(([group, rows]) =>
rows.map((row, i) => ({
...row,
group,
order: (i + 1) * 10,
access: row.access ?? access(row.key),
// System-admin pages use the full content width.
layout: SYSTEM_ADMIN_SETTINGS_SECTIONS.has(row.key) ? 'full' : row.layout,
})),
)

View File

@ -0,0 +1,77 @@
// The chat renderings of WeKnora's own tools, keyed by the display_type the
// backend puts on each tool result.
import type { Component } from 'vue'
import ChunkDetail from '@/views/chat/components/tool-results/ChunkDetail.vue'
import DatabaseQuery from '@/views/chat/components/tool-results/DatabaseQuery.vue'
import DocumentInfo from '@/views/chat/components/tool-results/DocumentInfo.vue'
import GraphQueryResults from '@/views/chat/components/tool-results/GraphQueryResults.vue'
import GrepResults from '@/views/chat/components/tool-results/GrepResults.vue'
import KnowledgeBaseList from '@/views/chat/components/tool-results/KnowledgeBaseList.vue'
import KnowledgeChunksList from '@/views/chat/components/tool-results/KnowledgeChunksList.vue'
import McpToolResult from '@/views/chat/components/tool-results/McpToolResult.vue'
import PlanDisplay from '@/views/chat/components/tool-results/PlanDisplay.vue'
import ReadSkillResult from '@/views/chat/components/tool-results/ReadSkillResult.vue'
import RelatedChunks from '@/views/chat/components/tool-results/RelatedChunks.vue'
import SandboxFilesResult from '@/views/chat/components/tool-results/SandboxFilesResult.vue'
import SearchResults from '@/views/chat/components/tool-results/SearchResults.vue'
import ShellExecResult from '@/views/chat/components/tool-results/ShellExecResult.vue'
import ThinkingDisplay from '@/views/chat/components/tool-results/ThinkingDisplay.vue'
import WebFetchResults from '@/views/chat/components/tool-results/WebFetchResults.vue'
import WebSearchResults from '@/views/chat/components/tool-results/WebSearchResults.vue'
import WikiEditResult from '@/views/chat/components/tool-results/WikiEditResult.vue'
import WriteSandboxFileResult from '@/views/chat/components/tool-results/WriteSandboxFileResult.vue'
import { CORE_PLUGIN_ID } from '../registry'
import { toolResultViews, type ToolResultView } from '../toolResultViews'
type View = Omit<ToolResultView, 'key' | 'pluginId'>
const dataOnly = (component: Component): View => ({ component })
const VIEWS: Record<string, View> = {
search_results: { component: SearchResults, props: (c) => ({ data: c.data, arguments: c.arguments }) },
chunk_detail: dataOnly(ChunkDetail),
related_chunks: dataOnly(RelatedChunks),
knowledge_base_list: dataOnly(KnowledgeBaseList),
document_info: dataOnly(DocumentInfo),
graph_query_results: dataOnly(GraphQueryResults),
thinking: dataOnly(ThinkingDisplay),
plan: dataOnly(PlanDisplay),
database_query: dataOnly(DatabaseQuery),
web_search_results: dataOnly(WebSearchResults),
web_fetch_results: dataOnly(WebFetchResults),
grep_results: dataOnly(GrepResults),
knowledge_chunks_list: dataOnly(KnowledgeChunksList),
wiki_write_page: dataOnly(WikiEditResult),
wiki_replace_text: dataOnly(WikiEditResult),
wiki_rename_page: dataOnly(WikiEditResult),
wiki_delete_page: dataOnly(WikiEditResult),
shell_exec: {
component: ShellExecResult,
props: (c) => ({ data: c.data, output: c.output, arguments: c.arguments }),
},
list_sandbox_files: dataOnly(SandboxFilesResult),
write_sandbox_file: dataOnly(WriteSandboxFileResult),
edit_sandbox_file: dataOnly(WriteSandboxFileResult),
read_skill: dataOnly(ReadSkillResult),
mcp_discovery: {
component: McpToolResult,
props: (c) => ({ discovery: true, data: c.data, output: c.output, arguments: c.arguments, success: c.success }),
},
mcp_call: {
component: McpToolResult,
props: (c) => ({ discovery: false, data: c.data, output: c.output, arguments: c.arguments, success: c.success }),
},
}
let registered = false
/** Registers the builtin tool result views once. */
export function registerBuiltinToolResultViews() {
if (registered) return
registered = true
for (const [key, view] of Object.entries(VIEWS)) {
toolResultViews.register({ key, pluginId: CORE_PLUGIN_ID, ...view })
}
}

View File

@ -0,0 +1,26 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { computed } from 'vue'
import { createRegistry } from './registry'
test('registry registers, rejects duplicates and unregisters', () => {
const r = createRegistry<{ key: string; n: number }>('thing')
const off = r.register({ key: 'a', n: 1 })
r.register({ key: 'b', n: 2 })
assert.deepEqual(r.items.map((i) => i.key), ['a', 'b'])
assert.equal(r.get('b')?.n, 2)
assert.throws(() => r.register({ key: 'a', n: 3 }), /thing "a" is already registered/)
off()
assert.deepEqual(r.items.map((i) => i.key), ['b'])
r.unregister('missing')
assert.equal(r.items.length, 1)
})
test('registry reads are reactive', () => {
const r = createRegistry<{ key: string }>('thing')
const count = computed(() => r.items.length)
assert.equal(count.value, 0)
r.register({ key: 'x' })
assert.equal(count.value, 1)
})

View File

@ -0,0 +1,45 @@
import { shallowReactive } from 'vue'
/** Plugin ID of what every WeKnora build ships (builtin contributions). */
export const CORE_PLUGIN_ID = 'weknora.core'
/** Anything a registry holds is addressed by a unique key. */
export interface Keyed {
key: string
}
/**
* An extension registry: builtins register at startup, plugins at runtime,
* and the UI renders whatever is registered. Reads are reactive, so a plugin
* enabled later shows up without a reload.
*/
export interface Registry<T extends Keyed> {
/** Adds an item; returns a function that removes it again. */
register(item: T): () => void
unregister(key: string): void
get(key: string): T | undefined
/** Every registered item, in registration order. */
readonly items: readonly T[]
}
export function createRegistry<T extends Keyed>(name: string): Registry<T> {
const items = shallowReactive<T[]>([])
const unregister = (key: string) => {
const i = items.findIndex((item) => item.key === key)
if (i >= 0) items.splice(i, 1)
}
return {
register(item) {
if (items.some((existing) => existing.key === item.key)) {
throw new Error(`${name} "${item.key}" is already registered`)
}
items.push(item)
return () => unregister(item.key)
},
unregister,
get: (key) => items.find((item) => item.key === key),
get items() {
return items
},
}
}

View File

@ -0,0 +1,101 @@
import type { Component } from 'vue'
import type { DeploymentCapabilityKey, DeploymentCapabilityMap } from '@/config/deploymentCapabilities'
import type { SettingsRoleKey } from '@/config/settingsAccess'
import { createRegistry } from './registry'
export { CORE_PLUGIN_ID } from './registry'
/** How a section is drawn in the settings sidebar. */
export type SettingsNavIcon =
| { kind: 'tdesign'; name: string }
| { kind: 'emoji'; value: string }
/** Hand-drawn icons kept in SettingsNavIcon.vue. */
| { kind: 'builtin'; name: 'globe' | 'weknora' | 'sandbox' }
export interface SettingsGroup {
key: string
order: number
label: () => string
}
/** Who may see a section and whether this deployment supports it. */
export interface SettingsSectionAccess {
minRole?: SettingsRoleKey
systemAdminOnly?: boolean
capability?: DeploymentCapabilityKey
/** Overrides `capability` when support depends on several capabilities. */
supported?: (capabilities: DeploymentCapabilityMap) => boolean
}
/** One page of the settings modal. */
export interface SettingsSection {
/** Also the `?section=` value in the URL. */
key: string
group: string
/** Sort order within the group (lower first). */
order: number
label: () => string
icon: SettingsNavIcon
component: Component
props?: () => Record<string, unknown>
/** Sub-entries under the section in the sidebar. */
children?: Array<{ key: string; label: string }>
/** Content width: wide for tables, full for pages with their own layout. */
layout?: 'wide' | 'full'
pluginId: string
access: SettingsSectionAccess
}
export const settingsGroups = createRegistry<SettingsGroup>('settings group')
export const settingsSections = createRegistry<SettingsSection>('settings section')
/** What the current user and deployment allow, for sectionAllowed. */
export interface SettingsAccessContext {
isSystemAdmin: boolean
canAccessAllTenants: boolean
hasRole: (role: SettingsRoleKey) => boolean
isSupported: (capability?: DeploymentCapabilityKey) => boolean
capabilities: DeploymentCapabilityMap
}
/** Whether the user may open a section at all (role and system-admin gates). */
export function sectionPermitted(section: SettingsSection, ctx: SettingsAccessContext): boolean {
const { access } = section
if (access.systemAdminOnly) return ctx.isSystemAdmin
if (ctx.canAccessAllTenants) return true
return ctx.hasRole(access.minRole ?? 'viewer')
}
/** Whether this deployment supports a section. */
export function sectionSupported(section: SettingsSection, ctx: SettingsAccessContext): boolean {
const { access } = section
if (access.supported) return access.supported(ctx.capabilities)
return ctx.isSupported(access.capability)
}
export interface SettingsNavGroup {
key: string
label: string
items: SettingsSection[]
}
/**
* Sidebar groups in group order, each with its visible sections in section
* order. Groups without a visible section are dropped, and so are sections
* whose group is not registered.
*/
export function groupSections(
groups: readonly SettingsGroup[],
visible: readonly SettingsSection[],
): SettingsNavGroup[] {
return [...groups]
.sort((a, b) => a.order - b.order)
.map((group) => ({
key: group.key,
label: group.label(),
items: visible.filter((s) => s.group === group.key).sort((a, b) => a.order - b.order),
}))
.filter((group) => group.items.length > 0)
}

View File

@ -0,0 +1,31 @@
import type { Component } from 'vue'
import { createRegistry } from './registry'
/** What a tool result view gets to render one tool call. */
export interface ToolResultContext {
displayType: string
data: Record<string, any>
output: string
arguments: Record<string, any>
success?: boolean
}
/**
* Renders the tool results whose display_type equals `key`. Tools that
* declare no view (or an unknown one) fall back to the raw output.
*/
export interface ToolResultView {
key: string
component: Component
/** Props for the component; defaults to { data }. */
props?: (ctx: ToolResultContext) => Record<string, unknown>
pluginId: string
}
export const toolResultViews = createRegistry<ToolResultView>('tool result view')
/** The props a view receives for one tool call. */
export function toolResultProps(view: ToolResultView, ctx: ToolResultContext): Record<string, unknown> {
return view.props ? view.props(ctx) : { data: ctx.data }
}

View File

@ -0,0 +1,85 @@
// Locale keys the backend names: x-i18n-keys in builtin config schemas (web
// search parameters, data source and IM credentials), IM platform link titles
// and mode hints. Only the backend references them, so the i18n audit counts this list as used; otherwise pruning would
// drop the labels. internal/plugin/builtin/i18n_keys_test.go keeps it in step
// with the backend, sorted.
export const BACKEND_SCHEMA_I18N_KEYS = [
'agentEditor.im.dingtalkCardTemplateId',
'agentEditor.im.dingtalkCardTemplateIdHint',
'agentEditor.im.dingtalkConsole',
'agentEditor.im.feishuAPIBaseURLHint',
'agentEditor.im.feishuConsole',
'agentEditor.im.larkConsole',
'agentEditor.im.mattermostConsole',
'agentEditor.im.mattermostModeHint',
'agentEditor.im.mattermostPostToMain',
'agentEditor.im.mattermostPostToMainHint',
'agentEditor.im.qqbotAPIBaseURLHint',
'agentEditor.im.qqbotConsole',
'agentEditor.im.qqbotGatewayURLHint',
'agentEditor.im.slackConsole',
'agentEditor.im.telegramConsole',
'agentEditor.im.wecomAPIBaseURLHint',
'agentEditor.im.wecomConsole',
'agentEditor.im.wecomWSEndpointHint',
'agentEditor.im.yunzhijiaAllowedHostSuffix',
'agentEditor.im.yunzhijiaAllowedHostSuffixHint',
'agentEditor.im.yunzhijiaAppCredentialHint',
'agentEditor.im.yunzhijiaAppId',
'agentEditor.im.yunzhijiaAppIdPlaceholder',
'agentEditor.im.yunzhijiaAppSecret',
'agentEditor.im.yunzhijiaAppSecretPlaceholder',
'agentEditor.im.yunzhijiaImageDoc',
'agentEditor.im.yunzhijiaModeHint',
'agentEditor.im.yunzhijiaRobotDoc',
'agentEditor.im.yunzhijiaSecret',
'agentEditor.im.yunzhijiaSecretHint',
'agentEditor.im.yunzhijiaSecretPlaceholder',
'agentEditor.im.yunzhijiaSendMsgUrl',
'agentEditor.im.yunzhijiaSendMsgUrlHint',
'agentEditor.im.yunzhijiaTimeout',
'agentEditor.im.yunzhijiaTimeoutHint',
'credential.inputPlaceholder',
'datasource.field.apiToken',
'datasource.field.appId',
'datasource.field.appSecret',
'datasource.field.authHeaders',
'datasource.field.authHeadersHint',
'datasource.field.baseUrl',
'datasource.field.baseUrlHint',
'datasource.field.clientId',
'datasource.field.clientSecret',
'datasource.field.confluenceApiToken',
'datasource.field.confluenceBaseUrl',
'datasource.field.confluenceEdition',
'datasource.field.confluenceEditionCloud',
'datasource.field.confluenceEditionServer',
'datasource.field.confluencePassword',
'datasource.field.confluenceUsername',
'datasource.field.imaApiKey',
'datasource.field.imaClientId',
'datasource.field.integrationToken',
'datasource.field.operatorId',
'datasource.field.operatorIdHint',
'datasource.gitlab.accessToken',
'datasource.gitlab.baseUrl',
'webSearchSettings.apiKeyLabel',
'webSearchSettings.apiKeyOptionalLabel',
'webSearchSettings.apiKeyPlaceholder',
'webSearchSettings.baseUrlLabel',
'webSearchSettings.baseUrlPlaceholder',
'webSearchSettings.configFields.contentHigh',
'webSearchSettings.configFields.contentMedium',
'webSearchSettings.configFields.contentSize',
'webSearchSettings.configFields.contentSizeDesc',
'webSearchSettings.configFields.searchEngine',
'webSearchSettings.configFields.searchEngineDesc',
'webSearchSettings.configFields.searchPro',
'webSearchSettings.configFields.searchQuark',
'webSearchSettings.configFields.searchSogou',
'webSearchSettings.configFields.searchStd',
'webSearchSettings.engineIdLabel',
'webSearchSettings.proxyUrlHelp',
'webSearchSettings.proxyUrlLabel',
'webSearchSettings.proxyUrlPlaceholder',
] as const

View File

@ -14,6 +14,7 @@ import {
REGISTERED_AUDIT_ACTION_ENTRIES,
} from './auditActionRegistry.ts'
import { AUDIT_ACTION_LOCALE_DEFAULTS, getAuditActionLocaleDefault } from './auditActionLocaleDefaults.ts'
import { BACKEND_SCHEMA_I18N_KEYS } from './backendSchemaKeys.ts'
import { writeLocaleModule } from './localeSerialize.ts'
import enUS from './locales/en-US.ts'
@ -285,7 +286,8 @@ function addTemplatePattern(usage: I18nUsage, template: string): void {
export function collectI18nUsageFromSources(rootDir = SOURCE_ROOT): I18nUsage {
const usage: I18nUsage = {
staticKeys: new Set<string>(),
// Backend config schemas name these keys; count them as used.
staticKeys: new Set<string>(BACKEND_SCHEMA_I18N_KEYS),
prefixes: new Set<string>(EXTRA_PREFIXES),
segmentPatterns: [],
}

View File

@ -2249,6 +2249,18 @@ export default {
baseUrlLabel: 'Instance URL',
baseUrlPlaceholder: 'https://searxng.example.com',
apiKeyPlaceholder: 'Enter API key',
configFields: {
searchEngine: 'Search engine',
searchEngineDesc: 'Select the Zhipu search engine and per-request price tier.',
searchStd: 'Standard · ¥0.01/request',
searchPro: 'Pro · ¥0.03/request',
searchSogou: 'Sogou · ¥0.05/request',
searchQuark: 'Quark · ¥0.05/request',
contentSize: 'Content size',
contentSizeDesc: 'Medium returns concise summaries; high returns more context.',
contentMedium: 'Medium',
contentHigh: 'High'
},
toasts: {
providerCreated: 'Search provider created',
providerUpdated: 'Search provider updated',
@ -2717,6 +2729,43 @@ export default {
parseCurrentKnowledgeBaseFailed: 'Failed to parse current knowledge base'
}
},
pluginCenter: {
navGroup: 'Extensions',
title: 'Plugins',
description: 'Every plugin this deployment provides, builtins included. Enable or disable them for this workspace: a disabled plugin\'s integrations leave the type lists and cannot be created, while existing ones keep working.',
searchPlaceholder: 'Search plugins, IDs or integrations',
allPoints: 'All',
empty: 'No matching plugins',
builtin: 'Builtin',
required: 'Required',
requiredHint: 'WeKnora needs this plugin; it cannot be disabled',
adminOnly: 'Only workspace admins can enable or disable plugins',
loadFailed: 'Failed to load plugins',
saveFailed: 'Failed to save the plugin setting',
enabledToast: 'Plugin enabled',
disabledToast: 'Plugin disabled',
points: {
modelVendors: 'Model vendors',
connectors: 'Data sources',
imChannels: 'IM channels',
webSearch: 'Web search',
tools: 'Agent tools',
parsers: 'Document parsing'
}
},
schemaForm: {
errors: {
required: 'This field is required',
type: 'Invalid value',
enum: 'Not one of the allowed values',
min_length: 'Too short',
max_length: 'Too long',
pattern: 'Does not match the expected format',
minimum: 'Value is too small',
maximum: 'Value is too large',
format: 'Enter a full address such as https://example.com'
}
},
common: {
add: 'Add',
me: 'Me',
@ -6858,6 +6907,7 @@ export default {
resourceHint: 'Select the spaces or folders to sync',
untitled: 'Untitled',
resourceLoadFailed: 'Failed to load resources',
typesLoadFailed: 'Failed to load data source types',
noResources: 'No wiki spaces found',
noResourcesDesc: 'The app needs wiki access via a group chat to fetch content',
noResourcesDesc_notion: 'The app needs Notion page access permissions to fetch content',

View File

@ -2249,6 +2249,18 @@ export default {
baseUrlLabel: 'インスタンスURL',
baseUrlPlaceholder: 'https://searxng.example.com',
apiKeyPlaceholder: 'APIキーを入力',
configFields: {
searchEngine: '検索エンジン',
searchEngineDesc: 'Zhipu の検索エンジンとリクエストごとの料金プランを選択します。',
searchStd: 'スタンダード · ¥0.01/回',
searchPro: 'プロ · ¥0.03/回',
searchSogou: 'Sogou · ¥0.05/回',
searchQuark: 'Quark · ¥0.05/回',
contentSize: '要約の長さ',
contentSizeDesc: '中は簡潔な要約、詳細はより多くの文脈を返します。',
contentMedium: '中',
contentHigh: '詳細'
},
toasts: {
providerCreated: '検索プロバイダを作成しました',
providerUpdated: '検索プロバイダを更新しました',
@ -2717,6 +2729,43 @@ export default {
parseCurrentKnowledgeBaseFailed: '現在のナレッジベースの解析に失敗しました'
}
},
pluginCenter: {
navGroup: '拡張',
title: 'プラグイン',
description: 'このデプロイが提供するすべてのプラグイン(組み込みを含む)を表示し、このワークスペースで有効/無効にします。無効にしたプラグインの連携は種類一覧から消えて新規作成できなくなりますが、既存のものは引き続き動作します。',
searchPlaceholder: 'プラグイン名・ID・連携を検索',
allPoints: 'すべて',
empty: '一致するプラグインはありません',
builtin: '組み込み',
required: '必須',
requiredHint: 'WeKnora に必須のため無効にできません',
adminOnly: 'プラグインの有効化・無効化はワークスペース管理者のみ可能です',
loadFailed: 'プラグインを読み込めませんでした',
saveFailed: 'プラグイン設定を保存できませんでした',
enabledToast: 'プラグインを有効にしました',
disabledToast: 'プラグインを無効にしました',
points: {
modelVendors: 'モデルベンダー',
connectors: 'データソース',
imChannels: 'IM チャネル',
webSearch: 'Web 検索',
tools: 'エージェントツール',
parsers: 'ドキュメント解析'
}
},
schemaForm: {
errors: {
required: 'この項目は必須です',
type: '値が正しくありません',
enum: '選択可能な値ではありません',
min_length: '短すぎます',
max_length: '長すぎます',
pattern: '形式が正しくありません',
minimum: '値が小さすぎます',
maximum: '値が大きすぎます',
format: 'https://example.com のような完全なアドレスを入力してください'
}
},
common: {
add: '追加',
me: '自分',
@ -6858,6 +6907,7 @@ export default {
resourceHint: '同期するスペースまたはフォルダを選択してください',
untitled: '無題',
resourceLoadFailed: 'リソースの読み込みに失敗しました',
typesLoadFailed: 'データソースの種類を読み込めませんでした',
noResources: 'Wikiスペースが見つかりません',
noResourcesDesc: 'コンテンツを取得するには、グループチャット経由でアプリにWikiのアクセス権限を付与する必要があります',
noResourcesDesc_notion: 'コンテンツを取得するには、アプリにNotionページのアクセス権限が必要です',

View File

@ -995,6 +995,7 @@ export default {
resourceHint: '동기화할 공간/폴더를 선택하세요',
untitled: '제목 없음',
resourceLoadFailed: '리소스 목록 로드 실패',
typesLoadFailed: '데이터 소스 유형을 불러오지 못했습니다',
noResources: '동기화 가능한 위키 공간을 찾을 수 없습니다',
noResourcesDesc: '앱이 콘텐츠를 가져오려면 그룹 채팅을 통해 위키 접근 권한을 얻어야 합니다',
noResourcesDesc_notion: '앱이 콘텐츠를 가져오려면 Notion 페이지 접근 권한이 필요합니다',
@ -5248,6 +5249,43 @@ export default {
belongsToOrg: '스페이스: ',
noCompatibleKbForAgent: '현재 에이전트의 도구와 범위 내 지식베이스의 기능이 일치하지 않아 참조할 수 있는 지식베이스가 없습니다.'
},
pluginCenter: {
navGroup: '확장',
title: '플러그인',
description: '이 배포가 제공하는 모든 플러그인(내장 포함)을 보고 이 워크스페이스에서 켜거나 끕니다. 끈 플러그인의 연동은 유형 목록에서 사라지고 새로 만들 수 없지만 기존 연동은 계속 동작합니다.',
searchPlaceholder: '플러그인 이름, ID 또는 연동 검색',
allPoints: '전체',
empty: '일치하는 플러그인이 없습니다',
builtin: '내장',
required: '필수',
requiredHint: 'WeKnora에 필요한 플러그인이라 끌 수 없습니다',
adminOnly: '워크스페이스 관리자만 플러그인을 켜거나 끌 수 있습니다',
loadFailed: '플러그인을 불러오지 못했습니다',
saveFailed: '플러그인 설정을 저장하지 못했습니다',
enabledToast: '플러그인을 켰습니다',
disabledToast: '플러그인을 껐습니다',
points: {
modelVendors: '모델 공급사',
connectors: '데이터 소스',
imChannels: 'IM 채널',
webSearch: '웹 검색',
tools: '에이전트 도구',
parsers: '문서 파싱'
}
},
schemaForm: {
errors: {
required: '필수 항목입니다',
type: '값이 올바르지 않습니다',
enum: '허용된 값이 아닙니다',
min_length: '너무 짧습니다',
max_length: '너무 깁니다',
pattern: '형식이 올바르지 않습니다',
minimum: '값이 너무 작습니다',
maximum: '값이 너무 큽니다',
format: 'https://example.com 과 같은 전체 주소를 입력하세요'
}
},
common: {
add: '추가',
me: '나',
@ -5804,6 +5842,18 @@ export default {
baseUrlLabel: '인스턴스 URL',
baseUrlPlaceholder: 'https://searxng.example.com',
apiKeyPlaceholder: 'API 키를 입력하세요',
configFields: {
searchEngine: '검색 엔진',
searchEngineDesc: 'Zhipu 검색 엔진과 요청당 요금 등급을 선택합니다.',
searchStd: '기본 · ¥0.01/회',
searchPro: '프로 · ¥0.03/회',
searchSogou: 'Sogou · ¥0.05/회',
searchQuark: 'Quark · ¥0.05/회',
contentSize: '요약 길이',
contentSizeDesc: '보통은 간결한 요약을, 자세히는 더 많은 맥락을 반환합니다.',
contentMedium: '보통',
contentHigh: '자세히'
},
toasts: {
providerCreated: '검색 엔진 프로바이더가 생성되었습니다',
providerUpdated: '검색 엔진 프로바이더가 업데이트되었습니다',

View File

@ -995,6 +995,7 @@ export default {
resourceHint: 'Выберите пространства или папки для синхронизации',
untitled: 'Без названия',
resourceLoadFailed: 'Не удалось загрузить список ресурсов',
typesLoadFailed: 'Не удалось загрузить типы источников данных',
noResources: 'Пространства вики не найдены',
noResourcesDesc: 'Приложению требуется доступ к вики через групповой чат для получения контента',
noResourcesDesc_notion: 'Приложению требуются права доступа к странице Notion для получения контента',
@ -5248,6 +5249,43 @@ export default {
belongsToOrg: 'Пространство: ',
noCompatibleKbForAgent: 'Инструменты текущего агента не соответствуют возможностям ни одной базы знаний в области видимости — нечего упомянуть.'
},
pluginCenter: {
navGroup: 'Расширения',
title: 'Плагины',
description: 'Все плагины этого развертывания, включая встроенные. Включайте и отключайте их для рабочего пространства: интеграции отключенного плагина пропадают из списков типов и не создаются, а существующие продолжают работать.',
searchPlaceholder: 'Поиск по названию, ID или интеграции',
allPoints: 'Все',
empty: 'Подходящих плагинов нет',
builtin: 'Встроенный',
required: 'Обязательный',
requiredHint: 'Этот плагин нужен WeKnora, его нельзя отключить',
adminOnly: 'Включать и отключать плагины могут только администраторы пространства',
loadFailed: 'Не удалось загрузить плагины',
saveFailed: 'Не удалось сохранить настройку плагина',
enabledToast: 'Плагин включен',
disabledToast: 'Плагин отключен',
points: {
modelVendors: 'Поставщики моделей',
connectors: 'Источники данных',
imChannels: 'IM-каналы',
webSearch: 'Веб-поиск',
tools: 'Инструменты агента',
parsers: 'Разбор документов'
}
},
schemaForm: {
errors: {
required: 'Обязательное поле',
type: 'Недопустимое значение',
enum: 'Недопустимый вариант',
min_length: 'Слишком коротко',
max_length: 'Слишком длинно',
pattern: 'Неверный формат',
minimum: 'Слишком маленькое значение',
maximum: 'Слишком большое значение',
format: 'Введите полный адрес, например https://example.com'
}
},
common: {
add: 'Добавить',
me: 'Я',
@ -5804,6 +5842,18 @@ export default {
baseUrlLabel: 'URL экземпляра',
baseUrlPlaceholder: 'https://searxng.example.com',
apiKeyPlaceholder: 'Введите API-ключ',
configFields: {
searchEngine: 'Поисковая система',
searchEngineDesc: 'Выберите поисковую систему Zhipu и тариф за запрос.',
searchStd: 'Стандарт · ¥0.01/запрос',
searchPro: 'Pro · ¥0.03/запрос',
searchSogou: 'Sogou · ¥0.05/запрос',
searchQuark: 'Quark · ¥0.05/запрос',
contentSize: 'Объём сводки',
contentSizeDesc: 'Средний — краткие сводки; подробный — больше контекста.',
contentMedium: 'Средний',
contentHigh: 'Подробный'
},
toasts: {
providerCreated: 'Поисковый провайдер создан',
providerUpdated: 'Поисковый провайдер обновлён',

View File

@ -997,6 +997,7 @@ export default {
resourceHint: '选择要同步的内容空间/文件夹',
untitled: '无标题',
resourceLoadFailed: '加载资源列表失败',
typesLoadFailed: '加载数据源类型失败',
noResources: '未找到可同步的知识库空间',
noResourcesDesc: '应用需要通过群聊获得知识库访问权限才能拉取内容',
noResourcesDesc_notion: '应用需要获得 Notion 页面的访问权限才能拉取内容',
@ -5250,6 +5251,43 @@ export default {
belongsToOrg: '所属空间:',
noCompatibleKbForAgent: '当前智能体的工具与作用域内知识库的能力不匹配,暂无可引用的知识库。'
},
pluginCenter: {
navGroup: '扩展',
title: '插件',
description: '查看当前部署提供的全部插件(含内置插件),并为本空间启用或停用。停用后,该插件的集成不再出现在类型列表中、不能新建,已有实例不受影响。',
searchPlaceholder: '搜索插件名称、ID 或集成',
allPoints: '全部',
empty: '没有匹配的插件',
builtin: '内置',
required: '必需',
requiredHint: 'WeKnora 运行所必需,不能停用',
adminOnly: '仅空间管理员可以启用或停用插件',
loadFailed: '加载插件列表失败',
saveFailed: '保存插件设置失败',
enabledToast: '插件已启用',
disabledToast: '插件已停用',
points: {
modelVendors: '模型厂商',
connectors: '数据源',
imChannels: 'IM 渠道',
webSearch: '联网搜索',
tools: 'Agent 工具',
parsers: '文档解析'
}
},
schemaForm: {
errors: {
required: '此项为必填',
type: '格式不正确',
enum: '不是可选的值',
min_length: '长度过短',
max_length: '长度过长',
pattern: '格式不符合要求',
minimum: '数值过小',
maximum: '数值过大',
format: '请输入完整的地址,如 https://example.com'
}
},
common: {
add: '添加',
me: '我',
@ -5806,6 +5844,18 @@ export default {
baseUrlLabel: '实例地址',
baseUrlPlaceholder: 'https://searxng.example.com',
apiKeyPlaceholder: '请输入 API 密钥',
configFields: {
searchEngine: '搜索引擎',
searchEngineDesc: '选择智谱搜索引擎及对应的单次调用价格档位。',
searchStd: '基础版 · ¥0.01/次',
searchPro: '高级版 · ¥0.03/次',
searchSogou: '搜狗 · ¥0.05/次',
searchQuark: '夸克 · ¥0.05/次',
contentSize: '摘要长度',
contentSizeDesc: '中等返回精简摘要;详细返回更多上下文。',
contentMedium: '中等',
contentHigh: '详细'
},
toasts: {
providerCreated: '搜索引擎配置已创建',
providerUpdated: '搜索引擎配置已更新',

View File

@ -12,6 +12,7 @@ import {
loadProvidersForType,
mergeProviderIndex,
normalizeModelType,
plainExtraConfigSchema,
pickLocalized,
providerDescription,
providerIcon,
@ -258,3 +259,22 @@ test('extraFieldPlaceholder resolves the locale and tolerates no placeholder', (
)
assert.equal(extraFieldPlaceholder({ key: 'k', label: 'k', type: 'string' }, 'zh-CN'), '')
})
test('plainExtraConfigSchema keeps plain fields for the model type', () => {
const schema = {
type: 'object' as const,
required: ['region', 'secret_key'],
properties: {
region: { type: 'string' as const, oneOf: [{ const: 'bj', title: 'Beijing' }] },
secret_key: { type: 'string' as const, 'x-secret': true, 'x-model-types': ['Rerank'] },
instruction: { type: 'string' as const, 'x-model-types': ['Rerank'] },
thinking_control: { type: 'string' as const },
},
}
const rerank = plainExtraConfigSchema(schema, 'rerank', new Set(['thinking_control']))
assert.deepEqual(Object.keys(rerank.properties!).sort(), ['instruction', 'region'])
assert.deepEqual(rerank.required, ['region'])
const chat = plainExtraConfigSchema(schema, 'chat', new Set(['thinking_control']))
assert.deepEqual(Object.keys(chat.properties!), ['region'])
assert.deepEqual(plainExtraConfigSchema(undefined, 'chat').properties, {})
})

View File

@ -11,6 +11,7 @@ import type {
ModelProviderExtraField,
ModelProviderOption,
} from '@/api/initialization'
import type { ConfigSchema } from '@/components/schema-form/schema'
/** Editor model types → backend ModelType names used by ExtraField.model_types. */
const FRONTEND_TO_BACKEND_MODEL_TYPE: Record<string, string> = {
@ -41,6 +42,30 @@ export function extraFieldAppliesTo(field: Pick<ModelProviderExtraField, 'model_
return restricted.some((entry) => normalizeModelType(entry) === wanted)
}
/**
* A vendor's config schema narrowed to the plain extra_config fields shown at
* one model type. Secret fields are left out (they fill the app_secret
* credential slot, edited separately), and so are keys the editor controls
* itself.
*/
export function plainExtraConfigSchema(
schema: ConfigSchema | null | undefined,
modelType: string,
reservedKeys: ReadonlySet<string> = new Set(),
): ConfigSchema {
const properties: Record<string, ConfigSchema> = {}
for (const [key, prop] of Object.entries(schema?.properties ?? {})) {
if (prop['x-secret'] || reservedKeys.has(key)) continue
if (!extraFieldAppliesTo({ model_types: prop['x-model-types'] }, modelType)) continue
properties[key] = prop
}
return {
type: 'object',
properties,
required: (schema?.required ?? []).filter((key) => key in properties),
}
}
/** Extra fields to render for a provider at one model type. */
export function extraFieldsForModelType(
fields: ReadonlyArray<ModelProviderExtraField> | null | undefined,

View File

@ -0,0 +1,12 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { localizedText } from './localizedText'
test('localizedText resolves exact locale, then language, then default', () => {
const text = { default: 'Feishu', 'zh-CN': '飞书' }
assert.equal(localizedText(text, 'zh-CN'), '飞书')
assert.equal(localizedText(text, 'zh-TW'), '飞书')
assert.equal(localizedText(text, 'en-US'), 'Feishu')
assert.equal(localizedText(undefined, 'en-US'), '')
})

View File

@ -0,0 +1,11 @@
/** Text with locale variants, as plugin manifests serve it: { default, 'zh-CN': ... }. */
export type LocalizedText = { default: string } & Record<string, string>
/** Resolves localized text for a locale: exact, then same language, then default. */
export function localizedText(text: LocalizedText | undefined, locale: string): string {
if (!text) return ''
if (text[locale]) return text[locale]
const lang = locale.split('-')[0]
const match = Object.keys(text).sort().find((k) => k !== 'default' && k.split('-')[0] === lang && text[k])
return match ? text[match] : text.default
}

View File

@ -23,7 +23,8 @@
*
* IMPORTANT: keep this list aligned with backend tool definitions
* (`internal/agent/tools/`; this map mirrors
* `internal/agent/tools/capabilities.go`). A tool missing from this map
* `internal/agent/tools/capabilities.go`, and
* `capabilities_frontend_test.go` there fails when the two differ). A tool missing from this map
* defaults to "always available" so new tools don't silently start disabled.
*/

View File

@ -1,78 +1,7 @@
<template>
<div class="tool-result-renderer">
<!-- Search Results -->
<SearchResults v-if="displayType === 'search_results'" :data="toolData as SearchResultsData"
:arguments="toolArguments" />
<!-- Chunk Detail -->
<ChunkDetail v-else-if="displayType === 'chunk_detail'" :data="toolData as ChunkDetailData" />
<!-- Related Chunks -->
<RelatedChunks v-else-if="displayType === 'related_chunks'" :data="toolData as RelatedChunksData" />
<!-- Knowledge Base List -->
<KnowledgeBaseList v-else-if="displayType === 'knowledge_base_list'" :data="toolData as KnowledgeBaseListData" />
<!-- Document Info -->
<DocumentInfo v-else-if="displayType === 'document_info'" :data="toolData as DocumentInfoData" />
<!-- Graph Query Results -->
<GraphQueryResults v-else-if="displayType === 'graph_query_results'" :data="toolData as GraphQueryResultsData" />
<!-- Thinking Display -->
<ThinkingDisplay v-else-if="displayType === 'thinking'" :data="toolData as ThinkingData" />
<!-- Plan Display -->
<PlanDisplay v-else-if="displayType === 'plan'" :data="toolData as PlanData" />
<!-- Database Query Display -->
<DatabaseQuery v-else-if="displayType === 'database_query'" :data="toolData as DatabaseQueryData" />
<!-- Web Search Results Display -->
<WebSearchResults v-else-if="displayType === 'web_search_results'" :data="toolData as WebSearchResultsData" />
<!-- Web Fetch Results Display -->
<WebFetchResults v-else-if="displayType === 'web_fetch_results'" :data="toolData as WebFetchResultsData" />
<!-- Grep Results Display -->
<GrepResults v-else-if="displayType === 'grep_results'" :data="toolData as GrepResultsData" />
<!-- Knowledge Chunks List -->
<KnowledgeChunksList v-else-if="displayType === 'knowledge_chunks_list'"
:data="toolData as KnowledgeChunksListData" />
<!-- Wiki Edit Results Display -->
<WikiEditResult
v-else-if="displayType === 'wiki_write_page' || displayType === 'wiki_replace_text' || displayType === 'wiki_rename_page' || displayType === 'wiki_delete_page'"
:data="toolData as WikiEditData" />
<ShellExecResult
v-else-if="displayType === 'shell_exec'"
:data="toolData as ShellExecData"
:output="output"
:arguments="toolArguments"
/>
<SandboxFilesResult
v-else-if="displayType === 'list_sandbox_files'"
:data="toolData as ListSandboxFilesData"
/>
<WriteSandboxFileResult
v-else-if="displayType === 'write_sandbox_file' || displayType === 'edit_sandbox_file'"
:data="toolData as WriteSandboxFileData"
/>
<ReadSkillResult
v-else-if="displayType === 'read_skill'"
:data="toolData as ReadSkillData"
/>
<McpToolResult
v-else-if="displayType === 'mcp_discovery' || displayType === 'mcp_call'"
:discovery="displayType === 'mcp_discovery'" :data="toolData"
:output="output" :arguments="toolArguments" :success="success"
/>
<!-- Views come from the tool result registry: builtins plus plugin views. -->
<component :is="view.component" v-if="view" v-bind="viewProps" />
<!-- Fallback: Display raw output -->
<div v-else class="fallback-output">
@ -88,47 +17,11 @@
<script setup lang="ts">
import { computed } from 'vue';
import type {
DisplayType,
SearchResultsData,
ChunkDetailData,
RelatedChunksData,
KnowledgeBaseListData,
DocumentInfoData,
GraphQueryResultsData,
ThinkingData,
PlanData,
DatabaseQueryData,
WebSearchResultsData,
WebFetchResultsData,
GrepResultsData,
KnowledgeChunksListData,
WikiEditData,
ShellExecData,
ListSandboxFilesData,
WriteSandboxFileData,
ReadSkillData
} from '@/types/tool-results';
import type { DisplayType } from '@/types/tool-results';
import { registerBuiltinToolResultViews } from '@/extensions/builtin/toolResultViews';
import { toolResultProps, toolResultViews } from '@/extensions/toolResultViews';
import SearchResults from './tool-results/SearchResults.vue';
import ChunkDetail from './tool-results/ChunkDetail.vue';
import RelatedChunks from './tool-results/RelatedChunks.vue';
import KnowledgeBaseList from './tool-results/KnowledgeBaseList.vue';
import DocumentInfo from './tool-results/DocumentInfo.vue';
import GraphQueryResults from './tool-results/GraphQueryResults.vue';
import ThinkingDisplay from './tool-results/ThinkingDisplay.vue';
import PlanDisplay from './tool-results/PlanDisplay.vue';
import DatabaseQuery from './tool-results/DatabaseQuery.vue';
import WebSearchResults from './tool-results/WebSearchResults.vue';
import WebFetchResults from './tool-results/WebFetchResults.vue';
import GrepResults from './tool-results/GrepResults.vue';
import KnowledgeChunksList from './tool-results/KnowledgeChunksList.vue';
import WikiEditResult from './tool-results/WikiEditResult.vue';
import ShellExecResult from './tool-results/ShellExecResult.vue';
import SandboxFilesResult from './tool-results/SandboxFilesResult.vue';
import WriteSandboxFileResult from './tool-results/WriteSandboxFileResult.vue';
import ReadSkillResult from './tool-results/ReadSkillResult.vue';
import McpToolResult from './tool-results/McpToolResult.vue';
registerBuiltinToolResultViews();
interface Props {
success?: boolean;
@ -140,10 +33,20 @@ interface Props {
const props = withDefaults(defineProps<Props>(), { success: undefined });
const displayType = computed(() => props.displayType);
const toolData = computed(() => props.toolData || {});
const output = computed(() => props.output || '');
const toolArguments = computed(() => props.arguments || {});
const view = computed(() => (props.displayType ? toolResultViews.get(props.displayType) : undefined));
const viewProps = computed(() =>
view.value
? toolResultProps(view.value, {
displayType: props.displayType ?? '',
data: props.toolData || {},
output: output.value,
arguments: props.arguments || {},
success: props.success,
})
: {},
);
</script>
<style lang="less" scoped>

View File

@ -9,6 +9,8 @@ import ts from 'typescript'
import { createRenderer, h, nextTick, reactive, ref } from 'vue'
const require = createRequire(import.meta.url)
// The dialog validates credentials with the real schema helpers.
const schemaModule = require('../../../components/schema-form/schema.ts')
const filename = fileURLToPath(new URL('./DataSourceEditorDialog.vue', import.meta.url))
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
const script = compileScript(descriptor, { id: 'datasource-editor-test' }).content
@ -32,6 +34,20 @@ async function fixture({
const calls: Array<{ method: string; args: any[] }> = []
let storedToken = configured ? 'expired-token' : ''
const api = {
// Same credential form the backend serves for GitLab.
async getConnectorTypes() {
return [{
type: 'gitlab',
config_schema: {
type: 'object',
required: ['base_url', 'access_token'],
properties: {
base_url: { type: 'string', title: 'GitLab URL', 'x-order': 1 },
access_token: { type: 'string', title: 'Personal access token', 'x-secret': true, 'x-order': 2 },
},
},
}, { type: 'yuque', config_schema: { type: 'object', properties: {} } }]
},
async validateCredentials(type: string, credentials: Record<string, string>) {
calls.push({ method: 'validateCredentials', args: [type, { ...credentials }] })
if (credentials.access_token !== 'rotated-token') throw new Error('gitlab API /user: status 401')
@ -67,6 +83,10 @@ async function fixture({
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
if (name === 'tdesign-vue-next') return { MessagePlugin: { warning() {}, success() {}, error() {} } }
if (name === '@/api/datasource') return api
if (name === '@/components/schema-form/schema') return schemaModule
if (name === '@/components/schema-form/useSchemaText') {
return { useSchemaText: () => (schema: { title?: string }) => schema.title ?? '' }
}
return { default: {} }
},
URL, console,
@ -160,7 +180,8 @@ test('an existing data source with no saved credentials tests the entered token'
test('new GitLab data sources continue to test credentials without persistence', async () => {
const f = await fixture({ create: true })
try {
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'gitlab'))
await f.vm.loadConnectorTypes()
f.vm.selectType(f.vm.connectorTypes.find((def: any) => def.type === 'gitlab'))
await f.replace()
await f.vm.testConnection()
assert.equal(f.vm.testResult, 'success')
@ -168,11 +189,25 @@ test('new GitLab data sources continue to test credentials without persistence',
} finally { f.close() }
})
test('a missing required credential blocks the connection test and marks the field', async () => {
const f = await fixture({ create: true })
try {
await f.vm.loadConnectorTypes()
f.vm.selectType(f.vm.connectorTypes.find((def: any) => def.type === 'gitlab'))
f.vm.form.config.credentials = { base_url: 'https://gitlab.example.com' }
await nextTick() // the user typed before clicking; edits clear old errors
await f.vm.testConnection()
assert.deepEqual(f.calls, [], 'nothing reaches the backend')
assert.deepEqual(JSON.stringify(f.vm.credentialErrors), JSON.stringify([{ path: 'access_token', code: 'required' }]))
} finally { f.close() }
})
test('a new Yuque data source adopts the TOC folder layout, but not the filter', async () => {
const f = await fixture({ create: true })
try {
assert.equal(f.vm.form.config.settings.folder_mode, undefined)
f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'yuque'))
await f.vm.loadConnectorTypes()
f.vm.selectType(f.vm.connectorTypes.find((def: any) => def.type === 'yuque'))
assert.equal(f.vm.form.config.settings.folder_mode, 'toc')
// The layout is a presentation choice; toc_only decides what may enter the
// knowledge base, so a new source is deliberately left without it.

View File

@ -13,9 +13,20 @@ import {
deleteDataSource,
putDataSourceCredentials,
deleteDataSourceCredentials,
getConnectorTypes,
type ConnectorMeta,
type DataSource,
type Resource,
} from '@/api/datasource'
import SchemaForm from '@/components/schema-form/SchemaForm.vue'
import {
applyDefaults,
schemaAt,
validateConfig,
type ConfigSchema,
type FieldError,
} from '@/components/schema-form/schema'
import { useSchemaText } from '@/components/schema-form/useSchemaText'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import DataSourceTypeIcon from './DataSourceTypeIcon.vue'
import { getDatasourceIconUrl } from './datasourceIcons'
@ -103,35 +114,10 @@ function cancelReplaceCredentials() {
replaceCredentialsMode.value = false
pendingRemoveCredentials.value = false
form.value.config.credentials = {}
rssAuthHeaders.value = []
testResult.value = credentialsConfigured.value ? 'success' : ''
testErrorMsg.value = ''
}
interface CustomHeaderItem {
key: string
value: string
}
const rssAuthHeaders = ref<CustomHeaderItem[]>([])
function serializeAuthHeaders(items: CustomHeaderItem[]): string {
return items
.filter(h => h.key.trim())
.map(h => `${h.key.trim()}: ${h.value}`)
.join('\n')
}
function syncRssAuthHeadersToCredentials() {
if (form.value.type !== 'rss') return
const serialized = serializeAuthHeaders(rssAuthHeaders.value)
if (serialized) {
form.value.config.credentials.auth_headers = serialized
} else {
delete form.value.config.credentials.auth_headers
}
}
// Feed URLs may still live in credentials on older rows (not returned by the
// API). The backend copies them into settings on read; fall back to the
// selected feed resource IDs when settings are still empty.
@ -147,14 +133,6 @@ function hydrateRssFeedUrlsFromConfig(config: { settings?: Record<string, any>;
return { ...settings, feed_urls: ids.join('\n') }
}
function addRssAuthHeader() {
rssAuthHeaders.value.push({ key: '', value: '' })
}
function removeRssAuthHeader(idx: number) {
rssAuthHeaders.value.splice(idx, 1)
}
function needsConnectionTest(): boolean {
return !(isEdit.value && credentialsConfigured.value && !replaceCredentialsMode.value)
}
@ -540,212 +518,50 @@ const schedulePresets = computed(() => [
{ label: t('datasource.schedule24h'), value: '0 0 2 * * *' },
])
// --- Connector definitions ---
interface ConnectorDef {
type: string
available: boolean
docUrl: string
permissionDocUrl: string
permissionPageUrl: string
requiredPermissions: string[]
fields: {
key: string
labelKey: string
placeholder: string
secret?: boolean
optional?: boolean
hintKey?: string
multiline?: boolean
fieldType?: 'custom_headers'
}[]
// --- Connectors ---
// The connectors this deployment can create, with their setup guides and
// credential forms (config_schema), come from /datasource/types.
const connectorTypes = ref<ConnectorMeta[]>([])
async function loadConnectorTypes() {
if (connectorTypes.value.length > 0) return
try {
connectorTypes.value = [...(await getConnectorTypes())]
} catch (e: any) {
MessagePlugin.error(e?.message || t('datasource.typesLoadFailed'))
}
}
const connectorDefs = computed<ConnectorDef[]>(() => [
{
type: 'feishu',
available: true,
docUrl: 'https://open.feishu.cn/app',
permissionDocUrl: 'https://open.feishu.cn/document/server-docs/docs/wiki-v2/wiki-overview',
permissionPageUrl: 'https://open.feishu.cn/app',
requiredPermissions: [
'wiki:wiki:readonly',
'drive:drive:readonly',
'drive:export:readonly',
'docx:document:readonly',
],
fields: [
{ key: 'app_id', labelKey: 'datasource.field.appId', placeholder: 'cli_xxxx' },
{ key: 'app_secret', labelKey: 'datasource.field.appSecret', placeholder: '', secret: true },
{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://open.feishu.cn', optional: true, hintKey: 'datasource.field.baseUrlHint' },
],
},
{
// Lark is Feishu's international cloud. Same wiki/docx/drive APIs and the
// same scope identifiers, but a separate console, tenant and app — an app
// created on open.feishu.cn cannot read a Lark wiki.
type: 'lark',
available: true,
docUrl: 'https://open.larksuite.com/app',
permissionDocUrl: 'https://open.larksuite.com/document/server-docs/docs/wiki-v2/wiki-overview',
permissionPageUrl: 'https://open.larksuite.com/app',
requiredPermissions: [
'wiki:wiki:readonly',
'drive:drive:readonly',
'drive:export:readonly',
'docx:document:readonly',
],
fields: [
{ key: 'app_id', labelKey: 'datasource.field.appId', placeholder: 'cli_xxxx' },
{ key: 'app_secret', labelKey: 'datasource.field.appSecret', placeholder: '', secret: true },
{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://open.feishu.cn', optional: true, hintKey: 'datasource.field.baseUrlHint' },
],
},
{
// Feishu Drive (云盘) mode: sync documents/files under a user-supplied Drive
// folder_token. Same auth as the wiki connector but no wiki:wiki:readonly
// scope - Drive only needs drive + export + docx.
type: 'feishu_drive',
available: true,
docUrl: 'https://open.feishu.cn/app',
permissionDocUrl: 'https://open.feishu.cn/document/server-docs/docs/drive-v1/file/list',
permissionPageUrl: 'https://open.feishu.cn/app',
requiredPermissions: [
'drive:drive:readonly',
'drive:export:readonly',
'docx:document:readonly',
],
fields: [
{ key: 'app_id', labelKey: 'datasource.field.appId', placeholder: 'cli_xxxx' },
{ key: 'app_secret', labelKey: 'datasource.field.appSecret', placeholder: '', secret: true },
{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://open.feishu.cn', optional: true, hintKey: 'datasource.field.baseUrlHint' },
],
},
{
// Lark Drive: international counterpart of feishu_drive.
type: 'lark_drive',
available: true,
docUrl: 'https://open.larksuite.com/app',
permissionDocUrl: 'https://open.larksuite.com/document/server-docs/docs/drive-v1/file/list',
permissionPageUrl: 'https://open.larksuite.com/app',
requiredPermissions: [
'drive:drive:readonly',
'drive:export:readonly',
'docx:document:readonly',
],
fields: [
{ key: 'app_id', labelKey: 'datasource.field.appId', placeholder: 'cli_xxxx' },
{ key: 'app_secret', labelKey: 'datasource.field.appSecret', placeholder: '', secret: true },
{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://open.larksuite.com', optional: true, hintKey: 'datasource.field.baseUrlHint' },
],
},
{
type: 'notion',
available: true,
docUrl: 'https://www.notion.so/my-integrations',
permissionDocUrl: '',
permissionPageUrl: '',
requiredPermissions: [],
fields: [
{ key: 'api_key', labelKey: 'datasource.field.integrationToken', placeholder: 'ntn_xxxx', secret: true },
],
},
{
type: 'confluence',
available: true,
docUrl: 'https://developer.atlassian.com/cloud/confluence/rest/',
permissionDocUrl: 'https://developer.atlassian.com/cloud/confluence/rest/',
permissionPageUrl: 'https://id.atlassian.com/manage-profile/security/api-tokens',
requiredPermissions: [],
fields: [
{ key: 'base_url', labelKey: 'datasource.field.confluenceBaseUrl', placeholder: 'https://confluence.example.com or https://team.atlassian.net/wiki' },
{ key: 'username', labelKey: 'datasource.field.confluenceUsername', placeholder: 'name or email' },
{ key: 'password', labelKey: 'datasource.field.confluencePassword', placeholder: 'Server/DC password', secret: true },
{ key: 'api_token', labelKey: 'datasource.field.confluenceApiToken', placeholder: 'Cloud API token', secret: true },
],
},
{
type: 'yuque',
available: true,
docUrl: 'https://www.yuque.com/yuque/developer/api',
permissionDocUrl: 'https://www.yuque.com/yuque/developer/api',
permissionPageUrl: 'https://www.yuque.com/settings/tokens',
requiredPermissions: [
'repo:read',
'doc:read',
],
fields: [
{ key: 'api_token', labelKey: 'datasource.field.apiToken', placeholder: '', secret: true },
{ key: 'base_url', labelKey: 'datasource.field.baseUrl', placeholder: 'https://www.yuque.com', optional: true, hintKey: 'datasource.field.baseUrlHint' },
],
},
{
type: 'dingtalk',
available: true,
docUrl: 'https://open.dingtalk.com/document/development/knowledge-base-overview',
permissionDocUrl: 'https://open.dingtalk.com/document/development/get-knowledge-base-list',
permissionPageUrl: 'https://open-dev.dingtalk.com/',
requiredPermissions: [
'Wiki.Workspace.Read',
'Wiki.Node.Read',
'Storage.File.Read',
],
fields: [
{ key: 'client_id', labelKey: 'datasource.field.clientId', placeholder: 'dingxxxxxxxx' },
{ key: 'client_secret', labelKey: 'datasource.field.clientSecret', placeholder: '', secret: true },
{ key: 'operator_id', labelKey: 'datasource.field.operatorId', placeholder: '', hintKey: 'datasource.field.operatorIdHint' },
],
},
{
// 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,
docUrl: '',
permissionDocUrl: '',
permissionPageUrl: '',
requiredPermissions: [],
fields: [
{ key: 'auth_headers', labelKey: 'datasource.field.authHeaders', placeholder: '', optional: true, hintKey: 'datasource.field.authHeadersHint', fieldType: 'custom_headers' },
],
},
{
type: 'gitlab', available: true, docUrl: '', permissionDocUrl: '', permissionPageUrl: '', requiredPermissions: [],
fields: [
{ key: 'base_url', labelKey: 'datasource.gitlab.baseUrl', placeholder: 'https://gitlab.example.com' },
{ key: 'access_token', labelKey: 'datasource.gitlab.accessToken', placeholder: '', secret: true },
],
},
])
const currentDef = computed(() => connectorTypes.value.find(d => d.type === form.value.type))
const EMPTY_SCHEMA: ConfigSchema = { type: 'object', properties: {} }
const credentialSchema = computed<ConfigSchema>(() => currentDef.value?.config_schema ?? EMPTY_SCHEMA)
const currentDef = computed(() => connectorDefs.value.find(d => d.type === form.value.type))
// Field errors of the last credential check, shown under each field.
const credentialErrors = ref<FieldError[]>([])
const schemaText = useSchemaText()
const displayedCredentialFields = computed(() => {
const fields = currentDef.value?.fields || []
if (form.value.type !== "confluence") return fields
watch(() => form.value.config.credentials, () => { credentialErrors.value = [] }, { deep: true })
return fields.filter((field) => {
if (field.key === "password") return form.value.config.credentials.edition !== "cloud"
if (field.key === "api_token") return form.value.config.credentials.edition === "cloud"
return true
})
})
// Checks the credential form against its schema. On failure it marks the
// fields and warns with the first one, as the editor always has.
function checkCredentials(): boolean {
credentialErrors.value = validateConfig(credentialSchema.value, form.value.config.credentials)
const first = credentialErrors.value[0]
if (!first) return true
const field = schemaAt(credentialSchema.value, first.path)
const label = field ? schemaText(field, 'title') : first.path
MessagePlugin.warning(
first.code === 'required'
? `${label} ${t('datasource.isRequired')}`
: `${label}: ${t(`schemaForm.errors.${first.code}`)}`,
)
return false
}
// --- Drawer lifecycle ---
watch(visible, async (v) => {
if (v) void loadConnectorTypes()
if (!v) {
if (!isEdit.value && tempDsId.value) {
try {
@ -772,7 +588,6 @@ watch(visible, async (v) => {
driveFolderToken.value = ''
driveFolderTokenError.value = ''
driveRootLoaded.value = false
rssAuthHeaders.value = []
gitlabProjects.value = []
if (isEdit.value && props.dataSource) {
@ -846,18 +661,6 @@ watch(
{ deep: true },
)
watch(
rssAuthHeaders,
() => {
syncRssAuthHeadersToCredentials()
if (needsConnectionTest()) {
testResult.value = ''
testErrorMsg.value = ''
}
},
{ deep: true },
)
watch(
() => form.value.config.settings.feed_urls,
() => {
@ -868,11 +671,12 @@ watch(
},
)
function selectType(def: ConnectorDef) {
if (!def.available) return
function selectType(def: ConnectorMeta) {
form.value.type = def.type
form.value.name = t(`datasource.connector.${def.type}`)
form.value.config.credentials = def.type === "confluence" ? { edition: "server" } : {}
// Schema defaults, e.g. Confluence starts on the Server edition.
form.value.config.credentials = applyDefaults(def.config_schema ?? EMPTY_SCHEMA, {})
credentialErrors.value = []
if (def.type === 'confluence') {
form.value.config.settings = { ...form.value.config.settings, edition: 'server' }
}
@ -883,24 +687,15 @@ function selectType(def: ConnectorDef) {
form.value.config.settings = { ...form.value.config.settings, folder_mode: 'toc' }
}
if (isGitLabConnector(def.type)) addGitLabProject()
rssAuthHeaders.value = []
step.value = 1
}
// --- Test connection ---
async function testConnection() {
syncRssAuthHeadersToCredentials()
syncConfluencePublicFieldsToSettings()
if (!validateRssFeedUrls()) return
if (!isEdit.value || !credentialsConfigured.value || replaceCredentialsMode.value) {
const fields = displayedCredentialFields.value
for (const f of fields) {
if (f.optional || f.fieldType === 'custom_headers') continue
if (!form.value.config.credentials[f.key]) {
MessagePlugin.warning(`${t(f.labelKey)} ${t('datasource.isRequired')}`)
return
}
}
if (!checkCredentials()) return
}
testing.value = true
@ -1087,21 +882,11 @@ function validateRssFeedUrls(): boolean {
}
function validateStep1Fields(): boolean {
syncRssAuthHeadersToCredentials()
if (!validateRssFeedUrls()) return false
if (isEdit.value && credentialsConfigured.value && !replaceCredentialsMode.value) {
return true
}
const fields = displayedCredentialFields.value
for (const f of fields) {
if (f.optional || f.fieldType === 'custom_headers') continue
if (!form.value.config.credentials[f.key]) {
MessagePlugin.warning(`${t(f.labelKey)} ${t('datasource.isRequired')}`)
return false
}
}
return true
return checkCredentials()
}
async function nextStep() {
@ -1173,7 +958,6 @@ function buildConfigPayload(): Record<string, unknown> {
// the whole submit on failure so we don't leave the row partially saved.
async function commitCredentialsIfNeeded(dsId: string): Promise<boolean> {
if (!isEdit.value || !replaceCredentialsMode.value) return true
syncRssAuthHeadersToCredentials()
syncConfluencePublicFieldsToSettings()
const filled = Object.entries(form.value.config.credentials).filter(
([, v]) => typeof v === 'string' ? v !== '' : v != null,
@ -1184,7 +968,6 @@ async function commitCredentialsIfNeeded(dsId: string): Promise<boolean> {
credentialsConfigured.value = true
replaceCredentialsMode.value = false
form.value.config.credentials = {}
rssAuthHeaders.value = []
return true
} catch (e: any) {
MessagePlugin.error(e?.message || e?.error || t('credential.saveFailed'))
@ -1420,17 +1203,15 @@ const drawerConfirmText = computed(() => {
<h4 class="setting-drawer__section-title">{{ t('datasource.step.selectType') }}</h4>
<div class="ds-type-grid">
<button
v-for="def in connectorDefs"
v-for="def in connectorTypes"
:key="def.type"
type="button"
:class="['ds-type-card', { disabled: !def.available }]"
:disabled="!def.available"
class="ds-type-card"
@click="selectType(def)"
>
<div class="ds-type-header">
<DataSourceTypeIcon :type="def.type" :size="20" />
<span class="ds-type-name">{{ t(`datasource.connector.${def.type}`) }}</span>
<span v-if="!def.available" class="ds-type-soon">{{ t('datasource.comingSoon') }}</span>
</div>
<div class="ds-type-desc">{{ t(`datasource.connectorDesc.${def.type}`) }}</div>
</button>
@ -1440,7 +1221,7 @@ const drawerConfirmText = computed(() => {
<!-- Step 1: Credentials -->
<template v-if="step === 1">
<div
v-if="currentDef && currentDef.requiredPermissions.length > 0"
v-if="currentDef?.required_permissions?.length"
class="ds-setup-guide ds-setup-guide--standalone"
>
<button
@ -1473,7 +1254,7 @@ const drawerConfirmText = computed(() => {
<span class="ds-setup-step__desc">
<template v-if="!t(`datasource.prereqStep2Desc_${form.type}`)">
<code
v-for="perm in currentDef.requiredPermissions"
v-for="perm in currentDef.required_permissions"
:key="perm"
class="ds-perm-tag"
>{{ perm }}</code>
@ -1489,8 +1270,8 @@ const drawerConfirmText = computed(() => {
</li>
</ol>
<a
v-if="currentDef.permissionPageUrl"
:href="currentDef.permissionPageUrl"
v-if="currentDef.permission_page_url"
:href="currentDef.permission_page_url"
target="_blank"
rel="noopener"
class="doc-link ds-setup-guide__link"
@ -1504,11 +1285,11 @@ const drawerConfirmText = computed(() => {
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('datasource.sectionBasic') }}</h4>
<div v-if="currentDef?.docUrl" class="inline-alert">
<div v-if="currentDef?.doc_url" class="inline-alert">
<t-icon name="info-circle-filled" class="inline-alert__icon" />
<span class="inline-alert__text">{{ t('datasource.docHint') }}</span>
<a
:href="currentDef.docUrl"
:href="currentDef.doc_url"
target="_blank"
rel="noopener"
class="inline-alert__action doc-link"
@ -1602,81 +1383,11 @@ const drawerConfirmText = computed(() => {
</div>
<template v-else-if="credentialsInputVisible">
<div v-if="form.type === 'confluence'" class="form-item">
<label class="form-label">{{ t('datasource.field.confluenceEdition') }}</label>
<t-select v-model="form.config.credentials.edition">
<t-option value="server" :label="t('datasource.field.confluenceEditionServer')" />
<t-option value="cloud" :label="t('datasource.field.confluenceEditionCloud')" />
</t-select>
</div>
<div
v-for="field in displayedCredentialFields"
:key="field.key"
class="form-item"
>
<template v-if="field.fieldType === 'custom_headers'">
<div class="custom-headers-header">
<label class="form-label" style="margin-bottom: 0;">{{ t(field.labelKey) }}</label>
<t-button variant="text" size="small" theme="primary" @click="addRssAuthHeader">
<template #icon><t-icon name="add" /></template>
{{ t('model.editor.customHeadersAdd') }}
</t-button>
</div>
<p v-if="field.hintKey" class="form-desc custom-headers-desc">{{ t(field.hintKey) }}</p>
<div v-if="rssAuthHeaders.length > 0" class="custom-headers-list">
<div v-for="(item, idx) in rssAuthHeaders" :key="idx" class="custom-header-row">
<t-input
v-model="item.key"
:placeholder="t('model.editor.customHeadersKeyPlaceholder')"
class="custom-header-key"
autocomplete="off"
spellcheck="false"
/>
<t-input
v-model="item.value"
:placeholder="t('model.editor.customHeadersValuePlaceholder')"
class="custom-header-value"
autocomplete="off"
spellcheck="false"
/>
<t-button
variant="text"
shape="square"
size="small"
class="custom-header-remove"
:aria-label="t('common.delete')"
@click="removeRssAuthHeader(idx)"
>
<t-icon name="close" />
</t-button>
</div>
</div>
</template>
<template v-else>
<label class="form-label" :class="{ required: !field.optional }">
{{ t(field.labelKey) }}
</label>
<t-textarea
v-if="field.multiline"
v-model="form.config.credentials[field.key]"
:placeholder="field.placeholder || t('credential.inputPlaceholder')"
:autosize="{ minRows: 2, maxRows: 6 }"
autocomplete="off"
spellcheck="false"
/>
<t-input
v-else
v-model="form.config.credentials[field.key]"
:placeholder="field.placeholder || t('credential.inputPlaceholder')"
:type="field.secret ? 'password' : 'text'"
autocomplete="off"
spellcheck="false"
>
<template v-if="field.secret" #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
<p v-if="field.hintKey" class="form-desc">{{ t(field.hintKey) }}</p>
</template>
</div>
<SchemaForm
v-model="form.config.credentials"
:schema="credentialSchema"
:errors="credentialErrors"
/>
<div v-if="isEdit && replaceCredentialsMode" class="credential-edit-actions">
<t-button size="small" variant="text" @click="cancelReplaceCredentials">
{{ t('common.cancel') }}
@ -1869,8 +1580,8 @@ const drawerConfirmText = computed(() => {
{{ t('datasource.retryLoadResources') }}
</button>
<a
v-if="currentDef?.permissionDocUrl"
:href="currentDef.permissionDocUrl"
v-if="currentDef?.permission_doc_url"
:href="currentDef.permission_doc_url"
target="_blank"
rel="noopener"
class="doc-link"
@ -2083,11 +1794,6 @@ const drawerConfirmText = computed(() => {
color: inherit;
}
.ds-type-card.disabled {
opacity: 0.5;
cursor: not-allowed;
}
.ds-type-header {
display: flex;
align-items: center;
@ -2100,14 +1806,6 @@ const drawerConfirmText = computed(() => {
font-weight: 600;
}
.ds-type-soon {
font-size: var(--app-text-2xs);
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-component);
padding: 1px 6px;
border-radius: 3px;
}
.ds-type-desc {
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
@ -2747,55 +2445,6 @@ const drawerConfirmText = computed(() => {
gap: 16px;
}
.custom-headers-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
}
.custom-headers-desc {
margin: 0 0 10px 0;
font-size: var(--app-text-sm);
line-height: 1.5;
color: var(--td-text-color-placeholder);
}
.custom-headers-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.custom-header-row {
display: flex;
align-items: center;
gap: 8px;
.custom-header-key {
flex: 0 0 38%;
}
.custom-header-value {
flex: 1;
}
.custom-header-remove {
flex-shrink: 0;
width: 32px;
height: 32px;
padding: 0;
color: var(--td-text-color-placeholder);
border-radius: var(--app-radius-sm);
transition: all 0.18s ease;
&:hover {
background: var(--td-error-color-light);
color: var(--td-error-color);
}
}
}
.ds-empty-retry {
padding: 0;
border: none;

View File

@ -0,0 +1,266 @@
<template>
<div class="plugin-center">
<div class="section-header">
<h2>{{ t('pluginCenter.title') }}</h2>
<p class="section-description">{{ t('pluginCenter.description') }}</p>
</div>
<div class="plugin-center__toolbar">
<t-input v-model="query" class="plugin-center__search" clearable :placeholder="t('pluginCenter.searchPlaceholder')">
<template #prefix-icon><t-icon name="search" /></template>
</t-input>
<div class="option-chips">
<button type="button" class="option-chip" :class="{ 'option-chip--active': point === '' }" @click="point = ''">
{{ t('pluginCenter.allPoints') }}
</button>
<button
v-for="p in EXTENSION_POINTS"
:key="p"
type="button"
class="option-chip"
:class="{ 'option-chip--active': point === p }"
@click="point = p"
>
{{ t(`pluginCenter.points.${p}`) }}
</button>
</div>
</div>
<div v-if="loading" class="plugin-center__state"><t-loading size="small" /></div>
<div v-else-if="visible.length === 0" class="plugin-center__state">
<t-empty :description="t('pluginCenter.empty')" />
</div>
<div v-else class="plugin-list">
<div v-for="p in visible" :key="p.manifest.id" class="plugin-card" :class="{ 'plugin-card--off': !p.enabled }">
<div class="plugin-card__badge">{{ initial(p) }}</div>
<div class="plugin-card__body">
<div class="plugin-card__title">
<span class="plugin-card__name">{{ nameOf(p) }}</span>
<t-tag v-if="p.manifest.builtin" size="small" variant="light">{{ t('pluginCenter.builtin') }}</t-tag>
<t-tag v-if="p.manifest.required" size="small" variant="light" theme="primary">
{{ t('pluginCenter.required') }}
</t-tag>
</div>
<div class="plugin-card__meta">{{ p.manifest.id }} · v{{ p.manifest.version }}</div>
<div v-if="descriptionOf(p)" class="plugin-card__desc">{{ descriptionOf(p) }}</div>
<div class="plugin-card__contribs">
<span v-for="s in contributionSummary(p.manifest)" :key="s.point" class="plugin-card__contrib">
{{ t(`pluginCenter.points.${s.point}`) }} × {{ s.count }}
</span>
</div>
</div>
<t-tooltip :content="switchTooltip(p)" :disabled="!switchTooltip(p)">
<t-switch
:model-value="p.enabled"
:disabled="!canManage || p.manifest.required || pending.has(p.manifest.id)"
:loading="pending.has(p.manifest.id)"
@update:model-value="(v: boolean) => toggle(p, v)"
/>
</t-tooltip>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { listPlugins, setPluginEnabled, type ExtensionPoint, type TenantPlugin } from '@/api/plugin'
import { useAuthStore } from '@/stores/auth'
import { localizedText } from '@/utils/localizedText'
import { EXTENSION_POINTS, contributionSummary, filterPlugins } from './pluginCenterState'
// Lists the plugins this deployment knows — builtins included — and lets an
// admin turn them off for the workspace. A disabled plugin's integrations drop
// out of the type lists; existing instances keep working.
const { t, locale } = useI18n()
const authStore = useAuthStore()
const plugins = ref<TenantPlugin[]>([])
const loading = ref(false)
const query = ref('')
const point = ref<ExtensionPoint | ''>('')
const pending = ref(new Set<string>())
const canManage = computed(() => authStore.canAccessAllTenants || authStore.hasRole('admin'))
const visible = computed(() =>
filterPlugins(plugins.value, { query: query.value, point: point.value, locale: locale.value }),
)
const nameOf = (p: TenantPlugin) => localizedText(p.manifest.name, locale.value)
const descriptionOf = (p: TenantPlugin) => localizedText(p.manifest.description, locale.value)
const initial = (p: TenantPlugin) => (nameOf(p).trim().charAt(0) || '?').toUpperCase()
function switchTooltip(p: TenantPlugin): string {
if (p.manifest.required) return t('pluginCenter.requiredHint')
if (!canManage.value) return t('pluginCenter.adminOnly')
return ''
}
async function load() {
loading.value = true
try {
const res = await listPlugins()
plugins.value = res.data || []
} catch (e: any) {
MessagePlugin.error(e?.message || t('pluginCenter.loadFailed'))
} finally {
loading.value = false
}
}
async function toggle(p: TenantPlugin, enabled: boolean) {
const id = p.manifest.id
pending.value = new Set([...pending.value, id])
try {
const res = await setPluginEnabled(id, enabled)
const updated = res.data
plugins.value = plugins.value.map((x) => (x.manifest.id === id ? { ...x, ...updated } : x))
MessagePlugin.success(enabled ? t('pluginCenter.enabledToast') : t('pluginCenter.disabledToast'))
} catch (e: any) {
MessagePlugin.error(e?.message || t('pluginCenter.saveFailed'))
} finally {
const next = new Set(pending.value)
next.delete(id)
pending.value = next
}
}
onMounted(load)
</script>
<style lang="less" scoped>
@import (reference) '@/components/css/provider-card.less';
@import (reference) '@/components/css/settings-section.less';
.plugin-center {
width: 100%;
}
.section-header {
.settings-section-header();
}
.plugin-center__toolbar {
display: flex;
flex-direction: column;
gap: 12px;
margin-bottom: 16px;
}
.plugin-center__search {
max-width: 360px;
}
// Segmented point filter, same look as the IM channel mode switch.
.option-chips {
display: inline-flex;
flex-wrap: wrap;
align-self: flex-start;
gap: 4px;
padding: 3px;
border-radius: var(--app-radius-md);
background: var(--td-bg-color-secondarycontainer);
}
.option-chip {
border: none;
background: transparent;
color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-sm);
line-height: 1.3;
padding: 5px 10px;
border-radius: var(--app-radius-sm);
cursor: pointer;
transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;
white-space: nowrap;
&:hover {
color: var(--td-text-color-primary);
}
&--active {
background: var(--td-bg-color-container);
color: var(--td-brand-color);
font-weight: 500;
box-shadow: var(--td-shadow-1);
}
}
.plugin-center__state {
display: flex;
justify-content: center;
padding: 32px 0;
}
.plugin-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 12px;
}
.plugin-card {
.provider-card();
align-items: flex-start;
&--off {
.plugin-card__badge,
.plugin-card__body {
opacity: 0.55;
}
}
}
.plugin-card__badge {
.provider-card-badge();
.provider-card-badge-color(#0052d9);
}
.plugin-card__body {
.provider-card-body();
gap: 4px;
}
.plugin-card__title {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.plugin-card__name {
.provider-card-title();
}
.plugin-card__meta {
font-family: var(--app-font-family-mono);
font-size: var(--app-text-xs);
color: var(--td-text-color-placeholder);
}
.plugin-card__desc {
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
line-height: 1.5;
}
.plugin-card__contribs {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 4px;
}
.plugin-card__contrib {
font-size: var(--app-text-xs);
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border-radius: var(--app-radius-xs);
padding: 1px 6px;
}
</style>

View File

@ -9,37 +9,8 @@
'has-submenu': item.children && item.children.length > 0,
'expanded': expandedMenus.includes(item.key)
}]" @click="handleNavClick(item)">
<!-- 网络搜索使用自定义 SVG 图标 -->
<svg v-if="item.key === 'websearch'" width="17" height="17" viewBox="0 0 18 18" fill="none"
xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="currentColor" stroke-width="1.2"
stroke-linecap="round" />
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="currentColor" stroke-width="1.2"
stroke-linecap="round" />
</svg>
<!-- WeKnora Cloud 使用自定义 W 图标 -->
<svg v-else-if="item.key === 'weknoracloud'" width="17" height="17" viewBox="0 0 18 18"
fill="none" xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<rect x="1.5" y="1.5" width="15" height="15" rx="3.5" stroke="currentColor" stroke-width="1.2"
fill="none" />
<path d="M4.5 5.5L6.5 12.5L9 7.5L11.5 12.5L13.5 5.5" stroke="currentColor" stroke-width="1.3"
stroke-linecap="round" stroke-linejoin="round" fill="none" />
</svg>
<!-- 沙箱:隔离运行窗口,避免和 Ollama / 系统设置共用 server -->
<svg v-else-if="item.key === 'sandbox'" width="17" height="17" viewBox="0 0 18 18" fill="none"
xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<rect x="2.5" y="3" width="13" height="12" rx="2" stroke="currentColor" stroke-width="1.2"
fill="none" />
<path d="M2.5 6.5h13" stroke="currentColor" stroke-width="1.2" />
<path d="M5.5 10h4M5.5 12.5h2.5" stroke="currentColor" stroke-width="1.2"
stroke-linecap="round" />
</svg>
<span v-else-if="item.emoji" class="nav-icon nav-icon-emoji">{{ item.emoji }}</span>
<t-icon v-else :name="item.icon" class="nav-icon" />
<span class="nav-label">{{ item.label }}</span>
<SettingsNavIcon :icon="item.icon" />
<span class="nav-label">{{ item.label() }}</span>
<t-icon v-if="item.children && item.children.length > 0"
:name="expandedMenus.includes(item.key) ? 'chevron-down' : 'chevron-right'"
class="expand-icon" />
@ -59,8 +30,8 @@
</template>
</template>
<div class="content-wrapper" :class="{
'content-wrapper--wide': currentSection === 'members',
'content-wrapper--full': SYSTEM_ADMIN_SECTIONS.has(currentSection) || isIntegrationSection(currentSection),
'content-wrapper--wide': currentEntry?.layout === 'wide',
'content-wrapper--full': currentEntry?.layout === 'full',
}">
<!-- 角色不允许访问当前 section(deep-link 进来 / 跨空间切换后角色降级)—— 优先于具体 section 渲染。
正常导航走 navItems filter 不会到这里,但 watch(navItems) 的 fallback 会在角色降级
@ -72,120 +43,10 @@
<div class="role-denied-title">{{ $t('settings.roleDenied.title') }}</div>
<div class="role-denied-desc">{{ $t('settings.roleDenied.desc') }}</div>
</div>
<template v-else>
<!-- 常规设置 -->
<div v-if="currentSection === 'general'" class="section">
<GeneralSettings />
</div>
<!-- Ollama 设置 -->
<div v-if="currentSection === 'ollama'" class="section">
<OllamaSettings />
</div>
<!-- WeKnora Cloud -->
<div v-if="currentSection === 'weknoracloud'" class="section">
<WeKnoraCloudSettings />
</div>
<!-- 模型配置 -->
<div v-if="currentSection === 'models'" class="section">
<ModelSettings />
</div>
<!-- 网络搜索配置 -->
<div v-if="currentSection === 'websearch'" class="section">
<WebSearchSettings />
</div>
<!-- 消息管理 -->
<div v-if="currentSection === 'chathistory'" class="section">
<ChatHistorySettings />
</div>
<!-- 长期记忆(空间级开关) -->
<div v-if="currentSection === 'memory'" class="section">
<MemoryWorkspaceSettings />
</div>
<!-- 我的记忆(个人记忆管理) -->
<div v-if="currentSection === 'mymemory'" class="section">
<MemorySettings />
</div>
<!-- 沙箱密钥(成员自己的技能 / 沙箱密钥) -->
<div v-if="currentSection === 'envvars'" class="section">
<EnvVarSettings />
</div>
<!-- 向量数据库引擎 -->
<div v-if="currentSection === 'vectorstore'" class="section">
<VectorStoreSettings />
</div>
<!-- 解析引擎 -->
<div v-if="currentSection === 'parser'" class="section">
<ParserEngineSettings />
</div>
<!-- 存储引擎 -->
<div v-if="currentSection === 'storage'" class="section">
<StorageBackendSettings />
</div>
<!-- 沙箱 -->
<div v-if="currentSection === 'sandbox'" class="section">
<SandboxSettings />
</div>
<!-- 系统信息 -->
<div v-if="currentSection === 'system'" class="section">
<SystemInfo />
</div>
<!-- 系统管理员可见的全局运行时设置 -->
<div v-if="currentSection === 'system-global'" class="section">
<SystemSettings />
</div>
<div v-if="currentSection === 'model-catalog'" class="section">
<ModelCatalog />
</div>
<!-- 系统管理员可见的任务队列运行状态 -->
<div v-if="currentSection === 'runtime-queues'" class="section">
<RuntimeQueues />
</div>
<div v-if="currentSection === 'platform-api-keys'" class="section">
<PlatformAPIKeys />
</div>
<div v-if="currentSection === 'system-audit-log'" class="section">
<SystemAuditLog />
</div>
<!-- 用户信息(账户基础信息:ID / 用户名 / 邮箱 / 注册时间)。
用户的基本信息不该跟 owner 权限绑定。 -->
<div v-if="currentSection === 'userprofile'" class="section">
<UserProfile />
</div>
<!-- 空间信息 -->
<div v-if="currentSection === 'tenant'" class="section">
<TenantInfo />
</div>
<!-- 成员管理 (#1303 PR 3) -->
<div v-if="currentSection === 'members'" class="section">
<TenantMembers />
</div>
<!-- 发布集成 -->
<div v-if="isIntegrationSection(currentSection)" class="section">
<IntegrationSettingsSection :tab="integrationTabFromSection(currentSection)" />
</div>
</template>
<!-- Sections come from the settings registry: builtins plus plugin pages. -->
<div v-else-if="currentEntry" class="section">
<component :is="currentEntry.component" v-bind="currentEntry.props?.() ?? {}" />
</div>
</div>
</SettingsModalShell>
</template>
@ -201,46 +62,20 @@ import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { useModalShell } from '@/composables/useModalShell'
import SettingsModalShell from '@/components/SettingsModalShell.vue'
import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue'
import UserProfile from './UserProfile.vue'
import GeneralSettings from './GeneralSettings.vue'
import ModelSettings from './ModelSettings.vue'
import ModelCatalog from '../system/ModelCatalog.vue'
import OllamaSettings from './OllamaSettings.vue'
import WebSearchSettings from './WebSearchSettings.vue'
import ChatHistorySettings from './ChatHistorySettings.vue'
import MemorySettings from './MemorySettings.vue'
import EnvVarSettings from './EnvVarSettings.vue'
import MemoryWorkspaceSettings from './MemoryWorkspaceSettings.vue'
import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
import StorageBackendSettings from './StorageBackendSettings.vue'
import SandboxSettings from './SandboxSettings.vue'
import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue'
import TenantMembers from './TenantMembers.vue'
import SystemSettings from '@/views/system/SystemSettings.vue'
import RuntimeQueues from '@/views/system/RuntimeQueues.vue'
import PlatformAPIKeys from '@/views/system/PlatformAPIKeys.vue'
import SystemAuditLog from '@/views/system/SystemAuditLog.vue'
import IntegrationSettingsSection from '@/views/integrations/IntegrationSettingsSection.vue'
import SettingsNavIcon from '@/extensions/SettingsNavIcon.vue'
import { registerBuiltinSettings } from '@/extensions/builtin/settings'
import {
INTEGRATION_PREVIEW_ITEMS,
INTEGRATION_TAB_CAPABILITY,
INTEGRATION_TAB_MIN_ROLE,
} from '@/config/integrations'
import {
SETTINGS_SECTION_MIN_ROLE,
SYSTEM_ADMIN_SETTINGS_SECTIONS,
} from '@/config/settingsAccess'
import { SETTINGS_SECTION_CAPABILITY, skillSettingsSupported } from '@/config/deploymentCapabilities'
groupSections,
sectionPermitted,
sectionSupported,
settingsGroups,
settingsSections,
type SettingsAccessContext,
type SettingsSection,
} from '@/extensions/settingsSections'
import { isToolboxSection, toolboxLocation } from '@/config/toolbox'
import { hostSkillsOnly } from '@/utils/skillTarget'
import {
buildSettingsRouteQuery,
integrationSectionKey,
integrationTabFromSection,
isIntegrationSection,
normalizeSettingsSection as normalizeSettingsSectionFromQuery,
settingsQueryUnchanged,
} from '@/config/settingsRoute'
@ -250,51 +85,27 @@ const router = useRouter()
const uiStore = useUIStore()
const authStore = useAuthStore()
const deploymentCapabilities = useDeploymentCapabilitiesStore()
const { t, te } = useI18n()
const hostSkills = computed(() => hostSkillsOnly(
deploymentCapabilities.isSupported('settings.sandbox.remote'),
deploymentCapabilities.isSupported('settings.sandbox.host'),
))
function envNavLabel(): string {
const hostKey = 'envVarSettings.host.title'
if (hostSkills.value && te(hostKey)) return t(hostKey)
return t('envVarSettings.title')
}
const { t } = useI18n()
// Sections are registered, not listed here: builtins first, plugins later.
registerBuiltinSettings()
const currentSection = ref<string>('general')
const currentSubSection = ref<string>('')
const expandedMenus = ref<string[]>([])
type NavItem = {
key: string
icon: string
label: string
emoji?: string
children?: Array<{ key: string; label: string }>
}
type NavGroup = {
key: string
label: string
items: NavItem[]
}
// 设置二级导航的最低可见角色来自 settingsAccess.ts,和
// internal/router/router.go 的守卫矩阵对齐。
// 以「页面里至少有 1 个有意义的写操作所要求的最低角色」为基准,把基础设
// 施配置(models 写、ollama 下载、websearch 写、parser/storage/vector/mcp
// CRUD、sandbox 连接、skills 安装、chat-history 配置)统一收到 admin;只读类(general / system info /
// tenant-info / members 名册)保留 viewer 可见;最高敏感的 reset api
// key 是 owner-only。改这张表前请在 router.go 里复核对应路由组。
//
// 特别说明:
// - chathistory 页面唯一的「启用消息索引」开关 PUT /tenants/kv/chat-history-config
// 后端走 g.Admin()。给 viewer/contributor 看到入口、点开开关、保存时
// 403,体验很差,所以入口本身归 admin。
// - models 列表 viewer 可读,页面内的「+ 添加模型 / 编辑 / 删除」按钮在
// ModelSettings.vue 里另用 hasRole('admin') 自己 gate,所以入口保留
// viewer 是合理的(contributor 也能浏览模型列表)。
const SYSTEM_ADMIN_SECTIONS = SYSTEM_ADMIN_SETTINGS_SECTIONS
// Who may see a section comes from each section's access rules (for builtins,
// settingsAccess.ts and deploymentCapabilities.ts, aligned with the guards in
// internal/router). They only decide whether the UI offers the entry; the
// server checks every route itself.
const accessContext = computed<SettingsAccessContext>(() => ({
isSystemAdmin: authStore.isSystemAdmin,
canAccessAllTenants: authStore.canAccessAllTenants,
hasRole: (role) => authStore.hasRole(role),
isSupported: (capability) => deploymentCapabilities.isSupported(capability),
capabilities: deploymentCapabilities.capabilities,
}))
const normalizeSettingsSection = (section: string) => {
return normalizeSettingsSectionFromQuery(section, route.query.tab as string | undefined)
@ -311,129 +122,28 @@ const syncSettingsRoute = (sectionKey: string) => {
}
const isSectionSupported = (key: string): boolean => {
if (isIntegrationSection(key)) {
return deploymentCapabilities.isSupported(
INTEGRATION_TAB_CAPABILITY[integrationTabFromSection(key)],
)
}
if (key === 'skills' || key === 'envvars') {
return skillSettingsSupported(deploymentCapabilities.capabilities)
}
return deploymentCapabilities.isSupported(SETTINGS_SECTION_CAPABILITY[key])
const section = settingsSections.get(key)
return !!section && sectionSupported(section, accessContext.value)
}
const canSeeSection = (key: string): boolean => {
if (isIntegrationSection(key)) {
const min = INTEGRATION_TAB_MIN_ROLE[integrationTabFromSection(key)]
if (!min) return true
if (authStore.canAccessAllTenants) return true
return authStore.hasRole(min)
}
if (SYSTEM_ADMIN_SECTIONS.has(key)) {
return authStore.isSystemAdmin
}
const min = SETTINGS_SECTION_MIN_ROLE[key] ?? 'viewer'
// canAccessAllTenants(superuser)和路由层一样必须 bypass,否则 cross-tenant
// 管理员看不到自己有权操作的入口(参考 TenantMembers.vue 的 canManage)。
if (authStore.canAccessAllTenants) return true
return authStore.hasRole(min)
const section = settingsSections.get(key)
// An unknown key (stale deep link) falls through to the fallback watchers.
return !section || sectionPermitted(section, accessContext.value)
}
const navItems = computed(() => {
// 一律走 SETTINGS_SECTION_MIN_ROLE 表,避免 ad-hoc isAdmin/isOwner 散落在多处。
// 服务端在每条路由上仍以 g.Viewer/Admin/Owner 为准,这里只决定 UI 是
// 否露入口;改动入口规则请同步更新 settingsAccess.ts 和对应后端路由。
const integrationItems: NavItem[] = INTEGRATION_PREVIEW_ITEMS.map((item) => ({
key: integrationSectionKey(item.key),
icon: item.icon.type === 'icon' ? item.icon.name : 'integration',
emoji: item.icon.type === 'emoji' ? item.icon.value : undefined,
label: t(`integrations.tabs.${item.key}`),
}))
const all: NavItem[] = [
{ key: 'general', icon: 'setting', label: t('general.title') },
{ key: 'ollama', icon: 'server', label: 'Ollama' },
{ key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' },
{ key: 'models', icon: 'control-platform', label: t('settings.modelManagement') },
{ key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
{ key: 'chathistory', icon: 'chat', label: t('chatHistorySettings.title') },
{ key: 'memory', icon: 'bulletpoint', label: t('memoryWorkspaceSettings.title') },
{ key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') },
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ key: 'storage', icon: 'cloud', label: t('settings.storageEngine') },
{ key: 'sandbox', icon: 'code', label: t('settings.sandbox.title') },
{ key: 'system', icon: 'info-circle', label: t('settings.versionInfo') },
{ key: 'system-global', icon: 'server', label: t('settings.system') },
{ key: 'model-catalog', icon: 'control-platform', label: t('modelCatalog.title') },
{ key: 'runtime-queues', icon: 'queue', label: t('settings.taskQueue') },
{ key: 'platform-api-keys', icon: 'secured', label: t('platformApiKeys.title') },
{ key: 'system-audit-log', icon: 'history', label: t('system.globalSettings.audit.tabLabel') },
{ key: 'userprofile', icon: 'user', label: t('userProfile.title') },
{ key: 'mymemory', icon: 'bookmark', label: t('memorySettings.title') },
{ key: 'envvars', icon: 'key', label: envNavLabel() },
{ key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
{ key: 'members', icon: 'usergroup', label: t('tenantMember.title') },
...integrationItems,
]
const currentEntry = computed<SettingsSection | undefined>(() => settingsSections.get(currentSection.value))
const navItems = computed<SettingsSection[]>(() => {
// currentTenantRole 为空表示「membership 还没加载」—— 比起渲染整套
// viewer 入口然后角色一返回又消失,先卡住不渲染更稳,跟原先 members
// 入口的策略一致。
if (!authStore.currentTenantRole && !authStore.canAccessAllTenants) {
return [] as NavItem[]
}
return all.filter((it) => canSeeSection(it.key) && isSectionSupported(it.key))
// viewer 入口然后角色一返回又消失,先卡住不渲染更稳。
if (!authStore.currentTenantRole && !authStore.canAccessAllTenants) return []
return settingsSections.items.filter((section) =>
sectionPermitted(section, accessContext.value) && sectionSupported(section, accessContext.value),
)
})
const navGroups = computed<NavGroup[]>(() => {
const itemMap = new Map(navItems.value.map((item) => [item.key, item]))
const pickItems = (keys: string[]) => keys.map((key) => itemMap.get(key)).filter(Boolean) as NavItem[]
// 分组:账户 → 空间 → 模型 → 发布集成 → 数据与扩展 → 系统管理 → 平台
// 关键调整:把个人偏好(general)和用户信息收进「账户」;
// 把空间内功能开关(chathistory)从「平台」挪到「空间」;
// 把检索引擎和外部集成合并为「数据与扩展」,避免两个 2~3 项的窄分组。
return [
{
key: 'account',
label: t('settings.navGroups.account'),
items: pickItems(['general', 'userprofile', 'mymemory', 'envvars']),
},
{
key: 'workspace',
label: t('settings.navGroups.workspace'),
items: pickItems(['tenant', 'members', 'chathistory', 'memory']),
},
{
key: 'models_runtime',
label: t('settings.navGroups.modelsRuntime'),
items: pickItems(['models', 'ollama', 'weknoracloud']),
},
{
key: 'integrations',
label: t('integrations.title'),
items: pickItems(INTEGRATION_PREVIEW_ITEMS.map((item) => integrationSectionKey(item.key))),
},
{
key: 'data_extensions',
label: t('settings.navGroups.dataExtensions'),
items: pickItems([
'vectorstore',
'parser',
'storage',
'sandbox',
'websearch',
]),
},
{
key: 'system_administration',
label: t('settings.navGroups.systemAdministration'),
items: pickItems(['system-global', 'model-catalog', 'runtime-queues', 'platform-api-keys', 'system-audit-log']),
},
{
key: 'platform',
label: t('settings.navGroups.platform'),
items: pickItems(['system']),
},
].filter((group) => group.items.length > 0)
})
const navGroups = computed(() => groupSections(settingsGroups.items, navItems.value))
// 导航项点击处理
const handleNavClick = (item: any) => {

View File

@ -202,96 +202,42 @@
</div>
</section>
<!-- Section 2 — 连接配置(base url / api key / engine id),仅当任意字段需要时渲染 -->
<section
v-if="selectedProviderType?.requires_api_key || selectedProviderType?.supports_optional_api_key || selectedProviderType?.requires_engine_id || selectedProviderType?.requires_base_url || selectedProviderType?.config_fields?.length"
class="setting-drawer__section"
>
<!-- Section 2 — 连接配置:按类型的 config_schema 渲染 credentials 分组 -->
<section v-if="hasGroup('credentials')" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('webSearchSettings.credentialsSection', '连接配置') }}</h4>
<div v-if="selectedProviderType?.requires_base_url" class="form-item">
<label class="form-label required">{{ t('webSearchSettings.baseUrlLabel') }}</label>
<t-input
v-model="providerForm.parameters.base_url"
:placeholder="t('webSearchSettings.baseUrlPlaceholder')"
/>
</div>
<!--
Edit 模式下凭证由 CredentialResource 管理(独立的 /credentials
子资源调用),不与本表单 submit 耦合;Create 模式下用 plain
password input + lock prefix-icon,与 ModelEditorDialog 一致。
子资源调用),不与本表单 submit 耦合;Create 模式下 SchemaForm
直接渲染密码输入框。
-->
<div v-if="selectedProviderType?.requires_api_key || selectedProviderType?.supports_optional_api_key" class="form-item">
<label class="form-label" :class="{ required: selectedProviderType?.requires_api_key }">
{{ selectedProviderType?.supports_optional_api_key && !selectedProviderType?.requires_api_key
? t('webSearchSettings.apiKeyOptionalLabel', 'API Key(可选)')
: t('webSearchSettings.apiKeyLabel') }}
</label>
<CredentialResource
v-if="editingProvider?.id"
:api="credentialApi"
:fields="credentialFields"
:meta="credentialMeta"
/>
<t-input
v-else
v-model="providerForm.parameters.api_key"
type="password"
:placeholder="apiKeyPlaceholder"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<div v-if="selectedProviderType?.requires_engine_id" class="form-item">
<label class="form-label required">{{ t('webSearchSettings.engineIdLabel') }}</label>
<t-input
v-model="providerForm.parameters.engine_id"
:placeholder="t('webSearchSettings.engineIdLabel')"
/>
</div>
<div
v-for="field in selectedProviderType?.config_fields || []"
:key="field.key"
class="form-item"
<SchemaForm
v-model="providerForm.parameters"
:schema="parametersSchema"
group="credentials"
:secret-mode="editingProvider?.id ? 'slot' : 'input'"
:errors="formErrors"
>
<label class="form-label" :class="{ required: field.required }">
{{ configFieldText(field.label_key, field.label) }}
</label>
<t-select
v-if="field.type === 'select'"
v-model="providerForm.parameters.extra_config[field.key]"
>
<t-option
v-for="option in field.options || []"
:key="option.value"
:value="option.value"
:label="configFieldText(option.label_key, option.label)"
<template #secret>
<CredentialResource
:api="credentialApi"
:fields="credentialFields"
:meta="credentialMeta"
/>
</t-select>
<p v-if="field.description" class="form-desc">
{{ configFieldText(field.description_key, field.description) }}
</p>
</div>
</template>
</SchemaForm>
</section>
<!-- Section 3 — 选项(代理 / 默认) -->
<section
v-if="selectedProviderType?.supports_proxy || selectedProviderType"
class="setting-drawer__section"
>
<section v-if="selectedProviderType" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('webSearchSettings.optionsSection', '选项') }}</h4>
<div v-if="selectedProviderType?.supports_proxy" class="form-item">
<label class="form-label">{{ t('webSearchSettings.proxyUrlLabel') }}</label>
<t-input
v-model="providerForm.parameters.proxy_url"
:placeholder="t('webSearchSettings.proxyUrlPlaceholder')"
/>
<p class="form-desc">{{ t('webSearchSettings.proxyUrlHelp') }}</p>
</div>
<SchemaForm
v-model="providerForm.parameters"
:schema="parametersSchema"
group="options"
:errors="formErrors"
/>
<div class="form-item">
<label class="form-label">{{ t('webSearchSettings.setAsDefault') }}</label>
@ -324,6 +270,17 @@ import {
type WebSearchCredentialField,
} from '@/api/web-search-provider'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import SchemaForm from '@/components/schema-form/SchemaForm.vue'
import {
inGroup,
isPlainObject,
orderedFields,
applyDefaults,
validateConfig,
type ConfigSchema,
type ConfigValue,
type FieldError,
} from '@/components/schema-form/schema'
import CredentialResource, {
type CredentialFieldDef,
type CredentialResourceApi,
@ -353,26 +310,25 @@ const formRef = ref<any>()
// is initialized so the watch's source function doesn't trip on TDZ).
const lastTestOk = ref<boolean | null>(null)
// parameters follows the selected type's config_schema: api_key, engine_id,
// base_url, proxy_url and extra_config, whichever the type declares.
const providerForm = ref<{
name: string
provider: string
description: string
parameters: {
api_key?: string
engine_id?: string
base_url?: string
proxy_url?: string
extra_config: Record<string, string>
}
parameters: ConfigValue
is_default: boolean
}>({
name: '',
provider: 'duckduckgo',
description: '',
parameters: { extra_config: {} },
parameters: {},
is_default: false,
})
// Field errors from the last save attempt, shown under each field.
const formErrors = ref<FieldError[]>([])
// Invalidate the cached test result whenever the user edits a connection
// field. Set up after providerForm is declared so the watch's source
// function — which dereferences providerForm.value on first run — doesn't
@ -381,22 +337,29 @@ const providerForm = ref<{
watch(
() => [
providerForm.value.provider,
providerForm.value.parameters?.api_key,
providerForm.value.parameters?.engine_id,
providerForm.value.parameters?.base_url,
JSON.stringify(providerForm.value.parameters?.extra_config || {}),
JSON.stringify({ ...providerForm.value.parameters, proxy_url: undefined }),
],
() => { lastTestOk.value = null },
)
// Any edit clears the errors of the last save attempt.
watch(() => JSON.stringify(providerForm.value.parameters), () => { formErrors.value = [] })
// ===== Computed =====
const selectedProviderType = computed(() => {
return providerTypes.value.find(pt => pt.id === providerForm.value.provider)
})
// Create-mode placeholder (edit mode replaces the input with
// <CredentialResource>, which has its own placeholder).
const apiKeyPlaceholder = computed(() => t('webSearchSettings.apiKeyPlaceholder'))
const EMPTY_SCHEMA: ConfigSchema = { type: 'object', properties: {} }
const parametersSchema = computed<ConfigSchema>(() => selectedProviderType.value?.config_schema ?? EMPTY_SCHEMA)
const hasGroup = (group: string) => orderedFields(parametersSchema.value).some(f => inGroup(f.schema, group))
// Validation for the parameters. In edit mode secrets are committed through
// <CredentialResource>, and the stored key stands in for an empty input.
const parameterErrors = () =>
validateConfig(parametersSchema.value, providerForm.value.parameters, { skipSecrets: !!editingProvider.value })
const credentialFields = computed<CredentialFieldDef<WebSearchCredentialField>[]>(() => [
{ key: 'api_key', label: t('webSearchSettings.apiKeyLabel') as string },
@ -449,14 +412,9 @@ const drawerLogoStyle = computed((): Record<string, string> => {
// can fire with no fresh api_key because the backend will fall back to
// the stored credential. Free providers don't show the button at all.
const canTestConnection = computed(() => {
const pt = selectedProviderType.value
if (!pt) return false
if (!selectedProviderType.value) return false
if (editingProvider.value) return true
if (pt.requires_api_key && !providerForm.value.parameters.api_key) return false
if (pt.requires_engine_id && !providerForm.value.parameters.engine_id) return false
if (pt.requires_base_url && !providerForm.value.parameters.base_url) return false
if (pt.config_fields?.some(field => field.required && !providerForm.value.parameters.extra_config?.[field.key])) return false
return true
return parameterErrors().length === 0
})
// 卡片首字母徽章。复用 providerType 信息表,让多字节缩写也走同一处。
@ -486,25 +444,17 @@ const providerTypeLabel = (providerId: string) => {
return providerTypes.value.find(p => p.id === providerId)?.name || providerId
}
const configFieldText = (key: string | undefined, fallback: string) => {
return key ? t(key, fallback) : fallback
}
const providerConfigDefaults = (providerId: string) => {
const fields = providerTypes.value.find(p => p.id === providerId)?.config_fields || []
return Object.fromEntries(
fields
.filter(field => field.default !== undefined)
.map(field => [field.key, field.default as string]),
)
// Fills a type's schema defaults (e.g. Zhipu's search engine) into parameters.
const parametersWithDefaults = (providerId: string, parameters: ConfigValue = {}) => {
const schema = providerTypes.value.find(p => p.id === providerId)?.config_schema
return schema ? applyDefaults(schema, parameters) : { ...parameters }
}
// ===== Methods =====
const onProviderTypeChange = () => {
providerForm.value.parameters = {
extra_config: providerConfigDefaults(providerForm.value.provider),
}
providerForm.value.parameters = parametersWithDefaults(providerForm.value.provider)
lastTestOk.value = null
formErrors.value = []
}
// 走 chatResources 的共享快照并强刷:增删改之后对话输入栏读到的就是最新列表,
@ -532,12 +482,11 @@ const openAddDialog = () => {
name: '',
provider: providerTypes.value[0]?.id || 'duckduckgo',
description: '',
parameters: {
extra_config: providerConfigDefaults(providerTypes.value[0]?.id || 'duckduckgo'),
},
parameters: parametersWithDefaults(providerTypes.value[0]?.id || 'duckduckgo'),
is_default: providerEntities.value.length === 0
}
lastTestOk.value = null
formErrors.value = []
showAddProviderDialog.value = true
}
@ -547,21 +496,13 @@ const editProvider = (entity: WebSearchProviderEntity) => {
name: entity.name,
provider: entity.provider,
description: entity.description || '',
parameters: {
// Never pre-fill the api_key — even the redacted placeholder from the
// server is ignored so that "non-empty means user typed it" holds.
api_key: '',
engine_id: entity.parameters?.engine_id || '',
base_url: entity.parameters?.base_url || '',
proxy_url: entity.parameters?.proxy_url || '',
extra_config: {
...providerConfigDefaults(entity.provider),
...(entity.parameters?.extra_config || {}),
},
},
// Never pre-fill the api_key — even the redacted placeholder from the
// server is ignored so that "non-empty means user typed it" holds.
parameters: parametersWithDefaults(entity.provider, { ...(entity.parameters || {}), api_key: undefined }),
is_default: entity.is_default || false,
}
lastTestOk.value = null
formErrors.value = []
showAddProviderDialog.value = true
}
@ -572,27 +513,15 @@ const saveProvider = async () => {
MessagePlugin.warning(typeof firstError === 'string' ? firstError : 'Please check the form fields')
return
}
formErrors.value = parameterErrors()
if (formErrors.value.length > 0) return
saving.value = true
try {
// Build the parameters payload. api_key only flows in on initial
// create — edit mode commits credentials through <CredentialResource>
// (a dedicated PUT /credentials call) before this save runs.
const paramsOut: WebSearchProviderEntity['parameters'] = {
engine_id: providerForm.value.parameters.engine_id,
base_url: providerForm.value.parameters.base_url,
proxy_url: providerForm.value.parameters.proxy_url,
}
const extraConfig = Object.fromEntries(
Object.entries(providerForm.value.parameters.extra_config || {})
.filter(([, value]) => value !== ''),
)
if (Object.keys(extraConfig).length > 0) {
paramsOut.extra_config = extraConfig
}
if (!editingProvider.value && providerForm.value.parameters.api_key) {
paramsOut.api_key = providerForm.value.parameters.api_key
}
const paramsOut = buildParametersPayload(providerForm.value.parameters, !editingProvider.value)
const data: Partial<WebSearchProviderEntity> = {
name: providerForm.value.name.trim() || selectedProviderType.value?.name || providerForm.value.provider,
@ -618,6 +547,22 @@ const saveProvider = async () => {
}
}
// Drops empty values (an empty extra_config entry means "unset") and, in edit
// mode, the api_key, which is committed through <CredentialResource>.
const buildParametersPayload = (parameters: ConfigValue, includeSecrets: boolean) => {
const out: Record<string, unknown> = {}
for (const [key, value] of Object.entries(parameters)) {
if (key === 'api_key' && !includeSecrets) continue
if (isPlainObject(value)) {
const nested = Object.fromEntries(Object.entries(value).filter(([, v]) => v !== '' && v !== undefined))
if (Object.keys(nested).length > 0) out[key] = nested
continue
}
if (value !== undefined && value !== '') out[key] = value
}
return out as WebSearchProviderEntity['parameters']
}
const deleteProvider = (entity: WebSearchProviderEntity) => {
confirmDelete({
body: t('webSearchSettings.deleteConfirm'),

View File

@ -0,0 +1,39 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { TenantPlugin } from '../../api/plugin'
import { contributionSummary, filterPlugins } from './pluginCenterState'
const plugin = (id: string, name: string, contributes: TenantPlugin['manifest']['contributes'], zh?: string): TenantPlugin => ({
enabled: true,
manifest: {
schemaVersion: 1, id, version: '1.0.0', publisher: { id: 'weknora' }, runtime: { type: 'builtin' },
name: zh ? { default: name, 'zh-CN': zh } : { default: name },
contributes,
},
})
const feishu = plugin('weknora.feishu', 'Feishu / Lark', {
connectors: [{ id: 'feishu', name: { default: 'Feishu' } }, { id: 'lark', name: { default: 'Lark' } }],
imChannels: [{ id: 'feishu', name: { default: 'Feishu' } }],
}, '飞书 / Lark')
const bing = plugin('weknora.bing', 'Bing', { webSearch: [{ id: 'bing', name: { default: 'Bing' } }] })
const openai = plugin('weknora.openai', 'OpenAI', { modelVendors: [{ id: 'openai', name: { default: 'OpenAI' } }] })
test('contributionSummary counts per point in point order', () => {
assert.deepEqual(contributionSummary(feishu.manifest), [
{ point: 'connectors', count: 2 },
{ point: 'imChannels', count: 1 },
])
})
test('filterPlugins matches names, IDs and contributions, and filters by point', () => {
const all = [openai, feishu, bing]
const names = (list: TenantPlugin[]) => list.map((p) => p.manifest.id)
assert.deepEqual(names(filterPlugins(all, { query: '', point: '', locale: 'en-US' })),
['weknora.bing', 'weknora.feishu', 'weknora.openai'])
assert.deepEqual(names(filterPlugins(all, { query: 'lark', point: '', locale: 'en-US' })), ['weknora.feishu'])
assert.deepEqual(names(filterPlugins(all, { query: '飞书', point: '', locale: 'zh-CN' })), ['weknora.feishu'])
assert.deepEqual(names(filterPlugins(all, { query: '', point: 'webSearch', locale: 'en-US' })), ['weknora.bing'])
assert.deepEqual(names(filterPlugins(all, { query: 'bing', point: 'connectors', locale: 'en-US' })), [])
})

View File

@ -0,0 +1,47 @@
// Pure helpers behind PluginCenter.vue, kept free of Vue so they run under
// node:test.
import type { ExtensionPoint, PluginManifest, TenantPlugin } from '../../api/plugin'
import { localizedText } from '../../utils/localizedText'
/** Extension points in the order the plugin center shows them. */
export const EXTENSION_POINTS: ExtensionPoint[] = [
'modelVendors', 'connectors', 'imChannels', 'webSearch', 'tools', 'parsers',
]
/** How many contributions a plugin makes at each point, in point order. */
export function contributionSummary(m: PluginManifest): Array<{ point: ExtensionPoint; count: number }> {
return EXTENSION_POINTS
.map((point) => ({ point, count: m.contributes[point]?.length ?? 0 }))
.filter((s) => s.count > 0)
}
export interface PluginFilter {
query: string
/** Only plugins contributing to this point; empty for all. */
point: ExtensionPoint | ''
locale: string
}
/**
* Plugins matching a search and point filter, sorted by display name. The
* query matches the plugin name, ID and the names of its contributions, so
* searching "lark" finds the Feishu plugin.
*/
export function filterPlugins(list: readonly TenantPlugin[], f: PluginFilter): TenantPlugin[] {
const q = f.query.trim().toLowerCase()
const matches = (p: TenantPlugin) => {
const m = p.manifest
if (f.point && !(m.contributes[f.point]?.length)) return false
if (!q) return true
const texts = [m.id, localizedText(m.name, f.locale), m.name.default]
for (const point of EXTENSION_POINTS) {
for (const c of m.contributes[point] ?? []) {
texts.push(c.id, localizedText(c.name, f.locale))
}
}
return texts.some((t) => t.toLowerCase().includes(q))
}
return list
.filter(matches)
.sort((a, b) => localizedText(a.manifest.name, f.locale).localeCompare(localizedText(b.manifest.name, f.locale), f.locale))
}

View File

@ -1,46 +1,73 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import { computed } from 'vue'
import { INTEGRATION_PREVIEW_ITEMS } from '../../config/integrations'
import { integrationSectionKey } from '../../config/settingsRoute'
import { BUILTIN_SETTINGS_GROUPS, BUILTIN_SETTINGS_SECTIONS } from '../../extensions/builtin/settingsCatalog'
import {
groupSections,
sectionPermitted,
type SettingsAccessContext,
type SettingsSection,
} from '../../extensions/settingsSections'
// Exercise the actual sidebar grouping without mounting the settings panels.
const source = readFileSync(new URL('./Settings.vue', import.meta.url), 'utf8')
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)![1]!
const ast = ts.createSourceFile('Settings.ts', script, ts.ScriptTarget.Latest, true)
const grouping = ast.statements.find((statement) =>
ts.isVariableStatement(statement) && statement.declarationList.declarations.some(
(declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === 'navGroups',
),
)
assert.ok(grouping, 'Settings must define sidebar groups')
const compiled = ts.transpileModule(grouping.getText(ast), {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText
// The sidebar is built from the builtin catalog through the same grouping
// function Settings.vue uses.
const groups = BUILTIN_SETTINGS_GROUPS.map((g) => ({ key: g.key, order: g.order, label: () => g.label }))
const sections = BUILTIN_SETTINGS_SECTIONS.map((s) => ({ ...s, label: () => s.label }) as unknown as SettingsSection)
function integrationMenu(visibleKeys: string[]): string[] {
const groups = runInNewContext(`${compiled}\nnavGroups.value`, {
computed,
navItems: { value: visibleKeys.map((key) => ({ key })) },
t: (key: string) => key,
integrationSectionKey,
INTEGRATION_PREVIEW_ITEMS,
}) as Array<{ key: string; items: Array<{ key: string }> }>
const integrationGroup = groups.find((group) => group.key === 'integrations')
return Array.from(integrationGroup?.items ?? [], (item) => item.key)
function menu(visibleKeys: string[], group: string): string[] {
const visible = sections.filter((s) => visibleKeys.includes(s.key))
return groupSections(groups, visible).find((g) => g.key === group)?.items.map((s) => s.key) ?? []
}
const integrationKeys = INTEGRATION_PREVIEW_ITEMS.map((item) => integrationSectionKey(item.key))
test('settings sidebar includes every registered integration, including CLI, in navigation order', () => {
assert.deepEqual(integrationMenu(['general', ...integrationKeys]), integrationKeys)
assert.deepEqual(menu(['general', ...integrationKeys], 'integrations'), integrationKeys)
})
test('settings sidebar preserves visibility filtering without hiding CLI', () => {
const visible = integrationKeys.filter((key) => key !== 'integration-api' && key !== 'integration-im')
assert.deepEqual(integrationMenu(visible), visible)
assert.deepEqual(integrationMenu(['general']), [])
assert.deepEqual(menu(visible, 'integrations'), visible)
assert.deepEqual(menu(['general'], 'integrations'), [])
})
test('groups keep their order and drop when empty', () => {
const all = sections.map((s) => s.key)
assert.deepEqual(
groupSections(groups, sections.filter((s) => all.includes(s.key))).map((g) => g.key),
[
'account', 'workspace', 'models_runtime', 'integrations', 'data_extensions', 'plugins',
'system_administration', 'platform',
],
)
assert.deepEqual(groupSections(groups, sections.filter((s) => s.key === 'system')).map((g) => g.key), ['platform'])
assert.deepEqual(menu(all, 'account'), ['general', 'userprofile', 'mymemory', 'envvars'])
assert.deepEqual(menu(all, 'data_extensions'), ['vectorstore', 'parser', 'storage', 'sandbox', 'websearch'])
})
test('section keys are unique', () => {
const keys = BUILTIN_SETTINGS_SECTIONS.map((s) => s.key)
assert.equal(new Set(keys).size, keys.length)
})
test('access follows the shared role tables', () => {
const ctx = (role: 'viewer' | 'admin', isSystemAdmin = false): SettingsAccessContext => {
const rank = { viewer: 0, contributor: 1, admin: 2, owner: 3 }
return {
isSystemAdmin,
canAccessAllTenants: false,
hasRole: (min) => rank[role] >= rank[min],
isSupported: () => true,
capabilities: {},
}
}
const byKey = new Map(sections.map((s) => [s.key, s]))
assert.equal(sectionPermitted(byKey.get('models')!, ctx('viewer')), true)
assert.equal(sectionPermitted(byKey.get('websearch')!, ctx('viewer')), false)
assert.equal(sectionPermitted(byKey.get('websearch')!, ctx('admin')), true)
assert.equal(sectionPermitted(byKey.get('integration-api')!, ctx('admin')), false, 'API integration is owner-only')
assert.equal(sectionPermitted(byKey.get('runtime-queues')!, ctx('admin')), false)
assert.equal(sectionPermitted(byKey.get('runtime-queues')!, ctx('viewer', true)), true)
})

View File

@ -2,7 +2,8 @@
//
// This file is the Go mirror of `frontend/src/utils/tool-capabilities.ts`.
// They MUST be kept in sync: whenever you add a tool to the registry with
// specific KB requirements, update both maps.
// specific KB requirements, update both maps. capabilities_frontend_test.go
// fails when they differ.
//
// Why duplicate it? The frontend uses it to gray out tools and filter KBs
// in the agent editor and `@` mention menu; the backend uses it as the

View File

@ -0,0 +1,84 @@
package tools
import (
"os"
"regexp"
"slices"
"sort"
"strings"
"testing"
)
// frontendCapabilitiesFile is the frontend copy of ToolCapabilityRequirements.
// The agent editor evaluates it synchronously in many places, so it stays a
// copy; this test keeps the two from drifting.
const frontendCapabilitiesFile = "../../../frontend/src/utils/tool-capabilities.ts"
func parseFrontendRequirements(t *testing.T) map[string]ToolRequirement {
t.Helper()
data, err := os.ReadFile(frontendCapabilitiesFile)
if err != nil {
t.Fatalf("read %s: %v", frontendCapabilitiesFile, err)
}
src := string(data)
start := strings.Index(src, "TOOL_CAPABILITY_REQUIREMENTS")
end := strings.Index(src[start:], "\n};")
if start < 0 || end < 0 {
t.Fatal("TOOL_CAPABILITY_REQUIREMENTS not found in the frontend file")
}
body := src[start : start+end]
entry := regexp.MustCompile(`(?m)^\s*([a-z_]+):\s*\{([^}]*)\},?`)
list := func(fields, key string) []KBCapability {
m := regexp.MustCompile(key + `:\s*\[([^\]]*)\]`).FindStringSubmatch(fields)
if m == nil {
return nil
}
var out []KBCapability
for _, v := range regexp.MustCompile(`'([a-z]+)'`).FindAllStringSubmatch(m[1], -1) {
out = append(out, KBCapability(v[1]))
}
return out
}
out := map[string]ToolRequirement{}
for _, m := range entry.FindAllStringSubmatch(body, -1) {
fields := m[2]
out[m[1]] = ToolRequirement{
AnyOf: list(fields, "anyOf"),
AllOf: list(fields, "allOf"),
ConsumesFiles: strings.Contains(fields, "consumesFiles: true"),
Auxiliary: strings.Contains(fields, "auxiliary: true"),
}
}
return out
}
func sortedCaps(c []KBCapability) []KBCapability {
out := slices.Clone(c)
sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
return out
}
func TestFrontendToolCapabilitiesMatchBackend(t *testing.T) {
front := parseFrontendRequirements(t)
if len(front) == 0 {
t.Fatal("parsed no frontend requirements")
}
for name, back := range ToolCapabilityRequirements {
f, ok := front[name]
if !ok {
t.Errorf("%s: missing from %s", name, frontendCapabilitiesFile)
continue
}
if !slices.Equal(sortedCaps(f.AnyOf), sortedCaps(back.AnyOf)) ||
!slices.Equal(sortedCaps(f.AllOf), sortedCaps(back.AllOf)) ||
f.ConsumesFiles != back.ConsumesFiles || f.Auxiliary != back.Auxiliary {
t.Errorf("%s: frontend %+v, backend %+v", name, f, back)
}
}
for name := range front {
if _, ok := ToolCapabilityRequirements[name]; !ok {
t.Errorf("%s: only in the frontend map", name)
}
}
}

View File

@ -0,0 +1,38 @@
package repository
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// pluginTenantSettingRepository stores per-tenant plugin switches
// (plugin_tenant_settings, migration 000115). A tenant has at most one row
// per plugin, and only for plugins it changed, so List does not paginate.
type pluginTenantSettingRepository struct {
db *gorm.DB
}
// NewPluginTenantSettingRepository wires the repository into the container.
func NewPluginTenantSettingRepository(db *gorm.DB) interfaces.PluginTenantSettingRepository {
return &pluginTenantSettingRepository{db: db}
}
func (r *pluginTenantSettingRepository) List(
ctx context.Context, tenantID uint64,
) ([]types.PluginTenantSetting, error) {
var rows []types.PluginTenantSetting
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("plugin_id ASC").Find(&rows).Error
return rows, err
}
// Upsert writes the row keyed by (tenant_id, plugin_id).
func (r *pluginTenantSettingRepository) Upsert(ctx context.Context, s *types.PluginTenantSetting) error {
return r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "plugin_id"}},
DoUpdates: clause.AssignmentColumns([]string{"enabled", "config", "updated_by", "updated_at"}),
}).Create(s).Error
}

View File

@ -1216,115 +1216,33 @@ func (s *agentService) registerTools(
// logger.Infof(ctx, "Registering tools: %v, webSearchEnabled: %v", allowedTools, config.WebSearchEnabled)
// Register each allowed tool
build := &toolBuildContext{
ctx: ctx,
config: config,
rerankModel: rerankModel,
sessionID: sessionID,
wikiScopes: wikiScopes,
wikiRoutes: wikiRoutes,
wikiKBIDs: wikiKBIDs,
writableWikiKBIDs: writableWikiKBIDs,
}
for _, toolName := range allowedTools {
var toolToRegister types.Tool
switch toolName {
case tools.ToolThinking:
toolToRegister = tools.NewSequentialThinkingTool()
case tools.ToolTodoWrite:
toolToRegister = tools.NewTodoWriteTool()
case tools.ToolSearchKnowledge:
toolToRegister = tools.NewSearchKnowledgeTool(
s.knowledgeBaseService,
s.knowledgeService,
s.chunkService,
config.SearchTargets,
rerankModel,
s.cfg,
)
case tools.ToolReadDocument:
toolToRegister = tools.NewReadDocumentTool(s.knowledgeService, s.chunkService, config.SearchTargets)
case tools.ToolListDocuments:
toolToRegister = tools.NewListDocumentsTool(s.knowledgeService, config.SearchTargets)
case tools.ToolQueryKnowledgeGraph:
var chunkRepo interfaces.ChunkRepository
if s.chunkService != nil {
chunkRepo = s.chunkService.GetRepository()
}
toolToRegister = tools.NewQueryKnowledgeGraphTool(s.knowledgeBaseService, config.SearchTargets).
WithKnowledgeScope(s.knowledgeService).
WithGraph(s.graphRepo, chunkRepo)
case tools.ToolSearchConversations:
// The owner is captured from the caller's identity here, not read
// from the model's arguments, so no prompt can redirect the search
// at somebody else's conversations.
toolToRegister = tools.NewSearchConversationsTool(
s.messageService, types.SessionOwnerIDFromContext(ctx), sessionID)
case tools.ToolSearchMemory:
// Reaching this case means the memory switches were already
// checked above, where the tool is injected. Which memory space is
// read is resolved from the request context inside the service, so
// this tool needs no owner argument and none can be supplied.
toolToRegister = tools.NewSearchMemoryTool(s.memoryService)
case tools.ToolDatabaseQuery:
toolToRegister = tools.NewDatabaseQueryTool(s.db, config.SearchTargets)
case tools.ToolWebSearch:
toolToRegister = tools.NewWebSearchTool(
s.webSearchService,
config.WebSearchMaxResults,
config.WebSearchProviderID,
)
logger.Infof(ctx, "Registered web_search tool for session: %s, maxResults: %d, providerID: %s", sessionID, config.WebSearchMaxResults, config.WebSearchProviderID)
case tools.ToolWebFetch:
toolToRegister = tools.NewWebFetchTool()
logger.Infof(ctx, "Registered web_fetch tool for session: %s", sessionID)
case tools.ToolDataAnalysis:
toolToRegister = tools.NewDataAnalysisTool(s.knowledgeBaseService, s.knowledgeService, s.tenantService, s.fileService, s.duckdb, sessionID, s.storageResolver).
WithSearchTargets(config.SearchTargets)
logger.Infof(ctx, "Registered data_analysis tool for session: %s", sessionID)
case tools.ToolDataSchema:
toolToRegister = tools.NewDataSchemaTool(s.knowledgeService, s.chunkService.GetRepository()).
WithSearchTargets(config.SearchTargets)
logger.Infof(ctx, "Registered data_schema tool")
// Wiki tools — only registered when wiki KBs are detected
case tools.ToolWikiReadPage:
toolToRegister = tools.NewWikiReadPageTool(s.wikiPageService, s.knowledgeService, wikiScopes, wikiRoutes)
case tools.ToolWikiSearch:
toolToRegister = tools.NewWikiSearchTool(s.wikiPageService, s.knowledgeService, wikiScopes, wikiRoutes)
case tools.ToolWikiFlagIssue:
toolToRegister = tools.NewWikiFlagIssueTool(s.wikiPageService, writableWikiKBIDs, wikiRoutes).
WithKnowledgeScope(s.knowledgeService, config.SearchTargets)
case tools.ToolWikiReadIssue:
toolToRegister = tools.NewWikiReadIssueTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiUpdateIssue:
toolToRegister = tools.NewWikiUpdateIssueTool(s.wikiPageService, writableWikiKBIDs)
case tools.ToolWikiWritePage:
toolToRegister = tools.NewWikiWritePageTool(
s.wikiPageService, writableWikiKBIDs, s.knowledgeService, wikiRoutes,
).WithSearchTargets(config.SearchTargets)
case tools.ToolWikiReplaceText:
toolToRegister = tools.NewWikiReplaceTextTool(
s.wikiPageService, writableWikiKBIDs, s.knowledgeService, wikiRoutes,
).WithSearchTargets(config.SearchTargets)
case tools.ToolWikiRenamePage:
toolToRegister = tools.NewWikiRenamePageTool(s.wikiPageService, writableWikiKBIDs, wikiRoutes)
case tools.ToolWikiDeletePage:
toolToRegister = tools.NewWikiDeletePageTool(s.wikiPageService, writableWikiKBIDs, wikiRoutes)
case tools.ToolShellExec, tools.ToolReadFile, tools.LegacyToolReadSkill, tools.LegacyToolExecuteSkillScript,
tools.ToolListSandboxFiles, tools.LegacyToolReadSandboxFile, tools.ToolWriteSandboxFile,
tools.ToolEditSandboxFile:
// Bound to the resolved sandbox manager in registerSandboxFileTools
// / registerSandboxShellIfAllowed / initializeSkillsManager.
// Listing them here would warn "Unknown tool: shell_exec" on every
// skill install, then register the real tool a few lines later.
if sandboxBoundTools[toolName] {
continue
default:
}
factory, ok := builtinToolFactories[toolName]
if !ok {
logger.Warnf(ctx, "Unknown tool: %s", toolName)
continue
}
if toolToRegister != nil {
if toolToRegister.Name() != toolName {
logger.Warnf(ctx, "Tool name mismatch: expected %s, got %s", toolName, toolToRegister.Name())
}
registry.RegisterTool(toolToRegister)
toolToRegister := factory(s, build)
if toolToRegister == nil {
continue
}
if toolToRegister.Name() != toolName {
logger.Warnf(ctx, "Tool name mismatch: expected %s, got %s", toolName, toolToRegister.Name())
}
registry.RegisterTool(toolToRegister)
}
logger.Infof(ctx, "Registered %d tools", len(registry.ListTools()))

View File

@ -0,0 +1,137 @@
package service
import (
"context"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// toolBuildContext is what building one agent tool may need from the run.
type toolBuildContext struct {
ctx context.Context
config *types.AgentConfig
rerankModel rerank.Reranker
sessionID string
wikiScopes []tools.WikiScope
wikiRoutes *tools.WikiRouteResolver
wikiKBIDs []string
writableWikiKBIDs []string
}
// toolFactory builds one builtin tool for a run.
type toolFactory func(s *agentService, b *toolBuildContext) types.Tool
// builtinToolFactories builds each tool an agent allowlist may name. Adding a
// builtin tool means adding its factory here; tools from plugins arrive as MCP
// tools and are registered separately (registerMCPTools).
var builtinToolFactories = map[string]toolFactory{
tools.ToolThinking: func(*agentService, *toolBuildContext) types.Tool { return tools.NewSequentialThinkingTool() },
tools.ToolTodoWrite: func(*agentService, *toolBuildContext) types.Tool { return tools.NewTodoWriteTool() },
tools.ToolSearchKnowledge: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewSearchKnowledgeTool(
s.knowledgeBaseService, s.knowledgeService, s.chunkService, b.config.SearchTargets, b.rerankModel, s.cfg,
)
},
tools.ToolReadDocument: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewReadDocumentTool(s.knowledgeService, s.chunkService, b.config.SearchTargets)
},
tools.ToolListDocuments: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewListDocumentsTool(s.knowledgeService, b.config.SearchTargets)
},
tools.ToolQueryKnowledgeGraph: func(s *agentService, b *toolBuildContext) types.Tool {
var chunkRepo interfaces.ChunkRepository
if s.chunkService != nil {
chunkRepo = s.chunkService.GetRepository()
}
return tools.NewQueryKnowledgeGraphTool(s.knowledgeBaseService, b.config.SearchTargets).
WithKnowledgeScope(s.knowledgeService).
WithGraph(s.graphRepo, chunkRepo)
},
// The owner is captured from the caller's identity here, not read from the
// model's arguments, so no prompt can redirect the search at somebody
// else's conversations.
tools.ToolSearchConversations: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewSearchConversationsTool(s.messageService, types.SessionOwnerIDFromContext(b.ctx), b.sessionID)
},
// Reaching this factory means the memory switches were already checked
// where the tool is injected. The memory space is resolved from the
// request context inside the service, so the tool takes no owner.
tools.ToolSearchMemory: func(s *agentService, _ *toolBuildContext) types.Tool {
return tools.NewSearchMemoryTool(s.memoryService)
},
tools.ToolDatabaseQuery: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewDatabaseQueryTool(s.db, b.config.SearchTargets)
},
tools.ToolWebSearch: func(s *agentService, b *toolBuildContext) types.Tool {
logger.Infof(b.ctx, "Registered web_search tool for session: %s, maxResults: %d, providerID: %s",
b.sessionID, b.config.WebSearchMaxResults, b.config.WebSearchProviderID)
return tools.NewWebSearchTool(s.webSearchService, b.config.WebSearchMaxResults, b.config.WebSearchProviderID)
},
tools.ToolWebFetch: func(_ *agentService, b *toolBuildContext) types.Tool {
logger.Infof(b.ctx, "Registered web_fetch tool for session: %s", b.sessionID)
return tools.NewWebFetchTool()
},
tools.ToolDataAnalysis: func(s *agentService, b *toolBuildContext) types.Tool {
logger.Infof(b.ctx, "Registered data_analysis tool for session: %s", b.sessionID)
return tools.NewDataAnalysisTool(
s.knowledgeBaseService, s.knowledgeService, s.tenantService, s.fileService, s.duckdb,
b.sessionID, s.storageResolver,
).WithSearchTargets(b.config.SearchTargets)
},
tools.ToolDataSchema: func(s *agentService, b *toolBuildContext) types.Tool {
logger.Infof(b.ctx, "Registered data_schema tool")
return tools.NewDataSchemaTool(s.knowledgeService, s.chunkService.GetRepository()).
WithSearchTargets(b.config.SearchTargets)
},
// Wiki tools only make it into the allowlist when wiki KBs are in scope.
tools.ToolWikiReadPage: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiReadPageTool(s.wikiPageService, s.knowledgeService, b.wikiScopes, b.wikiRoutes)
},
tools.ToolWikiSearch: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiSearchTool(s.wikiPageService, s.knowledgeService, b.wikiScopes, b.wikiRoutes)
},
tools.ToolWikiFlagIssue: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiFlagIssueTool(s.wikiPageService, b.writableWikiKBIDs, b.wikiRoutes).
WithKnowledgeScope(s.knowledgeService, b.config.SearchTargets)
},
tools.ToolWikiReadIssue: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiReadIssueTool(s.wikiPageService, b.wikiKBIDs)
},
tools.ToolWikiUpdateIssue: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiUpdateIssueTool(s.wikiPageService, b.writableWikiKBIDs)
},
tools.ToolWikiWritePage: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiWritePageTool(s.wikiPageService, b.writableWikiKBIDs, s.knowledgeService, b.wikiRoutes).
WithSearchTargets(b.config.SearchTargets)
},
tools.ToolWikiReplaceText: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiReplaceTextTool(s.wikiPageService, b.writableWikiKBIDs, s.knowledgeService, b.wikiRoutes).
WithSearchTargets(b.config.SearchTargets)
},
tools.ToolWikiRenamePage: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiRenamePageTool(s.wikiPageService, b.writableWikiKBIDs, b.wikiRoutes)
},
tools.ToolWikiDeletePage: func(s *agentService, b *toolBuildContext) types.Tool {
return tools.NewWikiDeletePageTool(s.wikiPageService, b.writableWikiKBIDs, b.wikiRoutes)
},
}
// sandboxBoundTools are allowlist names bound to the resolved sandbox manager
// (registerSandboxFileTools / registerSandboxShellIfAllowed /
// initializeSkillsManager). They have no factory, and seeing them in the
// allowlist is expected rather than an unknown tool.
var sandboxBoundTools = map[string]bool{
tools.ToolShellExec: true,
tools.ToolReadFile: true,
tools.LegacyToolReadSkill: true,
tools.LegacyToolExecuteSkillScript: true,
tools.ToolListSandboxFiles: true,
tools.LegacyToolReadSandboxFile: true,
tools.ToolWriteSandboxFile: true,
tools.ToolEditSandboxFile: true,
}

View File

@ -0,0 +1,31 @@
package service
import (
"testing"
"github.com/Tencent/WeKnora/internal/agent/tools"
)
func TestEverySelectableToolHasAFactory(t *testing.T) {
names := []string{tools.ToolWebSearch, tools.ToolWebFetch, tools.ToolSearchMemory}
for _, def := range tools.AvailableToolDefinitions() {
names = append(names, def.Name)
}
names = append(names, tools.DefaultAllowedTools()...)
for _, name := range names {
if _, ok := builtinToolFactories[name]; !ok {
t.Errorf("%s has no factory in builtinToolFactories", name)
}
if sandboxBoundTools[name] {
t.Errorf("%s is both selectable and sandbox-bound", name)
}
}
}
func TestFactoriesAndSandboxToolsDoNotOverlap(t *testing.T) {
for name := range sandboxBoundTools {
if _, ok := builtinToolFactories[name]; ok {
t.Errorf("%s is sandbox-bound but also has a factory", name)
}
}
}

View File

@ -6,7 +6,6 @@ package container
import (
"context"
"database/sql"
"errors"
"fmt"
"io"
"net"
@ -59,29 +58,10 @@ import (
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/database"
"github.com/Tencent/WeKnora/internal/datasource"
confluenceConnector "github.com/Tencent/WeKnora/internal/datasource/connector/confluence"
dingtalkConnector "github.com/Tencent/WeKnora/internal/datasource/connector/dingtalk"
"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"
gitlabConnector "github.com/Tencent/WeKnora/internal/datasource/connector/gitlab"
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"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/handler"
"github.com/Tencent/WeKnora/internal/handler/session"
imPkg "github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/im/dingtalk"
"github.com/Tencent/WeKnora/internal/im/feishu"
"github.com/Tencent/WeKnora/internal/im/mattermost"
"github.com/Tencent/WeKnora/internal/im/qqbot"
"github.com/Tencent/WeKnora/internal/im/slack"
"github.com/Tencent/WeKnora/internal/im/telegram"
"github.com/Tencent/WeKnora/internal/im/wechat"
"github.com/Tencent/WeKnora/internal/im/wecom"
"github.com/Tencent/WeKnora/internal/im/yunzhijia"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
@ -91,6 +71,10 @@ import (
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/limiter" // register built-in vendors
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
pluginbuiltin "github.com/Tencent/WeKnora/internal/plugin/builtin"
plugindriver "github.com/Tencent/WeKnora/internal/plugin/driver"
pluginregistry "github.com/Tencent/WeKnora/internal/plugin/registry"
plugintenancy "github.com/Tencent/WeKnora/internal/plugin/tenancy"
"github.com/Tencent/WeKnora/internal/router"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/storageallowlist"
@ -594,6 +578,14 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewEmbedChannelHandler))
must(container.Provide(handler.NewMCPEndpointHandler))
must(container.Provide(handler.NewWeKnoraCloudHandler))
// Plugin catalog: builtins are described from what is registered above.
must(container.Provide(newPluginRegistry))
must(container.Provide(repository.NewPluginTenantSettingRepository))
must(container.Provide(plugintenancy.NewService))
must(container.Provide(func(s *plugintenancy.Service) interfaces.PluginGate { return s }))
must(container.Invoke(installPluginGate))
must(container.Provide(newPluginDrivers))
must(container.Provide(handler.NewPluginHandler))
logger.Debugf(ctx, "[Container] HTTP handlers registered")
// Wire the chat package's local image resolver so multimodal chat can read
@ -1807,37 +1799,51 @@ func NewDuckDB() (*sql.DB, error) {
// Each provider type is registered with its factory function that accepts parameters.
// Provider instances are created on-demand when tenants configure them.
func registerWebSearchProviders(registry *infra_web_search.Registry) {
registry.Register("duckduckgo", infra_web_search.NewDuckDuckGoProvider)
registry.Register("google", infra_web_search.NewGoogleProvider)
registry.Register("bing", infra_web_search.NewBingProvider)
registry.Register("tavily", infra_web_search.NewTavilyProvider)
registry.Register("ollama", infra_web_search.NewOllamaProvider)
registry.Register("baidu", infra_web_search.NewBaiduProvider)
registry.Register("searxng", infra_web_search.NewSearxngProvider)
registry.Register("keenable", infra_web_search.NewKeenableProvider)
registry.Register("zhipu", infra_web_search.NewZhipuProvider)
registry.Register("exa", infra_web_search.NewExaProvider)
registry.Register("metaso", infra_web_search.NewMetasoProvider)
registry.Register("bocha", infra_web_search.NewBochaProvider)
registry.Register("brave", infra_web_search.NewBraveProvider)
registry.Register("serply", infra_web_search.NewSerplyProvider)
pluginbuiltin.RegisterWebSearchProviders(registry)
}
// newPluginRegistry builds the plugin registry from the builtins this process
// has registered. It depends on the IM service so adapter factories are in
// place before the platforms are read.
func newPluginRegistry(
connectors *datasource.ConnectorRegistry,
webSearch *infra_web_search.Registry,
imService *imPkg.Service,
) (*pluginregistry.Registry, error) {
return pluginbuiltin.NewRegistry(pluginbuiltin.Live{
Version: handler.Version,
Connectors: connectors,
WebSearch: webSearch,
IMPlatforms: imService.Platforms(),
})
}
// newPluginDrivers returns the drivers that run plugin code. Only builtins
// exist today; host, remote and kubernetes drivers join this set.
func newPluginDrivers(reg *pluginregistry.Registry) *plugindriver.Set {
return plugindriver.NewSet(plugindriver.NewBuiltin(reg.Plugin))
}
// installPluginGate gives the integration handlers the tenant plugin switches,
// so a disabled plugin's integrations drop out of type listings and cannot
// back new instances.
func installPluginGate(
gate interfaces.PluginGate,
models *handler.ModelHandler,
webSearch *handler.WebSearchProviderHandler,
dataSources *handler.DataSourceHandler,
imHandler *handler.IMHandler,
) {
for _, h := range []interface{ SetPluginGate(interfaces.PluginGate) }{models, webSearch, dataSources, imHandler} {
h.SetPluginGate(gate)
}
}
// registerIMService registers adapter factories, loads enabled channels, and
// wires the process-lifetime shutdown hook. Each platform's factory lives in
// its own subpackage to keep this file focused on wiring.
func registerIMService(imService *imPkg.Service, cleaner interfaces.ResourceCleaner) {
imService.RegisterAdapterFactory("wecom", wecom.NewFactory())
imService.RegisterAdapterFactory("feishu", feishu.NewFactory(feishu.RegionFeishu))
// Lark is Feishu's international cloud: same adapter, different host/tenant.
imService.RegisterAdapterFactory("lark", feishu.NewFactory(feishu.RegionLark))
imService.RegisterAdapterFactory("slack", slack.NewFactory())
imService.RegisterAdapterFactory("telegram", telegram.NewFactory())
imService.RegisterAdapterFactory("dingtalk", dingtalk.NewFactory())
imService.RegisterAdapterFactory("mattermost", mattermost.NewFactory())
imService.RegisterAdapterFactory("wechat", wechat.NewFactory())
imService.RegisterAdapterFactory("qqbot", qqbot.NewFactory())
imService.RegisterAdapterFactory("yunzhijia", yunzhijia.NewFactory())
pluginbuiltin.RegisterIMAdapters(imService)
// Load and start all enabled channels from database
if err := imService.LoadAndStartChannels(); err != nil {
@ -1854,54 +1860,7 @@ func registerIMService(imService *imPkg.Service, cleaner interfaces.ResourceClea
// Aggregates registration errors via errors.Join so a misconfigured or duplicated connector fails
// container initialization loudly instead of silently disabling the feature at runtime.
func initConnectorRegistry() (*datasource.ConnectorRegistry, error) {
registry := datasource.NewConnectorRegistry()
var errs error
if err := registry.Register(wiki.NewConnector(core.RegionFeishu)); err != nil {
errs = errors.Join(errs, fmt.Errorf("register feishu connector: %w", err))
}
// Lark is Feishu's international cloud: same connector, different host/tenant.
if err := registry.Register(wiki.NewConnector(core.RegionLark)); err != nil {
errs = errors.Join(errs, fmt.Errorf("register lark connector: %w", err))
}
// Feishu/Lark Drive (云盘) mode: different connector type so the registry
// dispatches to the Drive connector. Shares core.Client/Region/export logic
// with the wiki connector. See 飞书云盘数据源设计.md / ADR-0001.
if err := registry.Register(drive.NewDriveConnector(core.RegionFeishuDrive)); err != nil {
errs = errors.Join(errs, fmt.Errorf("register feishu_drive connector: %w", err))
}
if err := registry.Register(drive.NewDriveConnector(core.RegionLarkDrive)); err != nil {
errs = errors.Join(errs, fmt.Errorf("register lark_drive connector: %w", err))
}
if err := registry.Register(notionConnector.NewConnector()); err != nil {
errs = errors.Join(errs, fmt.Errorf("register notion connector: %w", err))
}
if err := registry.Register(confluenceConnector.NewConnector()); err != nil {
errs = errors.Join(errs, fmt.Errorf("register confluence connector: %w", err))
}
if err := registry.Register(yuqueConnector.NewConnector()); err != nil {
errs = errors.Join(errs, fmt.Errorf("register yuque connector: %w", err))
}
if err := registry.Register(dingtalkConnector.NewConnector()); err != nil {
errs = errors.Join(errs, fmt.Errorf("register dingtalk 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))
}
if err := registry.Register(gitlabConnector.NewConnector()); err != nil {
errs = errors.Join(errs, fmt.Errorf("register gitlab connector: %w", err))
}
// Future connectors will be registered here:
// if err := registry.Register(githubConnector.NewConnector()); err != nil { ... }
if errs != nil {
return nil, errs
}
return registry, nil
return pluginbuiltin.NewConnectorRegistry()
}
// startDataSourceScheduler starts the data source cron scheduler and registers cleanup.

View File

@ -35,6 +35,7 @@ var versionedSQLiteTables = []string{
"tenant_skill_snapshots",
"tenant_skill_catalog",
"tenant_user_env_vars",
"plugin_tenant_settings",
}
// versionedSQLiteColumns maps each existing table to the columns that the
@ -69,7 +70,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
const expectedSQLiteMigrationVersion = 33
const expectedSQLiteMigrationVersion = 34
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)

View File

@ -360,6 +360,16 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
}
```
### Credential form
Describe the connector's `credentials` in `connectorForms`
(`internal/datasource/connector_forms.go`): a config schema for the fields
(mark secrets with `Secret`, use `VisibleIf` for fields that depend on
another one) plus the setup-guide links and required permissions. The
frontend renders the form from `GET /api/v1/datasource/types`, so no frontend
change is needed. Frontend locale keys named in `I18nKeys` must be listed in
`frontend/src/i18n/backendSchemaKeys.ts`; a test enforces it.
## Step 8: Test Your Connector
```go

View File

@ -2,7 +2,10 @@ package datasource
import (
"context"
"math"
"sort"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
"github.com/Tencent/WeKnora/internal/types"
)
@ -169,6 +172,16 @@ type ConnectorMetadata struct {
Priority int `json:"priority"` // Priority order for UI display (lower = higher priority)
AuthType string `json:"auth_type"` // "oauth2", "api_key", "token", etc.
Capabilities []string `json:"capabilities"` // "incremental", "webhook", "deletion_sync", etc.
// Setup guide shown next to the credential form: where to create the
// app, which scopes to grant and where to grant them.
DocURL string `json:"doc_url,omitempty"`
PermissionDocURL string `json:"permission_doc_url,omitempty"`
PermissionPageURL string `json:"permission_page_url,omitempty"`
RequiredPermissions []string `json:"required_permissions,omitempty"`
// ConfigSchema describes DataSourceConfig.Credentials for this
// connector; the editor renders the credential form from it.
ConfigSchema *configschema.Schema `json:"config_schema,omitempty"`
}
// GetConnectorMetadata returns metadata for all available connectors
@ -186,7 +199,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeLark,
Name: "Lark",
Description: "Sync documents, wikis, and content from Lark (Feishu international)",
Priority: 0,
Priority: 1,
AuthType: "oauth2",
Capabilities: []string{"incremental", "deletion_sync"},
},
@ -194,7 +207,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeFeishuDrive,
Name: "Feishu Drive (飞书云盘)",
Description: "Sync documents and files from a Feishu Drive folder",
Priority: 0,
Priority: 2,
AuthType: "oauth2",
Capabilities: []string{"incremental", "deletion_sync"},
},
@ -202,7 +215,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeLarkDrive,
Name: "Lark Drive",
Description: "Sync documents and files from a Lark Drive folder",
Priority: 0,
Priority: 3,
AuthType: "oauth2",
Capabilities: []string{"incremental", "deletion_sync"},
},
@ -210,7 +223,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeNotion,
Name: "Notion",
Description: "Sync pages and databases from Notion",
Priority: 1,
Priority: 4,
AuthType: "api_key",
Capabilities: []string{"incremental"},
},
@ -218,7 +231,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeConfluence,
Name: "Confluence",
Description: "Sync spaces and pages from Atlassian Confluence",
Priority: 2,
Priority: 5,
AuthType: "api_key",
Capabilities: []string{"incremental", "deletion_sync"},
},
@ -226,7 +239,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeYuque,
Name: "Yuque (语雀)",
Description: "Sync knowledge bases and documents from Yuque",
Priority: 3,
Priority: 6,
AuthType: "api_key",
Capabilities: []string{"incremental"},
},
@ -234,7 +247,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeIMA,
Name: "Tencent IMA (ima.qq.com)",
Description: "Sync knowledge bases and documents from Tencent IMA",
Priority: 3,
Priority: 8,
AuthType: "api_key",
Capabilities: []string{"incremental", "deletion_sync"},
},
@ -242,7 +255,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeGitHub,
Name: "GitHub",
Description: "Sync repositories, wikis, and issues from GitHub",
Priority: 4,
Priority: 20,
AuthType: "oauth2",
Capabilities: []string{"incremental"},
},
@ -250,7 +263,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeGoogleDrive,
Name: "Google Drive",
Description: "Sync documents and files from Google Drive",
Priority: 5,
Priority: 21,
AuthType: "oauth2",
Capabilities: []string{"incremental"},
},
@ -258,7 +271,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeOneDrive,
Name: "OneDrive / SharePoint",
Description: "Sync documents and files from Microsoft OneDrive",
Priority: 6,
Priority: 22,
AuthType: "oauth2",
Capabilities: []string{"incremental"},
},
@ -274,7 +287,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeWebCrawler,
Name: "Web Crawler (Sitemap)",
Description: "Crawl websites via Sitemap.xml",
Priority: 9,
Priority: 23,
AuthType: "none",
Capabilities: []string{},
},
@ -282,7 +295,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeSlack,
Name: "Slack",
Description: "Sync channel messages and files from Slack",
Priority: 10,
Priority: 24,
AuthType: "oauth2",
Capabilities: []string{"incremental"},
},
@ -290,7 +303,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeIMAP,
Name: "Email (IMAP)",
Description: "Sync email content from IMAP servers",
Priority: 11,
Priority: 25,
AuthType: "password",
Capabilities: []string{},
},
@ -298,7 +311,7 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeRSS,
Name: "RSS / Atom Feed",
Description: "Sync articles from RSS/Atom feeds",
Priority: 12,
Priority: 9,
AuthType: "custom",
Capabilities: []string{"incremental"},
},
@ -306,30 +319,50 @@ var ConnectorMetadataRegistry = map[string]ConnectorMetadata{
Type: types.ConnectorTypeGitLab,
Name: "GitLab",
Description: "Sync files from GitLab projects",
Priority: 8,
Priority: 10,
AuthType: "token",
Capabilities: []string{"incremental", "hierarchical"},
},
}
// ListAvailableConnectors returns all available connector metadata
// sorted by priority
// ListAvailableConnectors returns the metadata of every known connector,
// including ones not registered yet, with their credential forms, sorted by
// priority and then type.
func ListAvailableConnectors() []ConnectorMetadata {
metadata := make([]ConnectorMetadata, 0, len(ConnectorMetadataRegistry))
for _, meta := range ConnectorMetadataRegistry {
metadata = append(metadata, meta)
metadata = append(metadata, withForm(meta))
}
// Sort by priority (insertion sort for simplicity)
for i := 1; i < len(metadata); i++ {
key := metadata[i]
j := i - 1
for j >= 0 && metadata[j].Priority > key.Priority {
metadata[j+1] = metadata[j]
j--
sort.Slice(metadata, func(i, j int) bool {
if metadata[i].Priority != metadata[j].Priority {
return metadata[i].Priority < metadata[j].Priority
}
metadata[j+1] = key
}
return metadata[i].Type < metadata[j].Type
})
return metadata
}
// Metadata returns the metadata of the connectors registered here, in
// ListAvailableConnectors order. A registered connector without an entry in
// ConnectorMetadataRegistry is listed last under its type.
func (r *ConnectorRegistry) Metadata() []ConnectorMetadata {
out := make([]ConnectorMetadata, 0, len(r.connectors))
seen := make(map[string]bool, len(r.connectors))
for _, meta := range ListAvailableConnectors() {
if _, ok := r.connectors[meta.Type]; ok {
out = append(out, meta)
seen[meta.Type] = true
}
}
rest := make([]string, 0)
for t := range r.connectors {
if !seen[t] {
rest = append(rest, t)
}
}
sort.Strings(rest)
for _, t := range rest {
out = append(out, ConnectorMetadata{Type: t, Name: t, Priority: math.MaxInt32})
}
return out
}

View File

@ -0,0 +1,234 @@
package datasource
import (
"github.com/Tencent/WeKnora/internal/plugin/configschema"
"github.com/Tencent/WeKnora/internal/types"
)
// connectorForm is what the data source editor needs to set one connector up:
// the setup guide and the credential form. These lived in the frontend until
// the editor moved to config schemas; keeping them next to the connector means
// a new connector needs no frontend change.
type connectorForm struct {
docURL string
permissionDocURL string
permissionPageURL string
requiredPermissions []string
schema func() *configschema.Schema
}
// withForm fills a connector's setup guide and credential schema into its
// metadata. Connectors without a form (not implemented yet) are unchanged.
func withForm(meta ConnectorMetadata) ConnectorMetadata {
form, ok := connectorForms[meta.Type]
if !ok {
return meta
}
meta.DocURL = form.docURL
meta.PermissionDocURL = form.permissionDocURL
meta.PermissionPageURL = form.permissionPageURL
meta.RequiredPermissions = append([]string(nil), form.requiredPermissions...)
meta.ConfigSchema = form.schema()
return meta
}
// Scopes the Feishu / Lark apps must be granted. Lark is Feishu's
// international cloud: same APIs and scope identifiers, separate console.
var (
feishuWikiPermissions = []string{
"wiki:wiki:readonly", "drive:drive:readonly", "drive:export:readonly", "docx:document:readonly",
}
feishuDrivePermissions = []string{
"drive:drive:readonly", "drive:export:readonly", "docx:document:readonly",
}
)
var connectorForms = map[string]connectorForm{
types.ConnectorTypeFeishu: {
docURL: "https://open.feishu.cn/app",
permissionDocURL: "https://open.feishu.cn/document/server-docs/docs/wiki-v2/wiki-overview",
permissionPageURL: "https://open.feishu.cn/app",
requiredPermissions: feishuWikiPermissions,
schema: func() *configschema.Schema { return feishuSchema("https://open.feishu.cn") },
},
types.ConnectorTypeLark: {
docURL: "https://open.larksuite.com/app",
permissionDocURL: "https://open.larksuite.com/document/server-docs/docs/wiki-v2/wiki-overview",
permissionPageURL: "https://open.larksuite.com/app",
requiredPermissions: feishuWikiPermissions,
schema: func() *configschema.Schema { return feishuSchema("https://open.larksuite.com") },
},
// Drive mode syncs a folder: no wiki scope needed.
types.ConnectorTypeFeishuDrive: {
docURL: "https://open.feishu.cn/app",
permissionDocURL: "https://open.feishu.cn/document/server-docs/docs/drive-v1/file/list",
permissionPageURL: "https://open.feishu.cn/app",
requiredPermissions: feishuDrivePermissions,
schema: func() *configschema.Schema { return feishuSchema("https://open.feishu.cn") },
},
types.ConnectorTypeLarkDrive: {
docURL: "https://open.larksuite.com/app",
permissionDocURL: "https://open.larksuite.com/document/server-docs/docs/drive-v1/file/list",
permissionPageURL: "https://open.larksuite.com/app",
requiredPermissions: feishuDrivePermissions,
schema: func() *configschema.Schema { return feishuSchema("https://open.larksuite.com") },
},
types.ConnectorTypeNotion: {
docURL: "https://www.notion.so/my-integrations",
schema: func() *configschema.Schema {
token := secretField("Integration Token", "datasource.field.integrationToken", "ntn_xxxx", 1)
return configschema.Object().Set("api_key", token, true)
},
},
types.ConnectorTypeConfluence: {
docURL: "https://developer.atlassian.com/cloud/confluence/rest/",
permissionDocURL: "https://developer.atlassian.com/cloud/confluence/rest/",
permissionPageURL: "https://id.atlassian.com/manage-profile/security/api-tokens",
schema: confluenceSchema,
},
types.ConnectorTypeYuque: {
docURL: "https://www.yuque.com/yuque/developer/api",
permissionDocURL: "https://www.yuque.com/yuque/developer/api",
permissionPageURL: "https://www.yuque.com/settings/tokens",
requiredPermissions: []string{"repo:read", "doc:read"},
schema: func() *configschema.Schema {
return configschema.Object().
Set("api_token", secretField("API Token", "datasource.field.apiToken", "", 1), true).
Set("base_url", baseURLField("https://www.yuque.com", 2), false)
},
},
types.ConnectorTypeDingTalk: {
docURL: "https://open.dingtalk.com/document/development/knowledge-base-overview",
permissionDocURL: "https://open.dingtalk.com/document/development/get-knowledge-base-list",
permissionPageURL: "https://open-dev.dingtalk.com/",
requiredPermissions: []string{
"Wiki.Workspace.Read", "Wiki.Node.Read", "Storage.File.Read",
},
schema: func() *configschema.Schema {
operator := textField("Operator Union ID", "datasource.field.operatorId", "", 3)
operator.Description = "Reads knowledge bases with this user's permissions."
operator.I18nKeys["description"] = "datasource.field.operatorIdHint"
return configschema.Object().
Set("client_id", textField("Client ID", "datasource.field.clientId", "dingxxxxxxxx", 1), true).
Set("client_secret", secretField("Client Secret", "datasource.field.clientSecret", "", 2), true).
Set("operator_id", operator, true)
},
},
// Tencent IMA: OpenAPI with two static headers, no OAuth.
types.ConnectorTypeIMA: {
docURL: "https://ima.qq.com/agent-interface",
permissionDocURL: "https://ima.qq.com/agent-interface",
permissionPageURL: "https://ima.qq.com/agent-interface",
schema: func() *configschema.Schema {
return configschema.Object().
Set("client_id", secretField("IMA ClientID", "datasource.field.imaClientId", "", 1), true).
Set("api_key", secretField("IMA APIKey", "datasource.field.imaApiKey", "", 2), true).
Set("base_url", baseURLField("https://ima.qq.com", 3), false)
},
},
types.ConnectorTypeRSS: {
schema: func() *configschema.Schema {
// "Name: Value" lines, edited as rows by the headers widget. Not
// marked secret: the whole credential map is encrypted and never
// returned, and the widget needs to read back what it wrote.
headers := &configschema.Schema{
Type: configschema.TypeString,
Title: "Custom headers (optional)",
Description: `For private feeds. One per line in "Name: Value" form.`,
Widget: "headers",
I18nKeys: map[string]string{
"title": "datasource.field.authHeaders",
"description": "datasource.field.authHeadersHint",
},
Order: 1,
}
return configschema.Object().Set("auth_headers", headers, false)
},
},
types.ConnectorTypeGitLab: {
schema: func() *configschema.Schema {
baseURL := textField("GitLab URL", "datasource.gitlab.baseUrl", "https://gitlab.example.com", 1)
return configschema.Object().
Set("base_url", baseURL, true).
Set("access_token", secretField("Personal access token", "datasource.gitlab.accessToken", "", 2), true)
},
},
}
func feishuSchema(defaultBaseURL string) *configschema.Schema {
return configschema.Object().
Set("app_id", textField("App ID", "datasource.field.appId", "cli_xxxx", 1), true).
Set("app_secret", secretField("App Secret", "datasource.field.appSecret", "", 2), true).
Set("base_url", baseURLField(defaultBaseURL, 3), false)
}
// confluenceSchema switches the secret with the edition: Server / Data Center
// takes a password, Cloud an API token.
func confluenceSchema() *configschema.Schema {
edition := &configschema.Schema{
Type: configschema.TypeString,
Title: "Edition",
Default: "server",
Widget: "select",
I18nKeys: map[string]string{"title": "datasource.field.confluenceEdition"},
OneOf: []*configschema.Schema{
{
Const: "server", Title: "Server / Data Center",
I18nKeys: map[string]string{"title": "datasource.field.confluenceEditionServer"},
},
{
Const: "cloud", Title: "Cloud",
I18nKeys: map[string]string{"title": "datasource.field.confluenceEditionCloud"},
},
},
Order: 0,
}
password := secretField("Server/DC password", "datasource.field.confluencePassword", "Server/DC password", 4)
password.VisibleIf = map[string]any{"edition": "server"}
token := secretField("Cloud API token", "datasource.field.confluenceApiToken", "Cloud API token", 5)
token.VisibleIf = map[string]any{"edition": "cloud"}
return configschema.Object().
Set("edition", edition, false).
Set("base_url", textField(
"Confluence URL", "datasource.field.confluenceBaseUrl",
"https://confluence.example.com or https://team.atlassian.net/wiki", 1,
), true).
Set("username", textField(
"Username or email", "datasource.field.confluenceUsername", "name or email", 2,
), true).
Set("password", password, true).
Set("api_token", token, true)
}
// textField is a plain string input. An empty placeholder falls back to the
// generic "Enter value" hint the editor always showed.
func textField(title, titleKey, placeholder string, order int) *configschema.Schema {
f := &configschema.Schema{
Type: configschema.TypeString,
Title: title,
Placeholder: placeholder,
I18nKeys: map[string]string{"title": titleKey},
Order: order,
}
if placeholder == "" {
f.Placeholder = "Enter value"
f.I18nKeys["placeholder"] = "credential.inputPlaceholder"
}
return f
}
func secretField(title, titleKey, placeholder string, order int) *configschema.Schema {
f := textField(title, titleKey, placeholder, order)
f.Secret = true
f.Widget = "password"
return f
}
// baseURLField is the optional endpoint override for private deployments and
// reverse proxies.
func baseURLField(defaultURL string, order int) *configschema.Schema {
f := textField("Base URL (optional)", "datasource.field.baseUrl", defaultURL, order)
f.Description = "Leave empty to use the default public cloud address."
f.I18nKeys["description"] = "datasource.field.baseUrlHint"
return f
}

View File

@ -0,0 +1,100 @@
package datasource
import (
"context"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
"github.com/Tencent/WeKnora/internal/types"
)
// implementedConnectors are the types container.initConnectorRegistry
// registers; each needs a credential form.
var implementedConnectors = []string{
types.ConnectorTypeFeishu, types.ConnectorTypeLark, types.ConnectorTypeFeishuDrive,
types.ConnectorTypeLarkDrive, types.ConnectorTypeNotion, types.ConnectorTypeConfluence,
types.ConnectorTypeYuque, types.ConnectorTypeDingTalk, types.ConnectorTypeIMA,
types.ConnectorTypeRSS, types.ConnectorTypeGitLab,
}
func TestEveryImplementedConnectorHasAValidForm(t *testing.T) {
for _, typ := range implementedConnectors {
if _, ok := ConnectorMetadataRegistry[typ]; !ok {
t.Errorf("%s: no metadata", typ)
continue
}
meta := withForm(ConnectorMetadataRegistry[typ])
if meta.ConfigSchema == nil {
t.Errorf("%s: no config schema", typ)
continue
}
if err := meta.ConfigSchema.Check(); err != nil {
t.Errorf("%s: invalid schema: %v", typ, err)
}
}
}
func TestConfluenceSchemaSwitchesSecretByEdition(t *testing.T) {
s := confluenceSchema()
base := map[string]any{"base_url": "https://c.example.com", "username": "bob"}
server := map[string]any{"edition": "server", "base_url": base["base_url"], "username": "bob"}
errs := configschema.Validate(s, server)
if len(errs) != 1 || errs[0].Path != "password" {
t.Fatalf("server edition must require the password only, got %v", errs)
}
cloud := map[string]any{"edition": "cloud", "base_url": base["base_url"], "username": "bob"}
errs = configschema.Validate(s, cloud)
if len(errs) != 1 || errs[0].Path != "api_token" {
t.Fatalf("cloud edition must require the API token only, got %v", errs)
}
if got := s.SecretPaths(); strings.Join(got, ",") != "api_token,password" {
t.Fatalf("secrets = %v", got)
}
}
// fakeConnector is enough to register a type.
type fakeConnector struct {
Connector
typ string
}
func (f fakeConnector) Type() string { return f.typ }
func (fakeConnector) Validate(context.Context, *types.DataSourceConfig) error { return nil }
func TestRegistryMetadataListsRegisteredOnly(t *testing.T) {
r := NewConnectorRegistry()
for _, typ := range []string{types.ConnectorTypeNotion, types.ConnectorTypeFeishu, "zz-custom"} {
if err := r.Register(fakeConnector{typ: typ}); err != nil {
t.Fatal(err)
}
}
var got []string
for _, m := range r.Metadata() {
got = append(got, m.Type)
}
if strings.Join(got, ",") != "feishu,notion,zz-custom" {
t.Fatalf("Metadata order = %v", got)
}
meta := r.Metadata()
if meta[0].ConfigSchema == nil || len(meta[0].RequiredPermissions) == 0 || meta[0].DocURL == "" {
t.Fatalf("feishu form missing: %+v", meta[0])
}
if meta[2].Name != "zz-custom" || meta[2].ConfigSchema != nil {
t.Fatalf("unknown connector should fall back to its type: %+v", meta[2])
}
}
func TestListAvailableConnectorsIsStable(t *testing.T) {
first := ListAvailableConnectors()
for range 5 {
again := ListAvailableConnectors()
for i := range first {
if first[i].Type != again[i].Type {
t.Fatalf("order changed at %d: %s vs %s", i, first[i].Type, again[i].Type)
}
}
}
}

View File

@ -7,6 +7,7 @@ import (
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/handler/dto"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
@ -14,18 +15,22 @@ import (
// DataSourceHandler handles HTTP requests for data source management
type DataSourceHandler struct {
service interfaces.DataSourceService
kbService interfaces.KnowledgeBaseService
pluginGated
service interfaces.DataSourceService
kbService interfaces.KnowledgeBaseService
connectors *datasource.ConnectorRegistry
}
// NewDataSourceHandler creates a new data source handler
func NewDataSourceHandler(
service interfaces.DataSourceService,
kbService interfaces.KnowledgeBaseService,
connectors *datasource.ConnectorRegistry,
) *DataSourceHandler {
return &DataSourceHandler{
service: service,
kbService: kbService,
service: service,
kbService: kbService,
connectors: connectors,
}
}
@ -108,6 +113,10 @@ func (h *DataSourceHandler) CreateDataSource(c *gin.Context) {
c.JSON(status, gin.H{"error": msg})
return
}
if !h.pluginFilter(c)(manifest.PointConnectors, req.Type) {
c.JSON(http.StatusBadRequest, gin.H{"error": disabledIntegrationError})
return
}
// Enforce tenant isolation
req.TenantID = tenantID
@ -607,6 +616,18 @@ func (h *DataSourceHandler) GetSyncLog(c *gin.Context) {
// @Success 200 {object} []datasource.ConnectorMetadata
// @Router /datasource/types [get]
func (h *DataSourceHandler) GetAvailableConnectors(c *gin.Context) {
connectors := datasource.ListAvailableConnectors()
c.JSON(http.StatusOK, connectors)
// Only connectors that can actually be created: the metadata table also
// describes ones not implemented yet.
if h.connectors == nil {
c.JSON(http.StatusOK, []datasource.ConnectorMetadata{})
return
}
enabled := h.pluginFilter(c)
out := make([]datasource.ConnectorMetadata, 0)
for _, meta := range h.connectors.Metadata() {
if enabled(manifest.PointConnectors, meta.Type) {
out = append(out, meta)
}
}
c.JSON(http.StatusOK, out)
}

View File

@ -44,7 +44,7 @@ func TestDataSourceScheduleAPIRejectsInvalidCron(t *testing.T) {
require.NoError(t, scheduler.AddOrUpdate(ds))
}
entries := scheduler.EntryCount()
h := NewDataSourceHandler(svc, kbSvc)
h := NewDataSourceHandler(svc, kbSvc, nil)
router := newDataSourceTestRouter(h)
router.POST("/datasource", h.CreateDataSource)
router.PUT("/datasource/:id", h.UpdateDataSource)

View File

@ -83,7 +83,7 @@ func TestDataSource_GetSyncLogs_ValidLimitWithinBounds(t *testing.T) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
h := NewDataSourceHandler(dsSvc, kbSvc, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=50&offset=25", nil)
@ -116,7 +116,7 @@ func TestDataSource_GetSyncLogs_LimitExceedingMaximum(t *testing.T) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
h := NewDataSourceHandler(dsSvc, kbSvc, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=999", nil)
@ -156,7 +156,7 @@ func TestDataSource_GetSyncLogs_MissingLimitDefaultsCorrectly(t *testing.T) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
h := NewDataSourceHandler(dsSvc, kbSvc, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs", nil)
@ -189,7 +189,7 @@ func TestDataSource_GetSyncLogs_NonNumericLimitRejected(t *testing.T) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
h := NewDataSourceHandler(dsSvc, kbSvc, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=abc", nil)
@ -216,7 +216,7 @@ func TestDataSource_GetSyncLogs_ZeroLimitRejected(t *testing.T) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
h := NewDataSourceHandler(dsSvc, kbSvc, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=0", nil)
@ -243,7 +243,7 @@ func TestDataSource_GetSyncLogs_NegativeLimitRejected(t *testing.T) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
h := NewDataSourceHandler(dsSvc, kbSvc, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=-5", nil)

View File

@ -9,6 +9,7 @@ import (
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
@ -34,6 +35,7 @@ var invalidIMPlatformError = func() string {
// IMHandler handles IM platform callback requests and channel CRUD.
type IMHandler struct {
pluginGated
imService *im.Service
}
@ -44,6 +46,57 @@ func NewIMHandler(imService *im.Service) *IMHandler {
}
}
// GetIMChannel godoc
// @Summary 获取 IM 渠道
// @Description 返回单个渠道供编辑:凭证中的密钥字段以 *** 代替
// @Tags IM
// @Produce json
// @Param id path string true "渠道 ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id} [get]
func (h *IMHandler) GetIMChannel(c *gin.Context) {
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
channel, err := h.imService.GetChannelByIDAndTenant(c.Param("id"), tenantID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
}
creds, err := im.RedactCredentials(channel.Platform, channel.Credentials)
if err != nil {
creds = map[string]any{}
}
c.JSON(http.StatusOK, gin.H{"data": struct {
*im.IMChannel
Credentials map[string]any `json:"credentials"`
}{channel, creds}})
}
// ListIMPlatforms godoc
// @Summary 列出 IM 平台
// @Description 返回已注册的 IM 平台:支持的接入模式、控制台链接和凭证表单 Schema
// @Tags IM
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/platforms [get]
func (h *IMHandler) ListIMPlatforms(c *gin.Context) {
enabled := h.pluginFilter(c)
platforms := make([]im.PlatformInfo, 0)
for _, p := range h.imService.PlatformInfos() {
if enabled(manifest.PointIMChannels, p.ID) {
platforms = append(platforms, p)
}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": platforms})
}
// ── Channel CRUD handlers ──
// CreateIMChannel creates a new IM channel for an agent.
@ -76,6 +129,10 @@ func (h *IMHandler) CreateIMChannel(c *gin.Context) {
return
}
if !h.pluginFilter(c)(manifest.PointIMChannels, req.Platform) {
c.JSON(http.StatusBadRequest, gin.H{"error": disabledIntegrationError})
return
}
if !validIMPlatforms[req.Platform] {
c.JSON(http.StatusBadRequest, gin.H{"error": invalidIMPlatformError})
return
@ -265,7 +322,15 @@ func (h *IMHandler) UpdateIMChannel(c *gin.Context) {
}
}
if req.Credentials != nil {
channel.Credentials = req.Credentials
// The editor loads credentials redacted (GetIMChannel), so merge
// rather than replace: omitted keys and unchanged secrets keep their
// stored values.
merged, err := im.MergeCredentials(channel.Platform, channel.Credentials, req.Credentials)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid credentials"})
return
}
channel.Credentials = merged
}
if req.Enabled != nil {
channel.Enabled = *req.Enabled

View File

@ -16,6 +16,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
@ -25,6 +26,7 @@ import (
// ModelHandler handles HTTP requests for model-related operations
// It implements the necessary methods to create, retrieve, update, and delete models
type ModelHandler struct {
pluginGated
service interfaces.ModelService
}
@ -98,6 +100,10 @@ func (h *ModelHandler) CreateModel(c *gin.Context) {
_ = c.Error(errors.NewBadRequestError(err.Error()))
return
}
if p := req.Parameters.Provider; p != "" && !h.pluginFilter(c)(manifest.PointModelVendors, p) {
_ = c.Error(errors.NewBadRequestError(disabledIntegrationError))
return
}
model := &types.Model{
TenantID: tenantID,

View File

@ -13,6 +13,8 @@ import (
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/internal/models/providers"
modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
@ -37,6 +39,9 @@ type ModelProviderDTO struct {
DefaultURLs map[string]string `json:"defaultUrls"`
ModelTypes []string `json:"modelTypes"`
ExtraFields []providers.ExtraField `json:"extraFields,omitempty"`
// ConfigSchema describes ExtraFields as a config schema (the values of
// extra_config). It carries the same fields; the editor moves to it.
ConfigSchema *configschema.Schema `json:"configSchema,omitempty"`
// CredentialLabels rename the primary credential input for the model
// types that do not take a plain API key (signed rerank APIs).
CredentialLabels []providers.CredentialLabel `json:"credentialLabels,omitempty"`
@ -124,6 +129,9 @@ func providerDTO(v *modelruntime.Provider, modelType types.ModelType, includeMod
CredentialLabels: v.CredentialLabels,
Order: v.Order,
}
if len(v.ExtraFields) > 0 {
dto.ConfigSchema = providers.ExtraFieldsSchema(v.ExtraFields)
}
// Vendor-level thinking summary: resolve an unknown model so only the
// vendor defaults contribute.
if resolved, err := v.Resolve(
@ -219,7 +227,11 @@ func (h *ModelHandler) ListModelProviders(c *gin.Context) {
// themselves (dto.NewModelResponse).
includeURLs := dto.CanViewIntegrationSecrets(ctx)
result := make([]ModelProviderDTO, 0, len(vendors))
enabled := h.pluginFilter(c)
for _, v := range vendors {
if !enabled(manifest.PointModelVendors, v.ID) {
continue
}
p := providerDTO(v, backendType, true)
if !includeURLs {
p.DefaultURLs = nil

View File

@ -0,0 +1,218 @@
package handler
import (
stderrors "errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/plugin/driver"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/plugin/registry"
"github.com/Tencent/WeKnora/internal/plugin/tenancy"
"github.com/Tencent/WeKnora/internal/types"
)
// PluginHandler serves the read-only plugin catalog: every plugin this
// process knows about and what each contributes. Builtins are listed like
// any other plugin.
type PluginHandler struct {
registry *registry.Registry
tenancy *tenancy.Service
drivers *driver.Set
}
// NewPluginHandler creates a PluginHandler. Without a tenancy service every
// plugin reads as enabled; without drivers no instance status is reported.
func NewPluginHandler(registry *registry.Registry, tenancy *tenancy.Service, drivers *driver.Set) *PluginHandler {
return &PluginHandler{registry: registry, tenancy: tenancy, drivers: drivers}
}
// PluginDetailDTO is one plugin with where and how its code runs.
type PluginDetailDTO struct {
tenancy.TenantPlugin
Instances []driver.InstanceStatus `json:"instances"`
// InstanceError explains an empty Instances (no driver, lookup failed).
InstanceError string `json:"instanceError,omitempty"`
}
// tenantPlugins returns every plugin with the caller tenant's switch.
func (h *PluginHandler) tenantPlugins(c *gin.Context) ([]tenancy.TenantPlugin, error) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if h.tenancy == nil || tenantID == 0 {
plugins := h.registry.Plugins()
out := make([]tenancy.TenantPlugin, 0, len(plugins))
for _, m := range plugins {
out = append(out, tenancy.TenantPlugin{Manifest: m, Enabled: true})
}
return out, nil
}
return h.tenancy.List(c.Request.Context(), tenantID)
}
// PluginContributionDTO is one contribution with the plugin providing it.
type PluginContributionDTO struct {
manifest.Contribution
PluginID string `json:"pluginId"`
QualifiedID string `json:"qualifiedId"`
// Enabled reports whether the caller's tenant has the plugin enabled.
Enabled bool `json:"enabled"`
}
// PluginContributionsDTO groups contributions by extension point.
type PluginContributionsDTO struct {
Points []manifest.PointInfo `json:"points"`
Contributions map[manifest.Point][]PluginContributionDTO `json:"contributions"`
}
// ListPlugins godoc
// @Summary 列出插件
// @Description 列出当前进程已知的全部插件(含内置插件)、其贡献,以及当前空间是否启用
// @Tags Plugin
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /plugins [get]
func (h *PluginHandler) ListPlugins(c *gin.Context) {
plugins, err := h.tenantPlugins(c)
if err != nil {
_ = c.Error(errors.NewInternalServerError("failed to load plugin settings"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": plugins})
}
// GetPlugin godoc
// @Summary 获取插件详情
// @Tags Plugin
// @Produce json
// @Param id path string true "插件 ID,如 weknora.feishu"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /plugins/{id} [get]
func (h *PluginHandler) GetPlugin(c *gin.Context) {
plugins, err := h.tenantPlugins(c)
if err != nil {
_ = c.Error(errors.NewInternalServerError("failed to load plugin settings"))
return
}
for _, p := range plugins {
if p.Manifest.ID == c.Param("id") {
c.JSON(http.StatusOK, gin.H{"success": true, "data": h.detail(c, p)})
return
}
}
_ = c.Error(errors.NewNotFoundError("plugin not found"))
}
func (h *PluginHandler) detail(c *gin.Context, p tenancy.TenantPlugin) PluginDetailDTO {
out := PluginDetailDTO{TenantPlugin: p, Instances: []driver.InstanceStatus{}}
if h.drivers == nil {
return out
}
d, err := h.drivers.For(p.Manifest.Runtime.Type)
if err == nil {
out.Instances, err = d.Status(c.Request.Context(), p.Manifest.ID)
}
if err != nil {
out.InstanceError = err.Error()
out.Instances = []driver.InstanceStatus{}
}
return out
}
// SetPluginEnabledRequest turns a plugin on or off for the workspace.
type SetPluginEnabledRequest struct {
Enabled *bool `json:"enabled" binding:"required"`
}
// SetPluginEnabled godoc
// @Summary 启用或停用插件
// @Description 为当前空间启用或停用插件;停用后其贡献不再出现在类型列表中、不能新建实例,已有实例不受影响。必需插件不能停用
// @Tags Plugin
// @Accept json
// @Produce json
// @Param id path string true "插件 ID"
// @Param request body SetPluginEnabledRequest true "开关"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /plugins/{id}/enabled [put]
func (h *PluginHandler) SetPluginEnabled(c *gin.Context) {
var req SetPluginEnabledRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("enabled is required"))
return
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if h.tenancy == nil || tenantID == 0 {
_ = c.Error(errors.NewBadRequestError("workspace context missing"))
return
}
userID, _ := c.Request.Context().Value(types.UserIDContextKey).(string)
err := h.tenancy.SetEnabled(c.Request.Context(), tenantID, c.Param("id"), *req.Enabled, userID)
switch {
case stderrors.Is(err, tenancy.ErrUnknownPlugin):
_ = c.Error(errors.NewNotFoundError("plugin not found"))
return
case stderrors.Is(err, tenancy.ErrRequiredPlugin):
_ = c.Error(errors.NewBadRequestError(err.Error()))
return
case err != nil:
_ = c.Error(errors.NewInternalServerError("failed to save plugin setting"))
return
}
h.GetPlugin(c)
}
// ListContributions godoc
// @Summary 按扩展点列出贡献
// @Description 返回各扩展点下的全部贡献;可用 point 参数只取一个扩展点
// @Tags Plugin
// @Produce json
// @Param point query string false "扩展点,如 connectors"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /plugins/contributions [get]
func (h *PluginHandler) ListContributions(c *gin.Context) {
points := manifest.Points()
if p := c.Query("point"); p != "" {
info, ok := manifest.LookupPoint(manifest.Point(p))
if !ok {
_ = c.Error(errors.NewBadRequestError("unknown extension point"))
return
}
points = []manifest.PointInfo{info}
}
out := PluginContributionsDTO{
Points: points,
Contributions: make(map[manifest.Point][]PluginContributionDTO, len(points)),
}
enabled := map[string]bool{}
plugins, err := h.tenantPlugins(c)
if err != nil {
_ = c.Error(errors.NewInternalServerError("failed to load plugin settings"))
return
}
for _, p := range plugins {
enabled[p.Manifest.ID] = p.Enabled
}
for _, info := range points {
entries := h.registry.Contributions(info.Point)
list := make([]PluginContributionDTO, 0, len(entries))
for _, e := range entries {
list = append(list, PluginContributionDTO{
Contribution: e.Contribution,
PluginID: e.PluginID,
QualifiedID: e.QualifiedID,
Enabled: enabled[e.PluginID],
})
}
out.Contributions[info.Point] = list
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
}

View File

@ -0,0 +1,39 @@
package handler
import (
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// pluginGated gives an integration handler the tenant's plugin switches.
// It is set after construction (SetPluginGate) so the many handler tests that
// build handlers directly need no gate; without one everything is enabled.
type pluginGated struct {
gate interfaces.PluginGate
}
// SetPluginGate installs the tenant plugin switches.
func (g *pluginGated) SetPluginGate(gate interfaces.PluginGate) { g.gate = gate }
// pluginFilter returns whether a contribution is enabled for the caller's
// tenant. A disabled plugin's contributions are left out of type listings
// and cannot back new instances; existing instances keep working.
func (g *pluginGated) pluginFilter(c *gin.Context) func(manifest.Point, string) bool {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
if v, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64); ok {
tenantID = v
}
}
if g.gate == nil || tenantID == 0 {
return func(manifest.Point, string) bool { return true }
}
return g.gate.EnabledFilter(c.Request.Context(), tenantID)
}
// disabledIntegrationError is the message for creating an instance of a
// contribution whose plugin the workspace has disabled.
const disabledIntegrationError = "this integration is disabled for the workspace; enable its plugin first"

View File

@ -0,0 +1,194 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/plugin/driver"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/plugin/registry"
"github.com/Tencent/WeKnora/internal/plugin/tenancy"
"github.com/Tencent/WeKnora/internal/types"
)
func newPluginHandlerTestRouter(t *testing.T) *gin.Engine {
t.Helper()
reg := registry.New()
err := reg.Register(&manifest.Manifest{
SchemaVersion: manifest.SchemaVersion,
ID: "weknora.feishu",
Version: "1.0.0",
Name: manifest.Text("Feishu", map[string]string{"zh-CN": "飞书"}),
Publisher: manifest.Publisher{ID: manifest.BuiltinPublisher},
Builtin: true,
Runtime: manifest.Runtime{Type: manifest.RuntimeBuiltin},
Contributes: manifest.Contributions{
manifest.PointConnectors: {{ID: "feishu", Name: manifest.Text("Feishu", nil), Aliases: []string{"feishu"}}},
manifest.PointIMChannels: {{ID: "feishu", Name: manifest.Text("Feishu", nil), Aliases: []string{"feishu"}}},
},
})
if err != nil {
t.Fatal(err)
}
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := NewPluginHandler(reg, nil, driver.NewSet(driver.NewBuiltin(reg.Plugin)))
r.GET("/plugins", h.ListPlugins)
r.GET("/plugins/contributions", h.ListContributions)
r.GET("/plugins/:id", h.GetPlugin)
return r
}
func getJSON(t *testing.T, r *gin.Engine, path string, out any) int {
t.Helper()
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
if out != nil && w.Code == http.StatusOK {
if err := json.Unmarshal(w.Body.Bytes(), out); err != nil {
t.Fatalf("decode %s: %v (%s)", path, err, w.Body.String())
}
}
return w.Code
}
func TestPluginHandlerListsPluginsAndContributions(t *testing.T) {
r := newPluginHandlerTestRouter(t)
var list struct {
Data []struct {
Manifest manifest.Manifest `json:"manifest"`
Enabled bool `json:"enabled"`
} `json:"data"`
}
if code := getJSON(t, r, "/plugins", &list); code != http.StatusOK {
t.Fatalf("list status = %d", code)
}
if len(list.Data) != 1 || list.Data[0].Manifest.Name.Resolve("zh-CN") != "飞书" || !list.Data[0].Enabled {
t.Fatalf("unexpected plugins: %+v", list.Data)
}
var contribs struct {
Data struct {
Points []manifest.PointInfo `json:"points"`
Contributions map[string][]map[string]any `json:"contributions"`
} `json:"data"`
}
if code := getJSON(t, r, "/plugins/contributions?point=connectors", &contribs); code != http.StatusOK {
t.Fatalf("contributions status = %d", code)
}
if len(contribs.Data.Points) != 1 || len(contribs.Data.Contributions) != 1 {
t.Fatalf("point filter not applied: %+v", contribs.Data)
}
got := contribs.Data.Contributions["connectors"]
if len(got) != 1 || got[0]["qualifiedId"] != "weknora.feishu/feishu" || got[0]["pluginId"] != "weknora.feishu" {
t.Fatalf("unexpected connectors: %+v", got)
}
}
func TestPluginHandlerErrors(t *testing.T) {
r := newPluginHandlerTestRouter(t)
if code := getJSON(t, r, "/plugins/acme.missing", nil); code != http.StatusNotFound {
t.Fatalf("missing plugin status = %d, want 404", code)
}
if code := getJSON(t, r, "/plugins/contributions?point=widgets", nil); code != http.StatusBadRequest {
t.Fatalf("unknown point status = %d, want 400", code)
}
var detail struct {
Data struct {
Enabled bool `json:"enabled"`
Instances []driver.InstanceStatus `json:"instances"`
} `json:"data"`
}
if code := getJSON(t, r, "/plugins/weknora.feishu", &detail); code != http.StatusOK {
t.Fatalf("get plugin status = %d", code)
}
if !detail.Data.Enabled || len(detail.Data.Instances) != 1 || detail.Data.Instances[0].State != driver.StateReady {
t.Fatalf("builtin plugin detail = %+v", detail.Data)
}
}
type memPluginSettings struct {
rows map[string]types.PluginTenantSetting
}
func (m *memPluginSettings) List(context.Context, uint64) ([]types.PluginTenantSetting, error) {
out := make([]types.PluginTenantSetting, 0, len(m.rows))
for _, r := range m.rows {
out = append(out, r)
}
return out, nil
}
func (m *memPluginSettings) Upsert(_ context.Context, s *types.PluginTenantSetting) error {
m.rows[s.PluginID] = *s
return nil
}
func TestPluginHandlerTogglesPluginsPerTenant(t *testing.T) {
reg := registry.New()
builtinPlugin := func(id string, required bool, point manifest.Point, localID string) *manifest.Manifest {
return &manifest.Manifest{
SchemaVersion: manifest.SchemaVersion, ID: id, Version: "1.0.0", Name: manifest.Text(id, nil),
Publisher: manifest.Publisher{ID: manifest.BuiltinPublisher}, Builtin: true, Required: required,
Runtime: manifest.Runtime{Type: manifest.RuntimeBuiltin},
Contributes: manifest.Contributions{
point: {{ID: localID, Name: manifest.Text(localID, nil)}},
},
}
}
for _, m := range []*manifest.Manifest{
builtinPlugin("weknora.notion", false, manifest.PointConnectors, "notion"),
builtinPlugin("weknora.agent-tools", true, manifest.PointTools, "thinking"),
} {
if err := reg.Register(m); err != nil {
t.Fatal(err)
}
}
settings := &memPluginSettings{rows: map[string]types.PluginTenantSetting{}}
h := NewPluginHandler(reg, tenancy.NewService(reg, settings), nil)
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) { c.Set(types.TenantIDContextKey.String(), uint64(7)) })
r.PUT("/plugins/:id/enabled", h.SetPluginEnabled)
r.GET("/plugins/contributions", h.ListContributions)
put := func(id, body string) int {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/plugins/"+id+"/enabled", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w.Code
}
if code := put("weknora.notion", `{"enabled":false}`); code != http.StatusOK {
t.Fatalf("disable status = %d", code)
}
if code := put("weknora.agent-tools", `{"enabled":false}`); code != http.StatusBadRequest {
t.Fatalf("disabling a required plugin = %d, want 400", code)
}
if code := put("acme.missing", `{"enabled":false}`); code != http.StatusNotFound {
t.Fatalf("unknown plugin = %d, want 404", code)
}
if code := put("weknora.notion", `{}`); code != http.StatusBadRequest {
t.Fatalf("missing enabled = %d, want 400", code)
}
var contribs struct {
Data struct {
Contributions map[string][]map[string]any `json:"contributions"`
} `json:"data"`
}
if code := getJSON(t, r, "/plugins/contributions?point=connectors", &contribs); code != http.StatusOK {
t.Fatalf("contributions status = %d", code)
}
if got := contribs.Data.Contributions["connectors"]; len(got) != 1 || got[0]["enabled"] != false {
t.Fatalf("disabled plugin's contribution should read disabled: %v", got)
}
}

View File

@ -9,6 +9,7 @@ import (
"github.com/Tencent/WeKnora/internal/handler/dto"
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
@ -17,6 +18,7 @@ import (
// WebSearchProviderHandler handles HTTP requests for web search provider CRUD
type WebSearchProviderHandler struct {
pluginGated
repo interfaces.WebSearchProviderRepository
service interfaces.WebSearchProviderService
registry *infra_web_search.Registry
@ -91,6 +93,11 @@ func (h *WebSearchProviderHandler) CreateProvider(c *gin.Context) {
return
}
if !h.pluginFilter(c)(manifest.PointWebSearch, string(req.Provider)) {
_ = c.Error(errors.NewBadRequestError(disabledIntegrationError))
return
}
logger.Infof(ctx, "Creating web search provider: tenant=%d, name=%s, type=%s",
tenantID, secutils.SanitizeForLog(req.Name), secutils.SanitizeForLog(string(req.Provider)))
@ -320,9 +327,17 @@ func (h *WebSearchProviderHandler) DeleteProvider(c *gin.Context) {
// @Security ApiKeyAuth
// @Router /web-search-providers/types [get]
func (h *WebSearchProviderHandler) ListProviderTypes(c *gin.Context) {
enabled := h.pluginFilter(c)
all := types.GetWebSearchProviderTypes()
out := make([]types.WebSearchProviderTypeInfo, 0, len(all))
for _, info := range all {
if enabled(manifest.PointWebSearch, info.ID) {
out = append(out, info)
}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": types.GetWebSearchProviderTypes(),
"data": out,
})
}

View File

@ -3,6 +3,8 @@ package im
import (
"encoding/json"
"strings"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
)
// ParseCredentials parses the JSONB credentials field into a map.
@ -47,3 +49,62 @@ func GetBool(creds map[string]any, key string) bool {
return false
}
}
// secretKeys returns the credential keys a platform's schema marks secret.
func secretKeys(platform string) map[string]bool {
out := map[string]bool{}
if s := LookupPlatformInfo(platform).ConfigSchema; s != nil {
for key, prop := range s.Properties {
if prop.Secret {
out[key] = true
}
}
}
return out
}
// RedactCredentials returns a channel's credentials for the editor: plain
// fields as stored, set secrets replaced by configschema.RedactedPlaceholder.
func RedactCredentials(platform string, raw []byte) (map[string]any, error) {
creds, err := ParseCredentials(raw)
if err != nil {
return nil, err
}
secrets := secretKeys(platform)
for key, v := range creds {
if s, ok := v.(string); ok && s != "" && secrets[key] {
creds[key] = configschema.RedactedPlaceholder
}
}
return creds, nil
}
// MergeCredentials applies credentials sent by the editor to the stored ones.
// Keys the update leaves out keep their stored value, and so does a secret
// sent empty or as the redaction placeholder, since the editor never saw it.
// A plain field sent empty is cleared. An empty update changes nothing, which
// keeps an edit that never loaded the credentials from wiping them.
func MergeCredentials(platform string, stored, incoming []byte) ([]byte, error) {
update, err := ParseCredentials(incoming)
if err != nil {
return nil, err
}
if len(update) == 0 {
return stored, nil
}
out, err := ParseCredentials(stored)
if err != nil {
// Unreadable stored credentials cannot be merged into; take the update.
out = map[string]any{}
}
secrets := secretKeys(platform)
for key, v := range update {
if secrets[key] {
if s, ok := v.(string); v == nil || (ok && (s == "" || s == configschema.RedactedPlaceholder)) {
continue
}
}
out[key] = v
}
return json.Marshal(out)
}

View File

@ -0,0 +1,64 @@
package im
import (
"encoding/json"
"testing"
)
func mustJSON(t *testing.T, v any) []byte {
t.Helper()
b, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
return b
}
func TestRedactCredentialsHidesOnlySecrets(t *testing.T) {
stored := mustJSON(t, map[string]any{"site_url": "https://mm", "bot_token": "tok", "post_to_main": true})
got, err := RedactCredentials("mattermost", stored)
if err != nil {
t.Fatal(err)
}
if got["site_url"] != "https://mm" || got["bot_token"] != "***" || got["post_to_main"] != true {
t.Fatalf("redacted = %v", got)
}
}
func TestMergeCredentials(t *testing.T) {
stored := mustJSON(t, map[string]any{
"site_url": "https://mm", "bot_token": "tok", "outgoing_token": "out", "bot_user_id": "u1",
})
merge := func(update map[string]any) map[string]any {
t.Helper()
out, err := MergeCredentials("mattermost", stored, mustJSON(t, update))
if err != nil {
t.Fatal(err)
}
var m map[string]any
if err := json.Unmarshal(out, &m); err != nil {
t.Fatal(err)
}
return m
}
// An edit that never loaded the credentials must not wipe them.
if got := merge(map[string]any{}); got["bot_token"] != "tok" || got["site_url"] != "https://mm" {
t.Fatalf("empty update changed credentials: %v", got)
}
// The redacted form comes back with one plain field changed.
got := merge(map[string]any{
"site_url": "https://new", "bot_token": "***", "outgoing_token": "", "bot_user_id": "",
})
want := map[string]any{"site_url": "https://new", "bot_token": "tok", "outgoing_token": "out", "bot_user_id": ""}
for k, v := range want {
if got[k] != v {
t.Errorf("%s = %v, want %v (all: %v)", k, got[k], v, got)
}
}
// A new secret replaces the stored one.
got = merge(map[string]any{"bot_token": "new-tok"})
if got["bot_token"] != "new-tok" || got["outgoing_token"] != "out" {
t.Fatalf("secret replacement = %v", got)
}
}

View File

@ -0,0 +1,342 @@
package im
import (
"sort"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
)
// Channel modes. The first mode a platform lists is its default.
const (
ModeWebSocket = "websocket"
ModeWebhook = "webhook"
ModeLongPoll = "longpoll"
)
// PlatformInfo describes one IM platform for the channel editor: how it is
// named, which connection modes it supports and what credentials it takes.
type PlatformInfo struct {
ID string `json:"id"`
// Name is the default (English) name; Names holds localized variants.
Name string `json:"name"`
Names map[string]string `json:"names,omitempty"`
// Order sorts platforms in the UI (lower first).
Order int `json:"order"`
// Modes lists the supported connection modes, default first.
Modes []string `json:"modes"`
// ModeLabels renames a mode for this platform (DingTalk calls its
// WebSocket connection "Stream").
ModeLabels map[string]string `json:"mode_labels,omitempty"`
// ModeHintKey is the frontend locale key of the hint under the mode
// choice; empty uses the generic hint.
ModeHintKey string `json:"mode_hint_key,omitempty"`
// SupportsThread reports whether replies can stay in a thread, which
// enables the per-thread session mode.
SupportsThread bool `json:"supports_thread"`
// Links point at the platform's console and docs.
Links []PlatformLink `json:"links,omitempty"`
// ConfigSchema describes IMChannel.Credentials. Fields that apply to one
// connection mode carry x-visible-if on "$mode", read from the channel
// rather than from the credentials.
ConfigSchema *configschema.Schema `json:"config_schema,omitempty"`
}
// PlatformLink is a link shown above the credential form.
type PlatformLink struct {
URL string `json:"url"`
Title string `json:"title"`
// TitleKey is the frontend locale key of the title.
TitleKey string `json:"title_key,omitempty"`
}
// LookupPlatformInfo returns the metadata of a platform. A platform without
// an entry gets its ID as name and WebSocket as its only mode, so a newly
// registered adapter still shows up.
func LookupPlatformInfo(id string) PlatformInfo {
if build, ok := platformInfos[id]; ok {
return build()
}
return PlatformInfo{ID: id, Name: id, Order: 1000, Modes: []string{ModeWebSocket}}
}
// KnownPlatformInfos returns the metadata of every platform this build
// describes, whether or not its adapter is registered, sorted by ID.
func KnownPlatformInfos() []PlatformInfo {
out := make([]PlatformInfo, 0, len(platformInfos))
for _, build := range platformInfos {
out = append(out, build())
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// Platforms returns the platforms that have a registered adapter factory,
// sorted by ID.
func (s *Service) Platforms() []string {
s.mu.RLock()
defer s.mu.RUnlock()
out := make([]string, 0, len(s.adapterFactories))
for p := range s.adapterFactories {
out = append(out, p)
}
sort.Strings(out)
return out
}
// PlatformInfos returns the metadata of every registered platform in display
// order.
func (s *Service) PlatformInfos() []PlatformInfo {
ids := s.Platforms()
out := make([]PlatformInfo, 0, len(ids))
for _, id := range ids {
out = append(out, LookupPlatformInfo(id))
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Order < out[j].Order })
return out
}
// platformInfos builds each platform's metadata. Names follow the frontend's
// agentEditor.im.* labels; field hints reuse its locale keys.
var platformInfos = map[string]func() PlatformInfo{
"wecom": func() PlatformInfo {
wsEndpoint := text("WebSocket Endpoint", "wss://openws.work.weixin.qq.com", 3)
describe(wsEndpoint, "Optional. Custom WebSocket address for private WeCom deployments.",
"agentEditor.im.wecomWSEndpointHint")
apiBase := text("API Base URL", "https://qyapi.weixin.qq.com", 16)
describe(apiBase, "Optional. Custom API base URL for private WeCom deployments.",
"agentEditor.im.wecomAPIBaseURLHint")
agentID := &configschema.Schema{Type: configschema.TypeInteger, Title: "Corp Agent ID", Order: 15}
return PlatformInfo{
ID: "wecom", Name: "WeCom", Names: map[string]string{"zh-CN": "企业微信"}, Order: 10,
Modes: []string{ModeWebSocket, ModeWebhook},
Links: []PlatformLink{console("https://work.weixin.qq.com/", "WeCom Admin Console", "wecomConsole")},
ConfigSchema: configschema.Object().
Set("bot_id", onlyIn(ModeWebSocket, text("Bot ID", "Bot ID", 1)), false).
Set("bot_secret", onlyIn(ModeWebSocket, secret("Bot Secret", "Bot Secret", 2)), false).
Set("ws_endpoint", onlyIn(ModeWebSocket, wsEndpoint), false).
Set("corp_id", onlyIn(ModeWebhook, text("Corp ID", "Corp ID", 11)), false).
Set("agent_secret", onlyIn(ModeWebhook, secret("Agent Secret", "Agent Secret", 12)), false).
Set("token", onlyIn(ModeWebhook, text("Token", "Token", 13)), false).
Set("encoding_aes_key", onlyIn(ModeWebhook, text("EncodingAESKey", "EncodingAESKey", 14)), false).
Set("corp_agent_id", onlyIn(ModeWebhook, agentID), false).
Set("api_base_url", onlyIn(ModeWebhook, apiBase), false),
}
},
"feishu": func() PlatformInfo {
return feishuPlatform("feishu", "Feishu", "飞书", 20,
console("https://open.feishu.cn/", "Feishu Open Platform", "feishuConsole"))
},
// Lark is Feishu's international cloud: same credentials, separate console.
"lark": func() PlatformInfo {
return feishuPlatform("lark", "Lark", "Lark(飞书国际版)", 30,
console("https://open.larksuite.com/", "Lark Open Platform", "larkConsole"))
},
"dingtalk": func() PlatformInfo {
card := text("Card Template ID (optional)", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.schema", 3)
card.I18nKeys = map[string]string{"title": "agentEditor.im.dingtalkCardTemplateId"}
describe(card, "Create an AI Card template to stream replies with a typewriter effect.",
"agentEditor.im.dingtalkCardTemplateIdHint")
return PlatformInfo{
ID: "dingtalk", Name: "DingTalk", Names: map[string]string{"zh-CN": "钉钉"}, Order: 60,
Modes: []string{ModeWebSocket},
ModeLabels: map[string]string{ModeWebSocket: "Stream"},
Links: []PlatformLink{
console("https://open.dingtalk.com/", "DingTalk Open Platform", "dingtalkConsole"),
},
ConfigSchema: configschema.Object().
Set("client_id", text("Client ID (AppKey)", "Client ID / AppKey", 1), false).
Set("client_secret", secret("Client Secret (AppSecret)", "Client Secret / AppSecret", 2), false).
Set("card_template_id", card, false),
}
},
// WeChat binds by scanning a QR code; the editor runs that flow itself
// and there is nothing to type. The bound fields are declared hidden so
// the token is still redacted and kept like any other secret.
"wechat": func() PlatformInfo {
hidden := func(title string, secret bool) *configschema.Schema {
return &configschema.Schema{Type: configschema.TypeString, Title: title, Widget: "hidden", Secret: secret}
}
return PlatformInfo{
ID: "wechat", Name: "WeChat", Names: map[string]string{"zh-CN": "微信"}, Order: 80,
Modes: []string{ModeLongPoll},
ConfigSchema: configschema.Object().
Set("bot_token", hidden("Bot Token", true), false).
Set("ilink_bot_id", hidden("iLink Bot ID", false), false).
Set("ilink_user_id", hidden("iLink User ID", false), false),
}
},
"qqbot": func() PlatformInfo {
apiBase := text("API Base URL", "https://api.sgroup.qq.com", 3)
describe(apiBase, "Optional. Leave empty to use the default production API endpoint.",
"agentEditor.im.qqbotAPIBaseURLHint")
gateway := text("Gateway URL", "wss://api.sgroup.qq.com/websocket/", 4)
describe(gateway, "Optional. Leave empty to fetch the common WebSocket gateway automatically.",
"agentEditor.im.qqbotGatewayURLHint")
return PlatformInfo{
ID: "qqbot", Name: "QQBot", Order: 90,
Modes: []string{ModeWebSocket},
Links: []PlatformLink{console("https://q.qq.com/", "QQ Open Platform", "qqbotConsole")},
ConfigSchema: configschema.Object().
Set("app_id", text("App ID", "QQBot App ID", 1), false).
Set("client_secret", secret("App Secret", "QQBot App Secret", 2), false).
Set("api_base_url", apiBase, false).
Set("gateway_url", gateway, false),
}
},
"yunzhijia": yunzhijiaPlatform,
"slack": func() PlatformInfo {
return PlatformInfo{
ID: "slack", Name: "Slack", Order: 40,
Modes: []string{ModeWebSocket, ModeWebhook},
SupportsThread: true,
Links: []PlatformLink{console("https://api.slack.com/apps", "Slack API Console", "slackConsole")},
ConfigSchema: configschema.Object().
Set("app_token", onlyIn(ModeWebSocket, secret("App Token", "xapp-...", 1)), false).
Set("bot_token", secret("Bot Token", "xoxb-...", 2), false).
Set("signing_secret", onlyIn(ModeWebhook, secret("Signing Secret", "Signing Secret", 3)), false),
}
},
"telegram": func() PlatformInfo {
return PlatformInfo{
ID: "telegram", Name: "Telegram", Order: 50,
Modes: []string{ModeWebSocket, ModeWebhook},
SupportsThread: true,
Links: []PlatformLink{console("https://t.me/BotFather", "Telegram BotFather", "telegramConsole")},
ConfigSchema: configschema.Object().
Set("bot_token", secret("Bot Token", "123456789:AABBccdd...", 1), false).
Set("secret_token", onlyIn(ModeWebhook, secret("Secret Token", "Secret Token (optional)", 2)), false),
}
},
"mattermost": func() PlatformInfo {
postToMain := &configschema.Schema{
Type: configschema.TypeBoolean,
Title: "Post replies in channel timeline",
Default: false,
Order: 5,
}
postToMain.I18nKeys = map[string]string{"title": "agentEditor.im.mattermostPostToMain"}
describe(postToMain, "When on, bot replies are new top-level posts instead of thread replies.",
"agentEditor.im.mattermostPostToMainHint")
return PlatformInfo{
ID: "mattermost", Name: "Mattermost", Order: 70,
Modes: []string{ModeWebhook},
ModeHintKey: "agentEditor.im.mattermostModeHint",
SupportsThread: true,
Links: []PlatformLink{console(
"https://developers.mattermost.com/integrate/webhooks/outgoing/",
"Mattermost integrations", "mattermostConsole",
)},
ConfigSchema: configschema.Object().
Set("site_url", text("Site URL", "https://mattermost.example.com", 1), false).
Set("bot_token", secret("Bot Token", "Bot Token", 2), false).
Set("outgoing_token", secret("Outgoing Webhook Token", "Token from Outgoing Webhook", 3), false).
Set("bot_user_id", text("Bot User ID", "Optional — filter bot self-messages", 4), false).
Set("post_to_main", postToMain, false),
}
},
}
func feishuPlatform(id, name, zhName string, order int, link PlatformLink) PlatformInfo {
apiBase := text("Base URL", "https://open.feishu.cn", 3)
describe(apiBase, "Optional. Enter a reverse proxy URL if the server reaches Feishu through one.",
"agentEditor.im.feishuAPIBaseURLHint")
return PlatformInfo{
ID: id, Name: name, Names: map[string]string{"zh-CN": zhName}, Order: order,
Modes: []string{ModeWebSocket, ModeWebhook},
SupportsThread: true,
Links: []PlatformLink{link},
ConfigSchema: configschema.Object().
Set("app_id", text("App ID", "App ID", 1), false).
Set("app_secret", secret("App Secret", "App Secret", 2), false).
Set("api_base_url", apiBase, false).
Set("verification_token", onlyIn(ModeWebhook, text("Verification Token", "Verification Token", 4)), false).
Set("encrypt_key", onlyIn(ModeWebhook, secret("Encrypt Key", "Encrypt Key", 5)), false),
}
}
func yunzhijiaPlatform() PlatformInfo {
sendURL := text("Send Message URL",
"https://www.yunzhijia.com/gateway/robot/webhook/send?yzjtype=0&yzjtoken=...", 1)
sendURL.I18nKeys = map[string]string{"title": "agentEditor.im.yunzhijiaSendMsgUrl"}
describe(sendURL, "Used for robot replies.", "agentEditor.im.yunzhijiaSendMsgUrlHint")
sign := secret("Signature Secret (optional)", "HmacSHA1 signature secret from Yunzhijia robot settings", 2)
localize(sign, "agentEditor.im.yunzhijiaSecret", "agentEditor.im.yunzhijiaSecretPlaceholder")
describe(sign, "If set, incoming callbacks are verified with an HmacSHA1 signature.",
"agentEditor.im.yunzhijiaSecretHint")
appID := text("App ID (image download)", "Yunzhijia Open Platform App ID", 3)
localize(appID, "agentEditor.im.yunzhijiaAppId", "agentEditor.im.yunzhijiaAppIdPlaceholder")
describe(appID, "Used to obtain appAccessToken and download images users send.",
"agentEditor.im.yunzhijiaAppCredentialHint")
appSecret := secret("App Secret (image download)", "Yunzhijia Open Platform App Secret", 4)
localize(appSecret, "agentEditor.im.yunzhijiaAppSecret", "agentEditor.im.yunzhijiaAppSecretPlaceholder")
minTimeout, maxTimeout := 1.0, 60.0
timeout := &configschema.Schema{
Type: configschema.TypeInteger, Title: "HTTP Timeout (seconds)", Default: 10,
Minimum: &minTimeout, Maximum: &maxTimeout, Placeholder: "10", Order: 5,
I18nKeys: map[string]string{"title": "agentEditor.im.yunzhijiaTimeout"},
}
describe(timeout, "Timeout for sending replies via Send Message URL.", "agentEditor.im.yunzhijiaTimeoutHint")
suffix := text("Allowed Host Suffix", "yunzhijia.com", 6)
suffix.Default = "yunzhijia.com"
suffix.I18nKeys = map[string]string{"title": "agentEditor.im.yunzhijiaAllowedHostSuffix"}
describe(suffix, "Restrict the Send Message URL host to this suffix.",
"agentEditor.im.yunzhijiaAllowedHostSuffixHint")
return PlatformInfo{
ID: "yunzhijia", Name: "Yunzhijia", Names: map[string]string{"zh-CN": "云之家"}, Order: 100,
Modes: []string{ModeWebhook, ModeWebSocket},
ModeHintKey: "agentEditor.im.yunzhijiaModeHint",
SupportsThread: true,
Links: []PlatformLink{
console("https://www.yunzhijia.com/opendocs/docs.html#/guide/im/robot",
"Robot messaging docs", "yunzhijiaRobotDoc"),
console("https://www.yunzhijia.com/developers/", "Developer platform (images)", "yunzhijiaImageDoc"),
},
ConfigSchema: configschema.Object().
Set("send_msg_url", sendURL, true).
Set("secret", sign, false).
Set("app_id", appID, false).
Set("app_secret", appSecret, false).
Set("timeout_seconds", timeout, false).
Set("allowed_webhook_host_suffix", suffix, true),
}
}
func text(title, placeholder string, order int) *configschema.Schema {
return &configschema.Schema{Type: configschema.TypeString, Title: title, Placeholder: placeholder, Order: order}
}
// secret is a password input. IM credentials are returned to admins as
// stored, so the form shows the saved value masked rather than redacted.
func secret(title, placeholder string, order int) *configschema.Schema {
s := text(title, placeholder, order)
s.Secret = true
s.Widget = "password"
return s
}
func onlyIn(mode string, s *configschema.Schema) *configschema.Schema {
s.VisibleIf = map[string]any{"$mode": mode}
return s
}
func describe(s *configschema.Schema, description, key string) {
s.Description = description
if s.I18nKeys == nil {
s.I18nKeys = map[string]string{}
}
s.I18nKeys["description"] = key
}
func localize(s *configschema.Schema, titleKey, placeholderKey string) {
s.I18nKeys = map[string]string{"title": titleKey, "placeholder": placeholderKey}
}
func console(url, title, key string) PlatformLink {
return PlatformLink{URL: url, Title: title, TitleKey: "agentEditor.im." + key}
}

View File

@ -0,0 +1,87 @@
package im
import (
"testing"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
)
// registeredPlatforms are the adapters container.registerIMService wires.
var registeredPlatforms = []string{
"wecom", "feishu", "lark", "slack", "telegram", "dingtalk", "mattermost", "wechat", "qqbot", "yunzhijia",
}
func TestEveryPlatformHasValidMetadata(t *testing.T) {
for _, id := range registeredPlatforms {
info := LookupPlatformInfo(id)
if info.Order >= 1000 {
t.Errorf("%s: no metadata entry", id)
continue
}
if len(info.Modes) == 0 {
t.Errorf("%s: no connection mode", id)
}
if info.ConfigSchema == nil {
t.Errorf("%s: no config schema", id)
continue
}
if err := info.ConfigSchema.Check(); err != nil {
t.Errorf("%s: invalid schema: %v", id, err)
}
// Mode-dependent fields may only name modes the platform supports.
for key, prop := range info.ConfigSchema.Properties {
if mode, ok := prop.VisibleIf["$mode"]; ok && !contains(info.Modes, mode.(string)) {
t.Errorf("%s.%s: visible only in unsupported mode %q", id, key, mode)
}
}
}
}
func TestWeComFieldsFollowTheMode(t *testing.T) {
s := LookupPlatformInfo("wecom").ConfigSchema
visibleIn := func(mode string) map[string]bool {
out := map[string]bool{}
for key, prop := range s.Properties {
if m, ok := prop.VisibleIf["$mode"]; !ok || m == mode {
out[key] = true
}
}
return out
}
ws, hook := visibleIn(ModeWebSocket), visibleIn(ModeWebhook)
if !ws["bot_id"] || ws["corp_id"] || !hook["corp_id"] || hook["bot_secret"] {
t.Fatalf("websocket=%v webhook=%v", ws, hook)
}
}
func TestYunzhijiaRequiresTheSendURL(t *testing.T) {
s := LookupPlatformInfo("yunzhijia").ConfigSchema
errs := configschema.ValidateInContext(s, map[string]any{
"allowed_webhook_host_suffix": "yunzhijia.com", "timeout_seconds": 10.0,
}, map[string]any{"mode": ModeWebhook})
if len(errs) != 1 || errs[0].Path != "send_msg_url" || errs[0].Code != configschema.CodeRequired {
t.Fatalf("want send_msg_url required, got %v", errs)
}
errs = configschema.Validate(s, map[string]any{
"send_msg_url": "https://x", "allowed_webhook_host_suffix": "yunzhijia.com", "timeout_seconds": 99.0,
})
if len(errs) != 1 || errs[0].Code != configschema.CodeMaximum {
t.Fatalf("want timeout maximum error, got %v", errs)
}
}
func TestUnknownPlatformFallsBack(t *testing.T) {
info := LookupPlatformInfo("brand-new")
if info.Name != "brand-new" || len(info.Modes) != 1 {
t.Fatalf("fallback = %+v", info)
}
}
func contains(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}

View File

@ -50,6 +50,13 @@ func RegisterEngine(e EngineRegistration) {
localEngines = append(localEngines, e)
}
// Engines returns the locally registered engines in registration order.
func Engines() []EngineRegistration {
out := make([]EngineRegistration, len(localEngines))
copy(out, localEngines)
return out
}
// lookupEngine returns the locally registered engine with this name.
func lookupEngine(name string) (EngineRegistration, bool) {
for _, engine := range localEngines {

View File

@ -2,6 +2,7 @@ package web_search
import (
"fmt"
"sort"
"sync"
"github.com/Tencent/WeKnora/internal/types"
@ -33,6 +34,18 @@ func (r *Registry) Register(id string, factory ProviderFactory) {
r.factories[id] = factory
}
// Types returns the registered provider type IDs, sorted.
func (r *Registry) Types() []string {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]string, 0, len(r.factories))
for id := range r.factories {
out = append(out, id)
}
sort.Strings(out)
return out
}
// CreateProvider creates a provider instance by type with the given parameters.
func (r *Registry) CreateProvider(providerType string, params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
r.mu.RLock()

View File

@ -0,0 +1,64 @@
package providers
import "github.com/Tencent/WeKnora/internal/plugin/configschema"
// ExtraFieldsSchema describes a vendor's extra fields as a config schema.
//
// The values live in models.parameters.extra_config, a map of strings, so
// every field is a string: number and boolean fields only pick a widget, and
// a boolean is the choice between "true" and "false". A field is secret when
// it says so or is a password input, which is how the model editor already
// treats it.
func ExtraFieldsSchema(fields []ExtraField) *configschema.Schema {
s := configschema.Object()
for i, f := range fields {
prop := &configschema.Schema{
Type: configschema.TypeString,
Title: f.Label,
Placeholder: f.Placeholder,
Secret: f.Secret || f.Type == "password",
Order: i,
}
if f.Default != "" {
prop.Default = f.Default
}
addI18n(prop, "title", f.Labels)
addI18n(prop, "placeholder", f.Placeholders)
for _, mt := range f.ModelTypes {
prop.ModelTypes = append(prop.ModelTypes, string(mt))
}
switch f.Type {
case "password":
prop.Widget = "password"
case "number":
prop.Widget = "number"
case "boolean":
prop.Widget = "switch"
prop.OneOf = []*configschema.Schema{{Const: "true"}, {Const: "false"}}
case "select":
prop.Widget = "select"
for _, o := range f.Options {
choice := &configschema.Schema{Const: o.Value, Title: o.Label}
addI18n(choice, "title", o.Labels)
prop.OneOf = append(prop.OneOf, choice)
}
}
s.Set(f.Key, prop, f.Required)
}
return s
}
func addI18n(s *configschema.Schema, key string, locales map[string]string) {
for locale, text := range locales {
if text == "" {
continue
}
if s.I18n == nil {
s.I18n = map[string]map[string]string{}
}
if s.I18n[key] == nil {
s.I18n[key] = map[string]string{}
}
s.I18n[key][locale] = text
}
}

View File

@ -0,0 +1,73 @@
package providers
import (
"testing"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
"github.com/Tencent/WeKnora/internal/types"
)
func TestExtraFieldsSchemaCoversEveryBuiltin(t *testing.T) {
for _, d := range Builtins() {
if len(d.ExtraFields) == 0 {
continue
}
s := ExtraFieldsSchema(d.ExtraFields)
if err := s.Check(); err != nil {
t.Errorf("%s: schema invalid: %v", d.ID, err)
}
if len(s.Properties) != len(d.ExtraFields) {
t.Errorf("%s: %d properties for %d fields", d.ID, len(s.Properties), len(d.ExtraFields))
}
for _, f := range d.ExtraFields {
p := s.Properties[f.Key]
if p == nil {
t.Errorf("%s: field %s missing", d.ID, f.Key)
continue
}
if p.Secret != (f.Secret || f.Type == "password") {
t.Errorf("%s.%s: secret = %v", d.ID, f.Key, p.Secret)
}
}
// Defaults are valid values of their own field.
defaults := map[string]any{}
for key, p := range s.Properties {
if p.Default != nil {
defaults[key] = p.Default
}
}
for _, e := range configschema.Validate(s, defaults) {
if e.Code != configschema.CodeRequired {
t.Errorf("%s: default fails validation: %v", d.ID, e)
}
}
}
}
func TestExtraFieldsSchemaMapping(t *testing.T) {
s := ExtraFieldsSchema([]ExtraField{
{
Key: "region", Label: "Region", Labels: map[string]string{"zh-CN": "地域"}, Type: "select", Required: true,
Options: []ExtraFieldOption{{Label: "Beijing", Labels: map[string]string{"zh-CN": "北京"}, Value: "bj"}},
},
{Key: "sk", Label: "Secret Key", Type: "password", ModelTypes: []types.ModelType{types.ModelTypeRerank}},
{Key: "stream", Label: "Stream", Type: "boolean", Default: "true"},
})
region := s.Properties["region"]
if region.Widget != "select" || len(region.OneOf) != 1 || region.OneOf[0].Const != "bj" ||
region.OneOf[0].I18n["title"]["zh-CN"] != "北京" || region.I18n["title"]["zh-CN"] != "地域" {
t.Fatalf("select field = %+v", region)
}
if len(s.Required) != 1 || s.Required[0] != "region" {
t.Fatalf("required = %v", s.Required)
}
sk := s.Properties["sk"]
if !sk.Secret || sk.Widget != "password" ||
len(sk.ModelTypes) != 1 || sk.ModelTypes[0] != string(types.ModelTypeRerank) {
t.Fatalf("password field = %+v", sk)
}
if errs := configschema.Validate(s, map[string]any{"region": "bj", "stream": "yes"}); len(errs) != 1 ||
errs[0].Path != "stream" || errs[0].Code != configschema.CodeEnum {
t.Fatalf("boolean must accept only true/false strings, got %v", errs)
}
}

View File

@ -0,0 +1,232 @@
// Package builtin describes the capabilities compiled into WeKnora as builtin
// plugins, so the plugin registry lists them next to third-party ones.
//
// Contributions are grouped into one plugin per vendor: Feishu's wiki and
// drive connectors and its IM channel all belong to weknora.feishu, which is
// the granularity a tenant enables or disables and the granularity a
// third-party plugin ships at.
package builtin
import (
"sort"
"strings"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/models/providers"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/plugin/registry"
"github.com/Tencent/WeKnora/internal/types"
)
// Sources is what builtin plugins are described from: the metadata each
// domain already keeps, limited to what is actually registered in this
// process.
type Sources struct {
// Version is the WeKnora build version; builtins share it.
Version string
ModelVendors []*providers.Definition
Connectors []datasource.ConnectorMetadata
IMPlatforms []im.PlatformInfo
WebSearch []types.WebSearchProviderTypeInfo
Tools []tools.AvailableTool
Parsers []Parser
}
// Parser is the metadata of one locally registered parser engine.
type Parser struct {
Name string
Description string
}
// Plugin IDs that group contributions without a vendor of their own.
const (
agentToolsKey = "agent-tools"
docParserKey = "docparser"
)
// vendorOverrides maps a contribution ID to its vendor where the two differ.
var vendorOverrides = map[manifest.Point]map[string]string{
manifest.PointConnectors: {
types.ConnectorTypeLark: "feishu",
types.ConnectorTypeFeishuDrive: "feishu",
types.ConnectorTypeLarkDrive: "feishu",
},
manifest.PointIMChannels: {"lark": "feishu"},
manifest.PointParsers: {
"builtin": docParserKey,
"simple": docParserKey,
"anydoc": docParserKey,
"mineru_cloud": "mineru",
"paddleocr_vl": "paddleocr",
"paddleocr_vl_cloud": "paddleocr",
},
}
// vendorNames names plugins that group several contributions. A vendor absent
// here takes the name of its first contribution, model vendors first.
var vendorNames = map[string]manifest.LocalizedText{
"feishu": manifest.Text("Feishu / Lark", map[string]string{"zh-CN": "飞书 / Lark"}),
"dingtalk": manifest.Text("DingTalk", map[string]string{"zh-CN": "钉钉"}),
"mineru": manifest.Text("MinerU", nil),
"paddleocr": manifest.Text("PaddleOCR-VL", nil),
docParserKey: manifest.Text("Document parsing", map[string]string{"zh-CN": "文档解析"}),
agentToolsKey: manifest.Text("Agent tools", map[string]string{"zh-CN": "Agent 内置工具"}),
}
// requiredVendors are builtins a tenant may not disable: without them agents
// and document import stop working altogether.
var requiredVendors = map[string]bool{agentToolsKey: true, docParserKey: true}
// Manifests describes every builtin capability in src as builtin plugins,
// sorted by plugin ID.
func Manifests(src Sources) []*manifest.Manifest {
b := &builder{version: normalizeVersion(src.Version), plugins: make(map[string]*manifest.Manifest)}
// Model vendors go first so a vendor that also offers web search (Zhipu)
// is named after its model brand.
for _, d := range src.ModelVendors {
b.add(manifest.PointModelVendors, d.ID, manifest.Contribution{
ID: d.ID,
Name: manifest.Text(d.Name, d.Names),
Description: manifest.Text(d.Description, d.Descriptions),
Order: d.Order,
Extra: map[string]any{"modelTypes": d.ModelTypes},
})
}
for _, c := range src.Connectors {
b.add(manifest.PointConnectors, c.Type, manifest.Contribution{
ID: c.Type,
Name: manifest.Text(c.Name, nil),
Description: manifest.Text(c.Description, nil),
Icon: c.Icon,
Capabilities: c.Capabilities,
Order: c.Priority,
Extra: map[string]any{"authType": c.AuthType},
})
}
for _, p := range src.IMPlatforms {
b.add(manifest.PointIMChannels, p.ID, manifest.Contribution{
ID: p.ID,
Name: manifest.Text(p.Name, p.Names),
Order: p.Order,
})
}
for i, w := range src.WebSearch {
b.add(manifest.PointWebSearch, w.ID, manifest.Contribution{
ID: w.ID,
Name: manifest.Text(w.Name, nil),
Description: manifest.Text(w.Description, nil),
Order: i,
})
}
for i, t := range src.Tools {
b.addTo(agentToolsKey, manifest.PointTools, t.Name, manifest.Contribution{
ID: t.Name,
Name: manifest.Text(t.Label, nil),
Description: manifest.Text(t.Description, nil),
Order: i,
})
}
for i, p := range src.Parsers {
b.add(manifest.PointParsers, p.Name, manifest.Contribution{
ID: p.Name,
Name: manifest.Text(p.Name, nil),
Description: manifest.Text(p.Description, nil),
Order: i,
})
}
return b.result()
}
// Register adds every builtin in src to r.
func Register(r *registry.Registry, src Sources) error {
for _, m := range Manifests(src) {
if err := r.Register(m); err != nil {
return err
}
}
return nil
}
type builder struct {
version string
plugins map[string]*manifest.Manifest
}
func (b *builder) add(point manifest.Point, id string, c manifest.Contribution) {
vendor := id
if v, ok := vendorOverrides[point][id]; ok {
vendor = v
}
b.addTo(vendor, point, id, c)
}
// addTo files a contribution under a vendor's plugin. The contribution keeps
// its bare ID as alias, since that is what existing rows store.
func (b *builder) addTo(vendor string, point manifest.Point, alias string, c manifest.Contribution) {
c.Aliases = []string{alias}
id := pluginID(vendor)
m, ok := b.plugins[id]
if !ok {
name, named := vendorNames[vendor]
if !named {
name = c.Name
}
m = &manifest.Manifest{
SchemaVersion: manifest.SchemaVersion,
ID: id,
Version: b.version,
Name: name,
Publisher: manifest.Publisher{ID: manifest.BuiltinPublisher, Name: "WeKnora"},
Builtin: true,
Required: requiredVendors[vendor],
Runtime: manifest.Runtime{Type: manifest.RuntimeBuiltin},
Contributes: manifest.Contributions{},
}
b.plugins[id] = m
}
m.Contributes[point] = append(m.Contributes[point], c)
}
func (b *builder) result() []*manifest.Manifest {
out := make([]*manifest.Manifest, 0, len(b.plugins))
for _, m := range b.plugins {
// A plugin with a single contribution borrows its description.
if all := allContributions(m); len(all) == 1 {
m.Description = all[0].Description
}
out = append(out, m)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
func allContributions(m *manifest.Manifest) []manifest.Contribution {
var out []manifest.Contribution
for _, list := range m.Contributes {
out = append(out, list...)
}
return out
}
// devVersion stands in when the build carries no usable version (local
// builds report "unknown").
const devVersion = "0.0.0-dev"
// normalizeVersion turns a build version ("v0.8.2", "0.8.2") into the bare
// semantic version manifests require.
func normalizeVersion(v string) string {
v = strings.TrimPrefix(strings.TrimSpace(v), "v")
probe := &manifest.Manifest{Version: v}
if !probe.HasValidVersion() {
return devVersion
}
return v
}
// pluginID turns a vendor key into a builtin plugin ID. Plugin IDs allow no
// underscores, so azure_openai becomes weknora.azure-openai.
func pluginID(vendor string) string {
return manifest.BuiltinPublisher + "." + strings.ReplaceAll(vendor, "_", "-")
}

View File

@ -0,0 +1,150 @@
package builtin
import (
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/infrastructure/web_search"
"github.com/Tencent/WeKnora/internal/models/providers"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
"github.com/Tencent/WeKnora/internal/plugin/registry"
"github.com/Tencent/WeKnora/internal/types"
)
func sampleSources() Sources {
return Sources{
Version: "v0.8.2",
ModelVendors: []*providers.Definition{
{ID: "zhipu", Name: "Zhipu AI", Names: map[string]string{"zh-CN": "智谱"}},
{ID: "azure_openai", Name: "Azure OpenAI"},
},
Connectors: []datasource.ConnectorMetadata{
{Type: types.ConnectorTypeFeishu, Name: "Feishu (飞书)", Capabilities: []string{"incremental"}},
{Type: types.ConnectorTypeLarkDrive, Name: "Lark Drive"},
{Type: types.ConnectorTypeNotion, Name: "Notion", Priority: 1},
},
IMPlatforms: []im.PlatformInfo{im.LookupPlatformInfo("feishu"), im.LookupPlatformInfo("lark")},
WebSearch: []types.WebSearchProviderTypeInfo{{ID: "zhipu", Name: "Zhipu Search"}, {ID: "bing", Name: "Bing"}},
Tools: []tools.AvailableTool{{Name: "search_knowledge", Label: "检索知识库"}},
Parsers: []Parser{{Name: "builtin"}, {Name: "simple"}, {Name: "mineru"}, {Name: "mineru_cloud"}},
}
}
func TestManifestsGroupByVendor(t *testing.T) {
byID := map[string]*manifest.Manifest{}
for _, m := range Manifests(sampleSources()) {
byID[m.ID] = m
}
want := []string{
"weknora.zhipu", "weknora.azure-openai", "weknora.feishu", "weknora.notion",
"weknora.bing", "weknora.agent-tools", "weknora.docparser", "weknora.mineru",
}
if len(byID) != len(want) {
t.Fatalf("got %d plugins, want %d: %v", len(byID), len(want), byID)
}
for _, id := range want {
if byID[id] == nil {
t.Fatalf("missing plugin %s", id)
}
}
feishu := byID["weknora.feishu"]
if n := len(feishu.Contributes[manifest.PointConnectors]); n != 2 {
t.Fatalf("feishu connectors = %d, want 2 (wiki + lark drive)", n)
}
if n := len(feishu.Contributes[manifest.PointIMChannels]); n != 2 {
t.Fatalf("feishu IM channels = %d, want 2 (feishu + lark)", n)
}
if got := feishu.Name.Resolve("zh-CN"); got != "飞书 / Lark" {
t.Fatalf("feishu name = %q", got)
}
zhipu := byID["weknora.zhipu"]
if zhipu.Name.Resolve("zh-CN") != "智谱" {
t.Fatalf("a vendor with a model brand is named after it, got %+v", zhipu.Name)
}
if len(zhipu.Contributes[manifest.PointWebSearch]) != 1 {
t.Fatal("zhipu web search should join the zhipu plugin")
}
if !byID["weknora.agent-tools"].Required || !byID["weknora.docparser"].Required {
t.Fatal("agent tools and the default parser must be required")
}
if byID["weknora.notion"].Required {
t.Fatal("ordinary vendors must not be required")
}
if byID["weknora.bing"].Version != "0.8.2" {
t.Fatalf("version = %q", byID["weknora.bing"].Version)
}
}
func TestRegisterResolvesLegacyIDs(t *testing.T) {
r := registry.New()
if err := Register(r, sampleSources()); err != nil {
t.Fatalf("Register: %v", err)
}
cases := []struct {
point manifest.Point
alias string
want string
}{
{manifest.PointConnectors, "lark_drive", "weknora.feishu/lark_drive"},
{manifest.PointIMChannels, "lark", "weknora.feishu/lark"},
{manifest.PointModelVendors, "azure_openai", "weknora.azure-openai/azure_openai"},
{manifest.PointParsers, "mineru_cloud", "weknora.mineru/mineru_cloud"},
{manifest.PointTools, "search_knowledge", "weknora.agent-tools/search_knowledge"},
}
for _, c := range cases {
e, ok := r.Resolve(c.point, c.alias)
if !ok || e.QualifiedID != c.want {
t.Errorf("Resolve(%s, %s) = %q, %v; want %q", c.point, c.alias, e.QualifiedID, ok, c.want)
}
}
}
func TestNormalizeVersion(t *testing.T) {
for in, want := range map[string]string{
"v0.8.2": "0.8.2", "0.8.2": "0.8.2", "unknown": devVersion, "": devVersion, "0.8": devVersion,
} {
if got := normalizeVersion(in); got != want {
t.Errorf("normalizeVersion(%q) = %q, want %q", in, got, want)
}
}
}
func TestCollectSourcesKeepsOnlyRegistered(t *testing.T) {
ws := web_search.NewRegistry()
ws.Register("bing", nil)
ws.Register("custom-search", nil)
connectors := datasource.NewConnectorRegistry()
src := CollectSources(Live{
Version: "0.8.2",
Connectors: connectors,
WebSearch: ws,
IMPlatforms: []string{"slack", "brand-new"},
})
var webSearch []string
for _, w := range src.WebSearch {
webSearch = append(webSearch, w.ID)
}
if strings.Join(webSearch, ",") != "bing,custom-search" {
t.Fatalf("web search = %v, want the registered ones only, unknown last", webSearch)
}
if len(src.Connectors) != 0 {
t.Fatalf("no connector is registered, got %v", src.Connectors)
}
if len(src.IMPlatforms) != 2 || src.IMPlatforms[1].Name != "brand-new" {
t.Fatalf("IM platforms = %+v", src.IMPlatforms)
}
if len(src.Parsers) == 0 || len(src.Tools) == 0 || len(src.ModelVendors) == 0 {
t.Fatal("process-wide registries (parsers, tools, model vendors) should be collected")
}
if _, err := NewRegistry(Live{Version: "0.8.2", WebSearch: ws}); err != nil {
t.Fatalf("NewRegistry: %v", err)
}
}

View File

@ -0,0 +1,98 @@
package builtin
import (
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"testing"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/plugin/configschema"
"github.com/Tencent/WeKnora/internal/types"
)
// backendSchemaKeysFile lists the frontend locale keys the backend names:
// x-i18n-keys in builtin config schemas, IM platform link titles and mode
// hints. The frontend i18n audit treats them as used, so pruning
// never drops a label only the backend references.
const backendSchemaKeysFile = "../../../frontend/src/i18n/backendSchemaKeys.ts"
func collectI18nKeys(s *configschema.Schema, into map[string]bool) {
if s == nil {
return
}
for _, key := range s.I18nKeys {
into[key] = true
}
for _, p := range s.Properties {
collectI18nKeys(p, into)
}
for _, c := range s.OneOf {
collectI18nKeys(c, into)
}
collectI18nKeys(s.Items, into)
}
func TestBackendSchemaKeysAreListedForTheFrontend(t *testing.T) {
used := map[string]bool{}
for _, info := range types.GetWebSearchProviderTypes() {
collectI18nKeys(info.ConfigSchema, used)
}
for _, meta := range datasource.ListAvailableConnectors() {
collectI18nKeys(meta.ConfigSchema, used)
}
for _, info := range im.KnownPlatformInfos() {
collectI18nKeys(info.ConfigSchema, used)
for _, link := range info.Links {
if link.TitleKey != "" {
used[link.TitleKey] = true
}
}
if info.ModeHintKey != "" {
used[info.ModeHintKey] = true
}
}
data, err := os.ReadFile(filepath.FromSlash(backendSchemaKeysFile))
if err != nil {
t.Fatalf("read %s: %v", backendSchemaKeysFile, err)
}
listed := map[string]bool{}
for _, m := range regexp.MustCompile(`'([A-Za-z0-9_.]+)'`).FindAllStringSubmatch(string(data), -1) {
listed[m[1]] = true
}
var missing, stale []string
for k := range used {
if !listed[k] {
missing = append(missing, k)
}
}
for k := range listed {
if !used[k] {
stale = append(stale, k)
}
}
sort.Strings(missing)
sort.Strings(stale)
if len(missing) > 0 {
t.Errorf("add to %s: %v", backendSchemaKeysFile, missing)
}
if len(stale) > 0 {
t.Errorf("no builtin schema uses these any more, drop them from %s: %v", backendSchemaKeysFile, stale)
}
if !slices.IsSorted(keysInFileOrder(string(data))) {
t.Errorf("keep %s sorted", backendSchemaKeysFile)
}
}
func keysInFileOrder(src string) []string {
var out []string
for _, m := range regexp.MustCompile(`'([A-Za-z0-9_.]+)'`).FindAllStringSubmatch(src, -1) {
out = append(out, m[1])
}
return out
}

View File

@ -0,0 +1,103 @@
package builtin
import (
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/datasource"
confluenceConnector "github.com/Tencent/WeKnora/internal/datasource/connector/confluence"
dingtalkConnector "github.com/Tencent/WeKnora/internal/datasource/connector/dingtalk"
"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"
gitlabConnector "github.com/Tencent/WeKnora/internal/datasource/connector/gitlab"
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"
"github.com/Tencent/WeKnora/internal/im"
imDingtalk "github.com/Tencent/WeKnora/internal/im/dingtalk"
imFeishu "github.com/Tencent/WeKnora/internal/im/feishu"
imMattermost "github.com/Tencent/WeKnora/internal/im/mattermost"
imQQBot "github.com/Tencent/WeKnora/internal/im/qqbot"
imSlack "github.com/Tencent/WeKnora/internal/im/slack"
imTelegram "github.com/Tencent/WeKnora/internal/im/telegram"
imWechat "github.com/Tencent/WeKnora/internal/im/wechat"
imWecom "github.com/Tencent/WeKnora/internal/im/wecom"
imYunzhijia "github.com/Tencent/WeKnora/internal/im/yunzhijia"
"github.com/Tencent/WeKnora/internal/infrastructure/web_search"
)
// This file registers the implementations behind the builtin plugins with
// the domain registries, so every builtin capability is declared in this
// package: implementations here, descriptions in builtin.go.
// NewConnectorRegistry returns the data source registry holding every builtin
// connector.
func NewConnectorRegistry() (*datasource.ConnectorRegistry, error) {
registry := datasource.NewConnectorRegistry()
connectors := []datasource.Connector{
wiki.NewConnector(core.RegionFeishu),
// Lark is Feishu's international cloud: same connector, other host.
wiki.NewConnector(core.RegionLark),
// Drive (云盘) mode is its own type so the registry dispatches to the
// Drive connector; it shares the Feishu client and export logic.
drive.NewDriveConnector(core.RegionFeishuDrive),
drive.NewDriveConnector(core.RegionLarkDrive),
notionConnector.NewConnector(),
confluenceConnector.NewConnector(),
yuqueConnector.NewConnector(),
dingtalkConnector.NewConnector(),
imaConnector.NewConnector(),
rssConnector.NewConnector(),
gitlabConnector.NewConnector(),
}
var errs error
for _, c := range connectors {
if err := registry.Register(c); err != nil {
errs = errors.Join(errs, fmt.Errorf("register %s connector: %w", c.Type(), err))
}
}
if errs != nil {
return nil, errs
}
return registry, nil
}
// RegisterWebSearchProviders registers every builtin web search provider.
func RegisterWebSearchProviders(registry *web_search.Registry) {
for id, factory := range map[string]web_search.ProviderFactory{
"duckduckgo": web_search.NewDuckDuckGoProvider,
"google": web_search.NewGoogleProvider,
"bing": web_search.NewBingProvider,
"tavily": web_search.NewTavilyProvider,
"ollama": web_search.NewOllamaProvider,
"baidu": web_search.NewBaiduProvider,
"searxng": web_search.NewSearxngProvider,
"keenable": web_search.NewKeenableProvider,
"zhipu": web_search.NewZhipuProvider,
"exa": web_search.NewExaProvider,
"metaso": web_search.NewMetasoProvider,
"bocha": web_search.NewBochaProvider,
"brave": web_search.NewBraveProvider,
"serply": web_search.NewSerplyProvider,
} {
registry.Register(id, factory)
}
}
// RegisterIMAdapters registers every builtin IM platform adapter. Each
// platform's factory lives in its own subpackage.
func RegisterIMAdapters(s *im.Service) {
s.RegisterAdapterFactory("wecom", imWecom.NewFactory())
s.RegisterAdapterFactory("feishu", imFeishu.NewFactory(imFeishu.RegionFeishu))
// Lark is Feishu's international cloud: same adapter, other host/tenant.
s.RegisterAdapterFactory("lark", imFeishu.NewFactory(imFeishu.RegionLark))
s.RegisterAdapterFactory("slack", imSlack.NewFactory())
s.RegisterAdapterFactory("telegram", imTelegram.NewFactory())
s.RegisterAdapterFactory("dingtalk", imDingtalk.NewFactory())
s.RegisterAdapterFactory("mattermost", imMattermost.NewFactory())
s.RegisterAdapterFactory("wechat", imWechat.NewFactory())
s.RegisterAdapterFactory("qqbot", imQQBot.NewFactory())
s.RegisterAdapterFactory("yunzhijia", imYunzhijia.NewFactory())
}

View File

@ -0,0 +1,83 @@
package builtin
import (
"sort"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/datasource"
"github.com/Tencent/WeKnora/internal/im"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
"github.com/Tencent/WeKnora/internal/infrastructure/web_search"
modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"
"github.com/Tencent/WeKnora/internal/plugin/registry"
"github.com/Tencent/WeKnora/internal/types"
)
// Live is what this process has actually registered. Metadata tables list
// some connectors and providers that are not wired up yet (GitHub, Google
// Drive); only registered ones become contributions.
type Live struct {
Version string
Connectors *datasource.ConnectorRegistry
WebSearch *web_search.Registry
IMPlatforms []string
}
// CollectSources gathers builtin metadata for what live has registered.
func CollectSources(live Live) Sources {
src := Sources{
Version: live.Version,
Tools: tools.AvailableToolDefinitions(),
}
for _, p := range modelruntime.List() {
src.ModelVendors = append(src.ModelVendors, p.Definition)
}
if live.Connectors != nil {
src.Connectors = live.Connectors.Metadata()
}
for _, p := range live.IMPlatforms {
src.IMPlatforms = append(src.IMPlatforms, im.LookupPlatformInfo(p))
}
if live.WebSearch != nil {
registered := toSet(live.WebSearch.Types())
for _, info := range types.GetWebSearchProviderTypes() {
if registered[info.ID] {
src.WebSearch = append(src.WebSearch, info)
delete(registered, info.ID)
}
}
for _, id := range sortedKeys(registered) {
src.WebSearch = append(src.WebSearch, types.WebSearchProviderTypeInfo{ID: id, Name: id})
}
}
for _, e := range docparser.Engines() {
src.Parsers = append(src.Parsers, Parser{Name: e.Name(), Description: e.Description()})
}
return src
}
// NewRegistry builds a plugin registry holding every builtin in live.
func NewRegistry(live Live) (*registry.Registry, error) {
r := registry.New()
if err := Register(r, CollectSources(live)); err != nil {
return nil, err
}
return r, nil
}
func toSet(values []string) map[string]bool {
out := make(map[string]bool, len(values))
for _, v := range values {
out[v] = true
}
return out
}
func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}

View File

@ -0,0 +1,264 @@
package configschema
import (
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/utils"
)
const testAESKey = "0123456789abcdef0123456789abcdef"
func intPtr(v int) *int { return &v }
func floatPtr(v float64) *float64 { return &v }
// jiraSchema is a connector-shaped schema: a URL, an auth mode, a token that
// only applies to one mode, and a nested object holding a secret.
func jiraSchema() *Schema {
auth := Object().
Set("user", &Schema{Type: TypeString}, false).
Set("password", &Schema{Type: TypeString, Secret: true}, false)
return Object().
Set("base_url", &Schema{Type: TypeString, Format: "uri", Order: 1}, true).
Set("mode", &Schema{Type: TypeString, OneOf: []*Schema{
{Const: "token", Title: "API token"}, {Const: "basic", Title: "Basic"},
}, Order: 2}, true).
Set("token", &Schema{
Type: TypeString, Secret: true, MinLength: intPtr(8),
VisibleIf: map[string]any{"mode": "token"}, Order: 3,
}, true).
Set("page_size", &Schema{Type: TypeInteger, Minimum: floatPtr(1), Maximum: floatPtr(100)}, false).
Set("auth", auth, false)
}
func TestCheckRejectsUnsupportedSchemas(t *testing.T) {
bad := []struct {
name string
schema *Schema
want string
}{
{"root not object", &Schema{Type: TypeString}, "root must be an object"},
{"unknown type", Object().Set("x", &Schema{Type: "date"}, false), `unsupported type "date"`},
{"secret number", Object().Set("x", &Schema{Type: TypeNumber, Secret: true}, false), "only allowed on strings"},
{"secret in array", Object().Set("x", &Schema{
Type: TypeArray, Items: &Schema{Type: TypeString, Secret: true},
}, false), "secrets inside arrays"},
{"required ghost", &Schema{Type: TypeObject, Required: []string{"ghost"}}, `"ghost" has no property`},
{"bad pattern", Object().Set("x", &Schema{Type: TypeString, Pattern: "("}, false), "invalid pattern"},
{"oneOf without const", Object().Set("x", &Schema{
Type: TypeString, OneOf: []*Schema{{Title: "A"}},
}, false), "must carry a const"},
}
for _, c := range bad {
err := c.schema.Check()
if err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%s: got %v, want error containing %q", c.name, err, c.want)
}
}
if err := jiraSchema().Check(); err != nil {
t.Fatalf("valid schema rejected: %v", err)
}
}
func TestParseRoundTrip(t *testing.T) {
data, err := json.Marshal(jiraSchema())
if err != nil {
t.Fatal(err)
}
for _, key := range []string{`"x-secret":true`, `"x-visible-if":{"mode":"token"}`, `"oneOf"`} {
if !strings.Contains(string(data), key) {
t.Fatalf("marshalled schema lacks %s: %s", key, data)
}
}
back, err := Parse(data)
if err != nil {
t.Fatalf("Parse: %v", err)
}
if got := back.SecretPaths(); strings.Join(got, ",") != "auth.password,token" {
t.Fatalf("SecretPaths = %v", got)
}
if got := back.OrderedKeys(); strings.Join(got, ",") != "auth,page_size,base_url,mode,token" {
t.Fatalf("OrderedKeys = %v", got)
}
}
func TestValidate(t *testing.T) {
s := jiraSchema()
ok := map[string]any{
"base_url": "https://acme.atlassian.net", "mode": "token", "token": "abcdefgh", "page_size": 50.0,
}
if errs := Validate(s, ok); errs != nil {
t.Fatalf("valid config rejected: %v", errs)
}
// token is required only while mode is token.
basic := map[string]any{"base_url": "https://acme.atlassian.net", "mode": "basic"}
if errs := Validate(s, basic); errs != nil {
t.Fatalf("hidden required field must not be required: %v", errs)
}
bad := map[string]any{
"base_url": "not a url",
"mode": "oauth",
"token": "short",
"page_size": 1.5,
"auth": map[string]any{"user": 42},
}
errs := Validate(s, bad)
got := map[string]string{}
for _, e := range errs {
got[e.Path] = e.Code
}
want := map[string]string{
"base_url": CodeFormat, "mode": CodeEnum, "page_size": CodeType, "auth.user": CodeType,
}
for path, code := range want {
if got[path] != code {
t.Errorf("%s: code %q, want %q (all: %v)", path, got[path], code, errs)
}
}
// mode is invalid, so token is hidden and not checked.
if _, checked := got["token"]; checked {
t.Errorf("token should be skipped while mode is not token: %v", errs)
}
missing := Validate(s, map[string]any{"mode": "token", "token": ""})
if len(missing) != 2 || missing[0].Code != CodeRequired || missing[1].Code != CodeRequired {
t.Fatalf("want base_url and token required, got %v", missing)
}
if !strings.Contains(missing.Error(), "base_url: is required") {
t.Fatalf("error text = %q", missing.Error())
}
// A redacted secret counts as present and skips its own checks.
if errs := Validate(s, map[string]any{
"base_url": "https://acme.atlassian.net", "mode": "token", "token": RedactedPlaceholder,
}); errs != nil {
t.Fatalf("redacted secret rejected: %v", errs)
}
if errs := Validate(s, map[string]any{
"base_url": "https://x.io", "mode": "basic", "page_size": 500.0,
}); len(errs) != 1 || errs[0].Code != CodeMaximum {
t.Fatalf("want maximum error, got %v", errs)
}
}
func TestSealOpenRedactMerge(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", testAESKey)
s := jiraSchema()
plain := map[string]any{
"base_url": "https://acme.atlassian.net",
"mode": "token",
"token": "secret-token",
"auth": map[string]any{"user": "bob", "password": "hunter2"},
}
sealed, err := Seal(s, plain)
if err != nil {
t.Fatal(err)
}
if plain["token"] != "secret-token" {
t.Fatal("Seal must not mutate its input")
}
token, _ := sealed["token"].(string)
password, _ := sealed["auth"].(map[string]any)["password"].(string)
if !strings.HasPrefix(token, utils.EncPrefix) || !strings.HasPrefix(password, utils.EncPrefix) {
t.Fatalf("secrets not encrypted: %v", sealed)
}
if sealed["base_url"] != plain["base_url"] || sealed["auth"].(map[string]any)["user"] != "bob" {
t.Fatalf("non-secrets must pass through: %v", sealed)
}
// Sealing twice keeps the ciphertext.
again, err := Seal(s, sealed)
if err != nil || again["token"] != token {
t.Fatalf("Seal is not idempotent: %v, %v", again["token"], err)
}
// Values sealed here read back through the helper every other table uses.
if got, err := utils.DecryptStoredSecret(token); err != nil || got != "secret-token" {
t.Fatalf("DecryptStoredSecret = %q, %v", got, err)
}
opened, err := Open(s, sealed)
if err != nil {
t.Fatal(err)
}
if opened["token"] != "secret-token" || opened["auth"].(map[string]any)["password"] != "hunter2" {
t.Fatalf("Open = %v", opened)
}
redacted := Redact(s, sealed)
if redacted["token"] != RedactedPlaceholder ||
redacted["auth"].(map[string]any)["password"] != RedactedPlaceholder {
t.Fatalf("Redact = %v", redacted)
}
if Redact(s, map[string]any{"token": ""})["token"] != "" {
t.Fatal("an unset secret must stay empty so the UI can tell it apart")
}
// The client sends the redacted form back with one field changed.
incoming := Redact(s, sealed)
incoming["base_url"] = "https://new.atlassian.net"
delete(incoming["auth"].(map[string]any), "password")
merged := Merge(s, sealed, incoming)
if merged["token"] != token || merged["auth"].(map[string]any)["password"] != password {
t.Fatalf("Merge must keep stored secrets: %v", merged)
}
if merged["base_url"] != "https://new.atlassian.net" {
t.Fatalf("Merge must apply changed fields: %v", merged)
}
replaced := Merge(s, sealed, map[string]any{"token": "new-token"})
if replaced["token"] != "new-token" {
t.Fatalf("a new secret must replace the stored one: %v", replaced)
}
if replaced["auth"].(map[string]any)["password"] != password {
t.Fatalf("a nested secret the update leaves out must survive: %v", replaced)
}
}
func TestOpenWithoutKey(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", testAESKey)
s := jiraSchema()
sealed, err := Seal(s, map[string]any{"token": "secret-token", "mode": "token"})
if err != nil {
t.Fatal(err)
}
t.Setenv("SYSTEM_AES_KEY", "")
if _, err := Open(s, sealed); err == nil || !strings.Contains(err.Error(), "decrypt token") {
t.Fatalf("Open without key must fail loudly, got %v", err)
}
lenient, failed := OpenLenient(s, sealed)
if lenient["token"] != "" || len(failed) != 1 || failed[0] != "token" {
t.Fatalf("OpenLenient = %v, failed %v", lenient, failed)
}
if lenient["mode"] != "token" {
t.Fatal("OpenLenient must keep the rest of the row")
}
// Legacy plaintext rows still open.
legacy, err := Open(s, map[string]any{"token": "plain-legacy"})
if err != nil || legacy["token"] != "plain-legacy" {
t.Fatalf("legacy plaintext = %v, %v", legacy, err)
}
}
func TestValidateInContextReadsDollarKeysFromContext(t *testing.T) {
s := Object().
Set("bot_token", &Schema{Type: TypeString}, true).
Set("signing_secret", &Schema{Type: TypeString, VisibleIf: map[string]any{"$mode": "webhook"}}, true)
value := map[string]any{"bot_token": "x"}
if errs := ValidateInContext(s, value, map[string]any{"mode": "websocket"}); errs != nil {
t.Fatalf("websocket mode hides the webhook secret: %v", errs)
}
errs := ValidateInContext(s, value, map[string]any{"mode": "webhook"})
if len(errs) != 1 || errs[0].Path != "signing_secret" {
t.Fatalf("webhook mode requires the signing secret, got %v", errs)
}
// Without a context the field is hidden, never wrongly required.
if errs := Validate(s, value); errs != nil {
t.Fatalf("Validate without context: %v", errs)
}
}

View File

@ -0,0 +1,219 @@
// Package configschema describes configuration with a subset of JSON Schema
// (draft 2020-12) plus a few x- keywords for the UI, and handles the secret
// fields such a schema marks: encrypting them at rest, redacting them in
// responses and keeping them when an update sends the redaction back.
//
// One schema drives both the form the frontend renders and the server-side
// validation, replacing the per-integration field descriptors (model vendor
// ExtraField, web search config fields, hardcoded connector and IM forms).
package configschema
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
)
// Types a schema node may declare.
const (
TypeObject = "object"
TypeString = "string"
TypeNumber = "number"
TypeInteger = "integer"
TypeBoolean = "boolean"
TypeArray = "array"
)
// Schema is one node of a configuration schema. The root is an object whose
// properties are the fields of a form.
type Schema struct {
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
Items *Schema `json:"items,omitempty"`
Default any `json:"default,omitempty"`
Const any `json:"const,omitempty"`
Enum []any `json:"enum,omitempty"`
// OneOf lists labelled choices: each entry carries a const and a title.
OneOf []*Schema `json:"oneOf,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
// Format is "uri" or "email"; other formats are carried but not checked.
Format string `json:"format,omitempty"`
// Secret marks a string that is encrypted at rest, redacted in
// responses, and kept when an update sends the redaction back.
Secret bool `json:"x-secret,omitempty"`
// Widget picks the form control (password, textarea, select, switch,
// headers, ...). Empty means the frontend picks from the type; "hidden"
// keeps a field out of the form while still declaring it (a secret set
// by another flow, such as WeChat's QR binding).
Widget string `json:"x-widget,omitempty"`
Placeholder string `json:"x-placeholder,omitempty"`
// I18n carries localized title / description / placeholder:
// {"title": {"zh-CN": "..."}}.
I18n map[string]map[string]string `json:"x-i18n,omitempty"`
// I18nKeys names frontend locale keys for title / description /
// placeholder. Builtins use them; the frontend falls back to I18n and
// then to the plain text when a key is missing.
I18nKeys map[string]string `json:"x-i18n-keys,omitempty"`
// VisibleIf shows the field only while every listed sibling field
// equals the given value.
VisibleIf map[string]any `json:"x-visible-if,omitempty"`
Group string `json:"x-group,omitempty"`
// Order sorts fields in the form (lower first); ties sort by key.
Order int `json:"x-order,omitempty"`
// ModelTypes limits a model vendor field to some model types.
ModelTypes []string `json:"x-model-types,omitempty"`
}
// Object returns an empty object schema.
func Object() *Schema { return &Schema{Type: TypeObject, Properties: map[string]*Schema{}} }
// Set adds a property and returns the parent for chaining. A required
// property is also listed in Required.
func (s *Schema) Set(key string, prop *Schema, required bool) *Schema {
if s.Properties == nil {
s.Properties = map[string]*Schema{}
}
s.Properties[key] = prop
if required {
s.Required = append(s.Required, key)
}
return s
}
// OrderedKeys returns property keys sorted by x-order, then by key.
func (s *Schema) OrderedKeys() []string {
keys := make([]string, 0, len(s.Properties))
for k := range s.Properties {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
oi, oj := s.Properties[keys[i]].Order, s.Properties[keys[j]].Order
if oi != oj {
return oi < oj
}
return keys[i] < keys[j]
})
return keys
}
// Parse decodes a schema and checks that it stays within the supported
// subset.
func Parse(data []byte) (*Schema, error) {
var s Schema
if err := json.Unmarshal(data, &s); err != nil {
return nil, fmt.Errorf("decode config schema: %w", err)
}
if err := s.Check(); err != nil {
return nil, err
}
return &s, nil
}
// Check verifies that a schema uses only what this package understands. The
// root must be an object, since a configuration is always a set of fields.
func (s *Schema) Check() error {
if s.Type != TypeObject {
return errors.New("config schema root must be an object")
}
var errs []error
s.check("", &errs)
return errors.Join(errs...)
}
func (s *Schema) check(path string, errs *[]error) {
fail := func(format string, args ...any) {
*errs = append(*errs, fmt.Errorf("%s: %s", displayPath(path), fmt.Sprintf(format, args...)))
}
switch s.Type {
case TypeObject:
for _, key := range s.Required {
if _, ok := s.Properties[key]; !ok {
fail("required field %q has no property", key)
}
}
for _, key := range s.OrderedKeys() {
s.Properties[key].check(joinPath(path, key), errs)
}
case TypeArray:
if s.Items == nil {
fail("array needs items")
} else {
if s.Items.containsSecret() {
fail("secrets inside arrays are not supported")
}
s.Items.check(path+"[]", errs)
}
case TypeString, TypeNumber, TypeInteger, TypeBoolean:
default:
fail("unsupported type %q", s.Type)
}
if s.Secret && s.Type != TypeString {
fail("x-secret is only allowed on strings")
}
if s.Pattern != "" {
if _, err := regexp.Compile(s.Pattern); err != nil {
fail("invalid pattern: %v", err)
}
}
for _, choice := range s.OneOf {
if choice.Const == nil {
fail("oneOf entries must carry a const")
}
}
}
func (s *Schema) containsSecret() bool {
if s.Secret {
return true
}
for _, p := range s.Properties {
if p.containsSecret() {
return true
}
}
return s.Items != nil && s.Items.containsSecret()
}
// SecretPaths lists the dotted paths of every secret field, sorted.
func (s *Schema) SecretPaths() []string {
var out []string
var walk func(n *Schema, path string)
walk = func(n *Schema, path string) {
if n.Secret {
out = append(out, path)
}
for key, p := range n.Properties {
walk(p, joinPath(path, key))
}
}
walk(s, "")
sort.Strings(out)
return out
}
func joinPath(parent, key string) string {
if parent == "" {
return key
}
return parent + "." + key
}
func displayPath(path string) string {
if path == "" {
return "(root)"
}
return path
}

View File

@ -0,0 +1,177 @@
package configschema
import (
"fmt"
"github.com/Tencent/WeKnora/internal/utils"
)
// RedactedPlaceholder replaces a set secret in responses. It equals
// types.RedactedSecretPlaceholder, which every other integration already
// sends, so the frontend treats both the same way.
const RedactedPlaceholder = "***"
// Seal returns a copy of value with every secret encrypted for storage. It
// uses the same AES-GCM format (enc:v1:) as the existing integration tables,
// so already-encrypted values pass through unchanged and values sealed here
// read back through utils.DecryptStoredSecret. Without SYSTEM_AES_KEY secrets
// stay in plaintext, as they do elsewhere.
func Seal(s *Schema, value map[string]any) (map[string]any, error) {
key := utils.GetAESKey()
return transformSecrets(s, value, func(path, secret string) (string, error) {
sealed, err := utils.EncryptAESGCM(secret, key)
if err != nil {
return "", fmt.Errorf("encrypt %s: %w", path, err)
}
return sealed, nil
})
}
// Open returns a copy of value with every secret decrypted. It fails when a
// secret cannot be decrypted (missing or rotated SYSTEM_AES_KEY), which is
// what a caller about to use the credential wants.
func Open(s *Schema, value map[string]any) (map[string]any, error) {
return transformSecrets(s, value, func(path, secret string) (string, error) {
plain, err := utils.DecryptStoredSecret(secret)
if err != nil {
return "", fmt.Errorf("decrypt %s: %w", path, err)
}
return plain, nil
})
}
// OpenLenient decrypts like Open but blanks secrets that cannot be decrypted
// and reports their paths, so a listing still loads and the UI can ask for
// the credential again.
func OpenLenient(s *Schema, value map[string]any) (map[string]any, []string) {
var failed []string
out, _ := transformSecrets(s, value, func(path, secret string) (string, error) {
plain, ok := utils.DecryptStoredSecretLenient(secret)
if !ok {
failed = append(failed, path)
}
return plain, nil
})
return out, failed
}
// Redact returns a copy of value with every set secret replaced by
// RedactedPlaceholder. Unset secrets stay empty so the UI can tell "not
// configured" from "configured".
func Redact(s *Schema, value map[string]any) map[string]any {
out, _ := transformSecrets(s, value, func(_, _ string) (string, error) {
return RedactedPlaceholder, nil
})
return out
}
// Merge applies an update to a stored configuration. Non-secret fields come
// from incoming as sent. A secret that incoming leaves out, empties or sends
// back as RedactedPlaceholder keeps its stored value, since the client never
// saw it; clearing a secret is an explicit operation elsewhere, as it is for
// the existing /credentials subresources.
func Merge(s *Schema, stored, incoming map[string]any) map[string]any {
out := deepCopyMap(incoming)
if out == nil {
out = map[string]any{}
}
mergeSecrets(s, stored, out)
return out
}
func mergeSecrets(s *Schema, stored, out map[string]any) {
for key, prop := range s.Properties {
switch {
case prop.Secret:
incoming, _ := out[key].(string)
if incoming != "" && incoming != RedactedPlaceholder {
continue
}
if old, ok := stored[key]; ok {
out[key] = old
} else {
delete(out, key)
}
case prop.Type == TypeObject && prop.containsSecret():
storedChild, _ := stored[key].(map[string]any)
outChild, ok := out[key].(map[string]any)
if !ok {
if storedChild == nil {
continue
}
outChild = map[string]any{}
out[key] = outChild
}
mergeSecrets(prop, storedChild, outChild)
}
}
}
// transformSecrets copies value and rewrites every non-empty secret string
// through fn.
func transformSecrets(
s *Schema, value map[string]any, fn func(path, secret string) (string, error),
) (map[string]any, error) {
out := deepCopyMap(value)
if out == nil {
return nil, nil
}
if err := walkSecrets(s, out, "", fn); err != nil {
return nil, err
}
return out, nil
}
func walkSecrets(s *Schema, obj map[string]any, path string, fn func(path, secret string) (string, error)) error {
for key, prop := range s.Properties {
v, ok := obj[key]
if !ok {
continue
}
fieldPath := joinPath(path, key)
if prop.Secret {
str, isStr := v.(string)
if !isStr || str == "" {
continue
}
rewritten, err := fn(fieldPath, str)
if err != nil {
return err
}
obj[key] = rewritten
continue
}
if child, isObj := v.(map[string]any); isObj && prop.Type == TypeObject {
if err := walkSecrets(prop, child, fieldPath, fn); err != nil {
return err
}
}
}
return nil
}
func deepCopyMap(m map[string]any) map[string]any {
if m == nil {
return nil
}
out := make(map[string]any, len(m))
for k, v := range m {
out[k] = deepCopyValue(v)
}
return out
}
func deepCopyValue(v any) any {
switch t := v.(type) {
case map[string]any:
return deepCopyMap(t)
case []any:
out := make([]any, len(t))
for i, item := range t {
out[i] = deepCopyValue(item)
}
return out
default:
return v
}
}

View File

@ -0,0 +1,245 @@
package configschema
import (
"encoding/json"
"fmt"
"math"
"net/mail"
"net/url"
"reflect"
"regexp"
"strings"
"unicode/utf8"
)
// Error codes a FieldError carries. The frontend maps them to messages.
const (
CodeRequired = "required"
CodeType = "type"
CodeEnum = "enum"
CodeMinLength = "min_length"
CodeMaxLength = "max_length"
CodePattern = "pattern"
CodeMinimum = "minimum"
CodeMaximum = "maximum"
CodeFormat = "format"
)
// FieldError is one problem with one field. Path is dotted ("auth.token")
// with "[i]" for array items.
type FieldError struct {
Path string `json:"path"`
Code string `json:"code"`
Message string `json:"message"`
}
// FieldErrors is every problem Validate found.
type FieldErrors []FieldError
func (e FieldErrors) Error() string {
parts := make([]string, len(e))
for i, fe := range e {
parts[i] = fe.Path + ": " + fe.Message
}
return "invalid configuration: " + strings.Join(parts, "; ")
}
// Validate checks a configuration against its schema and returns every
// problem, or nil. Fields the schema does not declare are allowed, so a
// configuration written by a newer version still validates. A required field
// hidden by x-visible-if is not required.
func Validate(s *Schema, value map[string]any) FieldErrors {
return ValidateInContext(s, value, nil)
}
// ValidateInContext is Validate for a configuration that lives inside a larger
// object: x-visible-if keys starting with "$" ("$mode") are read from ctx
// (without the "$") instead of from sibling fields. An IM channel's
// credentials depend on the channel's mode this way.
func ValidateInContext(s *Schema, value, ctx map[string]any) FieldErrors {
var errs FieldErrors
v := &validator{ctx: ctx, errs: &errs}
v.object(s, value, "")
if len(errs) == 0 {
return nil
}
return errs
}
// validator carries the context through one validation.
type validator struct {
ctx map[string]any
errs *FieldErrors
}
func (vd *validator) object(s *Schema, value map[string]any, path string) {
errs := vd.errs
required := make(map[string]bool, len(s.Required))
for _, k := range s.Required {
required[k] = true
}
for _, key := range s.OrderedKeys() {
prop := s.Properties[key]
if !visible(prop, value, vd.ctx) {
continue
}
fieldPath := joinPath(path, key)
val, present := value[key]
if !present || val == nil || val == "" {
if required[key] {
*errs = append(*errs, FieldError{fieldPath, CodeRequired, "is required"})
}
continue
}
vd.value(prop, val, fieldPath)
}
}
// visible evaluates x-visible-if against sibling values, or against ctx for
// "$"-prefixed keys.
func visible(s *Schema, siblings, ctx map[string]any) bool {
for key, want := range s.VisibleIf {
got := siblings[key]
if name, fromCtx := strings.CutPrefix(key, "$"); fromCtx {
got = ctx[name]
}
if !looselyEqual(got, want) {
return false
}
}
return true
}
func (vd *validator) value(s *Schema, v any, path string) {
add := func(code, format string, args ...any) {
*vd.errs = append(*vd.errs, FieldError{path, code, fmt.Sprintf(format, args...)})
}
switch s.Type {
case TypeObject:
obj, ok := v.(map[string]any)
if !ok {
add(CodeType, "must be an object")
return
}
vd.object(s, obj, path)
return
case TypeArray:
items, ok := v.([]any)
if !ok {
add(CodeType, "must be an array")
return
}
for i, item := range items {
vd.value(s.Items, item, fmt.Sprintf("%s[%d]", path, i))
}
return
case TypeString:
str, ok := v.(string)
if !ok {
add(CodeType, "must be a string")
return
}
validateString(s, str, add)
case TypeNumber, TypeInteger:
n, ok := toFloat(v)
if !ok {
add(CodeType, "must be a number")
return
}
if s.Type == TypeInteger && n != math.Trunc(n) {
add(CodeType, "must be an integer")
return
}
if s.Minimum != nil && n < *s.Minimum {
add(CodeMinimum, "must be at least %v", *s.Minimum)
}
if s.Maximum != nil && n > *s.Maximum {
add(CodeMaximum, "must be at most %v", *s.Maximum)
}
case TypeBoolean:
if _, ok := v.(bool); !ok {
add(CodeType, "must be true or false")
return
}
}
if !allowedChoice(s, v) {
add(CodeEnum, "is not one of the allowed values")
}
}
func validateString(s *Schema, str string, add func(code, format string, args ...any)) {
if s.Secret && str == RedactedPlaceholder {
// An unchanged secret: nothing to check about the stored value.
return
}
n := utf8.RuneCountInString(str)
if s.MinLength != nil && n < *s.MinLength {
add(CodeMinLength, "must be at least %d characters", *s.MinLength)
}
if s.MaxLength != nil && n > *s.MaxLength {
add(CodeMaxLength, "must be at most %d characters", *s.MaxLength)
}
if s.Pattern != "" {
if re, err := regexp.Compile(s.Pattern); err == nil && !re.MatchString(str) {
add(CodePattern, "does not match the expected format")
}
}
switch s.Format {
case "uri":
if u, err := url.Parse(str); err != nil || u.Scheme == "" || u.Host == "" {
add(CodeFormat, "must be an absolute URL")
}
case "email":
if _, err := mail.ParseAddress(str); err != nil {
add(CodeFormat, "must be an email address")
}
}
}
func allowedChoice(s *Schema, v any) bool {
if len(s.Enum) == 0 && len(s.OneOf) == 0 {
return true
}
for _, e := range s.Enum {
if looselyEqual(e, v) {
return true
}
}
for _, c := range s.OneOf {
if looselyEqual(c.Const, v) {
return true
}
}
return false
}
// looselyEqual compares decoded JSON values, treating all numeric kinds as
// equal when their values are.
func looselyEqual(a, b any) bool {
if fa, ok := toFloat(a); ok {
fb, ok := toFloat(b)
return ok && fa == fb
}
return reflect.DeepEqual(a, b)
}
func toFloat(v any) (float64, bool) {
switch n := v.(type) {
case float64:
return n, true
case float32:
return float64(n), true
case int:
return float64(n), true
case int64:
return float64(n), true
case int32:
return float64(n), true
case uint64:
return float64(n), true
case json.Number:
f, err := n.Float64()
return f, err == nil
}
return 0, false
}

View File

@ -0,0 +1,61 @@
package driver
import (
"context"
"errors"
"os"
"time"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
)
// Builtin serves plugins compiled into WeKnora: there is nothing to start,
// every node runs them in process, and they are ready as long as the node is.
type Builtin struct {
node string
started time.Time
lookup func(pluginID string) (*manifest.Manifest, bool)
}
// NewBuiltin returns the builtin driver. lookup finds a registered plugin.
func NewBuiltin(lookup func(pluginID string) (*manifest.Manifest, bool)) *Builtin {
node, err := os.Hostname()
if err != nil || node == "" {
node = "local"
}
return &Builtin{node: node, started: time.Now(), lookup: lookup}
}
// Type implements Driver.
func (b *Builtin) Type() manifest.RuntimeType { return manifest.RuntimeBuiltin }
// Ensure implements Driver. Builtins are ready by construction; anything else
// is a misrouted manifest.
func (b *Builtin) Ensure(_ context.Context, m *manifest.Manifest) error {
if !m.Builtin {
return errors.New("the builtin driver only runs builtin plugins")
}
return nil
}
// Remove implements Driver. Builtins cannot be removed, only disabled.
func (b *Builtin) Remove(context.Context, string, string) error {
return errors.New("builtin plugins cannot be removed")
}
// Resolve implements Driver.
func (b *Builtin) Resolve(_ context.Context, pluginID string, _ uint64) (Endpoint, error) {
if _, ok := b.lookup(pluginID); !ok {
return Endpoint{}, errors.New("unknown builtin plugin")
}
return Endpoint{Kind: EndpointInProcess}, nil
}
// Status implements Driver: one ready instance, this node.
func (b *Builtin) Status(_ context.Context, pluginID string) ([]InstanceStatus, error) {
m, ok := b.lookup(pluginID)
if !ok {
return nil, errors.New("unknown builtin plugin")
}
return []InstanceStatus{{Node: b.node, Version: m.Version, State: StateReady, UpdatedAt: b.started}}, nil
}

View File

@ -0,0 +1,100 @@
// Package driver defines how plugin code is run and reached. A driver turns a
// plugin's manifest into running instances (a child process of the plugin
// host, a remote URL, a Kubernetes Deployment) and tells callers where to send
// a request. Only the builtin driver exists today; the interface is fixed now
// so the host, remote and kubernetes drivers slot in without touching callers.
package driver
import (
"context"
"fmt"
"sync"
"time"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
)
// EndpointKind says how to reach a plugin instance.
type EndpointKind string
const (
// EndpointInProcess means the code is compiled into this process.
EndpointInProcess EndpointKind = "in-process"
// EndpointUnix is a unix socket of a child process on this node.
EndpointUnix EndpointKind = "unix"
// EndpointHTTP is an HTTP(S) base URL (plugin host gateway or remote).
EndpointHTTP EndpointKind = "http"
)
// Endpoint is where one request to a plugin goes.
type Endpoint struct {
Kind EndpointKind `json:"kind"`
Address string `json:"address,omitempty"`
}
// InstanceState is the health of one running instance.
type InstanceState string
// Instance states, from launch to shutdown.
const (
// StateStarting: launched, not yet passing health checks.
StateStarting InstanceState = "starting"
// StateReady: serving requests.
StateReady InstanceState = "ready"
// StateDegraded: running but failing health checks.
StateDegraded InstanceState = "degraded"
// StateStopped: not running.
StateStopped InstanceState = "stopped"
)
// InstanceStatus reports one instance of a plugin, for the plugin center.
type InstanceStatus struct {
// Node is the WeKnora node or plugin host running the instance.
Node string `json:"node"`
Version string `json:"version"`
State InstanceState `json:"state"`
Error string `json:"error,omitempty"`
UpdatedAt time.Time `json:"updatedAt"`
}
// Driver runs plugins of one runtime type.
type Driver interface {
// Type is the manifest runtime.type this driver serves.
Type() manifest.RuntimeType
// Ensure brings the plugin's current version to a runnable state. It is
// idempotent: reconciling calls it again on every pass.
Ensure(ctx context.Context, m *manifest.Manifest) error
// Remove stops and cleans up one version of a plugin.
Remove(ctx context.Context, pluginID, version string) error
// Resolve picks the endpoint for one request, balancing across
// instances. tenantID matters to drivers that isolate tenants.
Resolve(ctx context.Context, pluginID string, tenantID uint64) (Endpoint, error)
// Status lists the plugin's instances.
Status(ctx context.Context, pluginID string) ([]InstanceStatus, error)
}
// Set holds one driver per runtime type.
type Set struct {
mu sync.RWMutex
drivers map[manifest.RuntimeType]Driver
}
// NewSet returns a Set holding the given drivers.
func NewSet(drivers ...Driver) *Set {
s := &Set{drivers: make(map[manifest.RuntimeType]Driver)}
for _, d := range drivers {
s.drivers[d.Type()] = d
}
return s
}
// For returns the driver for a runtime type.
func (s *Set) For(t manifest.RuntimeType) (Driver, error) {
s.mu.RLock()
defer s.mu.RUnlock()
d, ok := s.drivers[t]
if !ok {
return nil, fmt.Errorf("no driver for runtime %q in this deployment", t)
}
return d, nil
}

View File

@ -0,0 +1,47 @@
package driver
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
)
func TestBuiltinDriver(t *testing.T) {
plugins := map[string]*manifest.Manifest{
"weknora.bing": {ID: "weknora.bing", Version: "0.8.2", Builtin: true},
}
d := NewBuiltin(func(id string) (*manifest.Manifest, bool) { m, ok := plugins[id]; return m, ok })
ctx := context.Background()
if err := d.Ensure(ctx, plugins["weknora.bing"]); err != nil {
t.Fatalf("Ensure builtin: %v", err)
}
if err := d.Ensure(ctx, &manifest.Manifest{ID: "acme.x"}); err == nil {
t.Fatal("the builtin driver must refuse non-builtin manifests")
}
if err := d.Remove(ctx, "weknora.bing", "0.8.2"); err == nil {
t.Fatal("builtins cannot be removed")
}
ep, err := d.Resolve(ctx, "weknora.bing", 1)
if err != nil || ep.Kind != EndpointInProcess {
t.Fatalf("Resolve = %+v, %v", ep, err)
}
if _, err := d.Resolve(ctx, "weknora.nope", 1); err == nil {
t.Fatal("unknown plugin must not resolve")
}
st, err := d.Status(ctx, "weknora.bing")
if err != nil || len(st) != 1 || st[0].State != StateReady || st[0].Version != "0.8.2" || st[0].Node == "" {
t.Fatalf("Status = %+v, %v", st, err)
}
}
func TestSet(t *testing.T) {
s := NewSet(NewBuiltin(func(string) (*manifest.Manifest, bool) { return nil, false }))
if d, err := s.For(manifest.RuntimeBuiltin); err != nil || d.Type() != manifest.RuntimeBuiltin {
t.Fatalf("For(builtin) = %v, %v", d, err)
}
if _, err := s.For(manifest.RuntimeHost); err == nil {
t.Fatal("no host driver is installed yet")
}
}

View File

@ -0,0 +1,276 @@
// Package manifest defines the plugin manifest: what a plugin is, how it runs,
// what it may touch and what it contributes. Builtin capabilities are
// described with the same type, so the rest of WeKnora sees one shape whether
// a connector is compiled in or shipped by a third party.
package manifest
import (
"bytes"
"errors"
"fmt"
"regexp"
"strings"
"golang.org/x/mod/semver"
"gopkg.in/yaml.v3"
)
// SchemaVersion is the manifest format version this build understands.
const SchemaVersion = 1
// BuiltinPublisher is the publisher of every plugin compiled into WeKnora.
// Other manifests may not claim it.
const BuiltinPublisher = "weknora"
// RuntimeType says where a plugin's code runs.
type RuntimeType string
const (
// RuntimeBuiltin runs compiled into WeKnora. Only builtin manifests use it.
RuntimeBuiltin RuntimeType = "builtin"
// RuntimeDeclarative has no code; WeKnora interprets the manifest itself.
RuntimeDeclarative RuntimeType = "declarative"
// RuntimeHost runs as a child process of the WeKnora plugin host.
RuntimeHost RuntimeType = "host"
// RuntimeRemote is an HTTP service somewhere else, registered by URL.
RuntimeRemote RuntimeType = "remote"
// RuntimeKubernetes runs as a Deployment + Service managed through the k8s API.
RuntimeKubernetes RuntimeType = "kubernetes"
)
// Manifest is a plugin's plugin.yaml.
type Manifest struct {
SchemaVersion int `json:"schemaVersion" yaml:"schemaVersion"`
ID string `json:"id" yaml:"id"`
Version string `json:"version" yaml:"version"`
// APIVersion is the extension protocol a code plugin speaks
// (weknora.plugin/v1). Builtin and declarative plugins leave it empty.
APIVersion string `json:"apiVersion,omitempty" yaml:"apiVersion"`
Engines Engines `json:"engines,omitzero" yaml:"engines"`
Name LocalizedText `json:"name" yaml:"name"`
Description LocalizedText `json:"description,omitzero" yaml:"description"`
Publisher Publisher `json:"publisher" yaml:"publisher"`
Icon string `json:"icon,omitempty" yaml:"icon"`
Homepage string `json:"homepage,omitempty" yaml:"homepage"`
License string `json:"license,omitempty" yaml:"license"`
// Builtin marks a plugin compiled into WeKnora. It cannot be set from a
// manifest file.
Builtin bool `json:"builtin,omitempty" yaml:"-"`
// Required marks a builtin a tenant may not disable (the core agent
// tools, the default parser).
Required bool `json:"required,omitempty" yaml:"-"`
Runtime Runtime `json:"runtime" yaml:"runtime"`
Permissions Permissions `json:"permissions,omitzero" yaml:"permissions"`
Config ConfigSchemas `json:"config,omitzero" yaml:"config"`
Contributes Contributions `json:"contributes" yaml:"contributes"`
}
// Engines constrains which WeKnora versions a plugin runs on.
type Engines struct {
// WeKnora is a semver range such as ">=0.10.0 <1.0.0".
WeKnora string `json:"weknora,omitempty" yaml:"weknora"`
}
// Publisher identifies who ships a plugin. ID is the first segment of the
// plugin ID.
type Publisher struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name,omitempty" yaml:"name"`
URL string `json:"url,omitempty" yaml:"url"`
}
// Runtime says how a plugin's code runs.
type Runtime struct {
Type RuntimeType `json:"type" yaml:"type"`
// Kind is the process runtime for host plugins: binary, python or node.
Kind string `json:"kind,omitempty" yaml:"kind"`
// Entry is the command inside the package, with {os} and {arch}
// placeholders for binaries.
Entry string `json:"entry,omitempty" yaml:"entry"`
// Singleton allows only one live instance across the cluster (long-lived
// connections such as an IM WebSocket).
Singleton bool `json:"singleton,omitempty" yaml:"singleton"`
Resources *Resources `json:"resources,omitempty" yaml:"resources"`
}
// Resources caps a host plugin process.
type Resources struct {
CPU string `json:"cpu,omitempty" yaml:"cpu"`
Memory string `json:"memory,omitempty" yaml:"memory"`
}
// Permissions is what a plugin asks for; an administrator confirms it at
// install time.
type Permissions struct {
// Egress lists host patterns the plugin may reach ("*.atlassian.net").
Egress []string `json:"egress,omitempty" yaml:"egress"`
// HostAPI lists WeKnora API scopes the plugin may call back with.
HostAPI []string `json:"hostApi,omitempty" yaml:"hostApi"`
// Events lists asynchronous events the plugin subscribes to.
Events []string `json:"events,omitempty" yaml:"events"`
}
// ConfigSchemas points at the JSON Schemas of plugin-level configuration.
type ConfigSchemas struct {
System string `json:"system,omitempty" yaml:"system"`
Tenant string `json:"tenant,omitempty" yaml:"tenant"`
}
// Contributions maps each extension point to what the plugin provides there.
type Contributions map[Point][]Contribution
// Contribution is one capability a plugin provides at one extension point,
// such as one connector.
type Contribution struct {
// ID is local to the plugin; QualifiedID adds the plugin ID.
ID string `json:"id" yaml:"id"`
Name LocalizedText `json:"name" yaml:"name"`
Description LocalizedText `json:"description,omitzero" yaml:"description"`
Icon string `json:"icon,omitempty" yaml:"icon"`
// Aliases are the short names builtins were stored under before plugins
// existed ("feishu"). Rows keep them, so lookups must keep resolving
// them. Only builtins may declare aliases.
Aliases []string `json:"aliases,omitempty" yaml:"-"`
Capabilities []string `json:"capabilities,omitempty" yaml:"capabilities"`
// Order sorts contributions of one point in the UI (lower first); ties
// keep registration order.
Order int `json:"order,omitempty" yaml:"order"`
// InstanceSchema points at the JSON Schema of one instance's
// configuration (one data source, one IM channel).
InstanceSchema string `json:"instanceSchema,omitempty" yaml:"instanceSchema"`
// Extra carries point-specific metadata the generic fields do not cover.
Extra map[string]any `json:"extra,omitempty" yaml:"extra"`
}
// QualifiedID is the cluster-wide ID of a contribution: "<plugin>/<local>".
func QualifiedID(pluginID, localID string) string {
return pluginID + "/" + localID
}
var (
pluginIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}\.[a-z0-9][a-z0-9-]{0,62}$`)
contributionIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]{0,127}$`)
)
// isStrictSemver accepts full MAJOR.MINOR.PATCH versions with an optional
// pre-release and build suffix. x/mod/semver alone also accepts "1.0".
func isStrictSemver(v string) bool {
withoutBuild, _, _ := strings.Cut(v, "+")
return semver.IsValid("v"+v) && semver.Canonical("v"+v) == "v"+withoutBuild
}
// HasValidVersion reports whether Version is a full semantic version.
func (m *Manifest) HasValidVersion() bool { return isStrictSemver(m.Version) }
// Parse decodes a manifest from YAML (JSON is accepted too) and validates it.
// Unknown keys are rejected so a typo does not silently drop a setting.
func Parse(data []byte) (*Manifest, error) {
dec := yaml.NewDecoder(bytes.NewReader(data))
dec.KnownFields(true)
var m Manifest
if err := dec.Decode(&m); err != nil {
return nil, fmt.Errorf("decode manifest: %w", err)
}
if err := m.Validate(); err != nil {
return nil, err
}
return &m, nil
}
// Validate checks a manifest. It reports every problem at once so an author
// fixes them in one pass.
func (m *Manifest) Validate() error {
var errs []error
add := func(format string, args ...any) { errs = append(errs, fmt.Errorf(format, args...)) }
if m.SchemaVersion != SchemaVersion {
add("schemaVersion must be %d, got %d", SchemaVersion, m.SchemaVersion)
}
if !pluginIDPattern.MatchString(m.ID) {
add("id %q must look like <publisher>.<name> in lowercase letters, digits and dashes", m.ID)
}
publisher, _, _ := strings.Cut(m.ID, ".")
if m.Publisher.ID != publisher {
add("publisher.id %q must match the id prefix %q", m.Publisher.ID, publisher)
}
if publisher == BuiltinPublisher && !m.Builtin {
add("publisher %q is reserved for builtin plugins", BuiltinPublisher)
}
if !isStrictSemver(m.Version) {
add("version %q is not a semantic version", m.Version)
}
if m.Name.IsZero() {
add("name is required")
}
m.validateRuntime(add)
m.validateContributions(add)
return errors.Join(errs...)
}
func (m *Manifest) validateRuntime(add func(string, ...any)) {
switch m.Runtime.Type {
case RuntimeBuiltin:
if !m.Builtin {
add("runtime.type %q is reserved for builtin plugins", RuntimeBuiltin)
}
case RuntimeDeclarative, RuntimeRemote, RuntimeKubernetes:
case RuntimeHost:
switch m.Runtime.Kind {
case "binary", "python", "node":
default:
add("runtime.kind must be binary, python or node for host plugins, got %q", m.Runtime.Kind)
}
if m.Runtime.Entry == "" {
add("runtime.entry is required for host plugins")
}
default:
add("runtime.type %q is not one of builtin, declarative, host, remote, kubernetes", m.Runtime.Type)
}
}
func (m *Manifest) validateContributions(add func(string, ...any)) {
if len(m.Contributes) == 0 {
add("contributes must declare at least one contribution")
}
for point := range m.Contributes {
if _, ok := LookupPoint(point); !ok {
add("contributes.%s is not a known extension point", point)
}
}
for _, info := range points {
point := info.Point
list, ok := m.Contributes[point]
if !ok {
continue
}
if !info.ThirdParty && !m.Builtin {
add("contributes.%s is not open to third-party plugins yet", point)
}
seen := make(map[string]bool, len(list))
for i, c := range list {
where := fmt.Sprintf("contributes.%s[%d]", point, i)
if !contributionIDPattern.MatchString(c.ID) {
add("%s.id %q must be lowercase letters, digits, '_', '-' or '.'", where, c.ID)
}
if seen[c.ID] {
add("%s.id %q is declared twice", where, c.ID)
}
seen[c.ID] = true
if c.Name.IsZero() {
add("%s.name is required", where)
}
if len(c.Aliases) > 0 && !m.Builtin {
add("%s.aliases may only be declared by builtin plugins", where)
}
for _, alias := range c.Aliases {
// Aliases share the ID alphabet, which has no '/', so an
// alias can never shadow a qualified ID.
if !contributionIDPattern.MatchString(alias) {
add("%s alias %q must be lowercase letters, digits, '_', '-' or '.'", where, alias)
}
}
}
}
}

View File

@ -0,0 +1,186 @@
package manifest
import (
"encoding/json"
"strings"
"testing"
)
const jiraManifest = `
schemaVersion: 1
id: acme.jira
version: 1.2.0
apiVersion: weknora.plugin/v1
engines: { weknora: ">=0.10.0" }
name: { zh-CN: Jira 问题, en-US: Jira }
publisher: { id: acme, name: ACME Inc. }
runtime: { type: host, kind: binary, entry: "bin/{os}-{arch}/jira" }
permissions:
egress: ["*.atlassian.net"]
contributes:
connectors:
- id: jira
name: Jira
capabilities: [incremental]
instanceSchema: schemas/connector.json
`
// openToThirdParty opens a point for the duration of a test; no point is open
// to third parties in P0, but the validation path still needs covering.
func openToThirdParty(t *testing.T, p Point) {
t.Helper()
saved := points
points = make([]PointInfo, len(saved))
copy(points, saved)
for i := range points {
if points[i].Point == p {
points[i].ThirdParty = true
}
}
t.Cleanup(func() { points = saved })
}
func TestParseValidManifest(t *testing.T) {
openToThirdParty(t, PointConnectors)
m, err := Parse([]byte(jiraManifest))
if err != nil {
t.Fatalf("Parse: %v", err)
}
if m.ID != "acme.jira" || m.Runtime.Type != RuntimeHost {
t.Fatalf("unexpected manifest: %+v", m)
}
if got := m.Name.Resolve("zh-CN"); got != "Jira 问题" {
t.Fatalf("zh-CN name = %q", got)
}
if got := m.Name.Default; got != "Jira" {
t.Fatalf("default name = %q, want the en-US variant", got)
}
c := m.Contributes[PointConnectors]
if len(c) != 1 || c[0].ID != "jira" || c[0].Name.Default != "Jira" {
t.Fatalf("unexpected connectors: %+v", c)
}
}
func TestParseRejectsUnknownKeys(t *testing.T) {
openToThirdParty(t, PointConnectors)
_, err := Parse([]byte(jiraManifest + "\nruntimee: {}\n"))
if err == nil || !strings.Contains(err.Error(), "runtimee") {
t.Fatalf("want unknown-key error, got %v", err)
}
}
func TestValidateReportsEveryProblem(t *testing.T) {
m := &Manifest{
SchemaVersion: 2,
ID: "Bad_ID",
Version: "1.0",
Runtime: Runtime{Type: RuntimeHost},
Contributes: Contributions{
"widgets": {{ID: "x", Name: Text("X", nil)}},
PointConnectors: {
{ID: "dup", Name: Text("A", nil), Aliases: []string{"old"}},
{ID: "dup"},
},
},
}
err := m.Validate()
if err == nil {
t.Fatal("want errors")
}
for _, want := range []string{
"schemaVersion must be 1",
`id "Bad_ID"`,
`version "1.0"`,
"name is required",
"runtime.kind",
"runtime.entry",
"contributes.widgets is not a known extension point",
"is not open to third-party plugins yet",
`"dup" is declared twice`,
"contributes.connectors[1].name is required",
"aliases may only be declared by builtin plugins",
} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not mention %q", err, want)
}
}
}
func TestBuiltinPublisherIsReserved(t *testing.T) {
m := &Manifest{
SchemaVersion: SchemaVersion,
ID: "weknora.fake",
Version: "1.0.0",
Name: Text("Fake", nil),
Publisher: Publisher{ID: BuiltinPublisher},
Runtime: Runtime{Type: RuntimeBuiltin},
Contributes: Contributions{PointTools: {{ID: "t", Name: Text("T", nil)}}},
}
err := m.Validate()
if err == nil || !strings.Contains(err.Error(), "reserved for builtin plugins") {
t.Fatalf("want reserved-publisher error, got %v", err)
}
m.Builtin = true
if err := m.Validate(); err != nil {
t.Fatalf("builtin manifest should validate: %v", err)
}
}
func TestStrictSemver(t *testing.T) {
for v, want := range map[string]bool{
"1.2.0": true, "1.2.0-beta.1": true, "1.2.0+build.5": true,
"1.2": false, "v1.2.0": false, "01.2.0": false, "": false,
} {
if got := isStrictSemver(v); got != want {
t.Errorf("isStrictSemver(%q) = %v, want %v", v, got, want)
}
}
}
func TestLocalizedTextResolve(t *testing.T) {
text := Text("Feishu", map[string]string{"zh-CN": "飞书", "ja-JP": ""})
cases := map[string]string{
"zh-CN": "飞书",
"zh-TW": "飞书", // same language
"zh": "飞书",
"en-US": "Feishu",
"ja-JP": "Feishu", // empty variants are dropped
"": "Feishu",
}
for locale, want := range cases {
if got := text.Resolve(locale); got != want {
t.Errorf("Resolve(%q) = %q, want %q", locale, got, want)
}
}
}
func TestLocalizedTextJSONRoundTrip(t *testing.T) {
data, err := json.Marshal(Text("Feishu", map[string]string{"zh-CN": "飞书"}))
if err != nil {
t.Fatal(err)
}
if string(data) != `{"default":"Feishu","zh-CN":"飞书"}` {
t.Fatalf("marshal = %s", data)
}
var back LocalizedText
if err := json.Unmarshal(data, &back); err != nil {
t.Fatal(err)
}
if back.Default != "Feishu" || back.Locales["zh-CN"] != "飞书" {
t.Fatalf("round trip = %+v", back)
}
var plain LocalizedText
if err := json.Unmarshal([]byte(`"Jira"`), &plain); err != nil || plain.Default != "Jira" {
t.Fatalf("plain string = %+v, %v", plain, err)
}
}
func TestContributionOmitsEmptyDescription(t *testing.T) {
data, err := json.Marshal(Contribution{ID: "x", Name: Text("X", nil)})
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), "description") {
t.Fatalf("empty description should be omitted: %s", data)
}
}

View File

@ -0,0 +1,55 @@
package manifest
// Point names an extension point: a kind of capability a plugin contributes.
// The string is also the key under `contributes` in a manifest.
type Point string
// Extension points with a builtin implementation today. Points the design
// opens later (mcpServers, skills, events, pipelineHooks, ui, ...) are added
// here when their first contribution lands, so a manifest can never declare a
// point nothing consumes.
const (
PointModelVendors Point = "modelVendors"
PointConnectors Point = "connectors"
PointIMChannels Point = "imChannels"
PointWebSearch Point = "webSearch"
PointTools Point = "tools"
PointParsers Point = "parsers"
)
// PointInfo describes an extension point.
type PointInfo struct {
Point Point `json:"point"`
// ThirdParty reports whether plugins other than builtins may contribute
// to this point yet. Builtins always may.
ThirdParty bool `json:"thirdParty"`
}
// points lists every known extension point in display order. Vector stores,
// object storage and sandboxes are deliberately absent: they are
// infrastructure owned by WeKnora itself, not extension points.
var points = []PointInfo{
{Point: PointModelVendors},
{Point: PointConnectors},
{Point: PointIMChannels},
{Point: PointWebSearch},
{Point: PointTools},
{Point: PointParsers},
}
// Points returns every known extension point in display order.
func Points() []PointInfo {
out := make([]PointInfo, len(points))
copy(out, points)
return out
}
// LookupPoint returns the info for a point name.
func LookupPoint(p Point) (PointInfo, bool) {
for _, info := range points {
if info.Point == p {
return info, true
}
}
return PointInfo{}, false
}

View File

@ -0,0 +1,129 @@
package manifest
import (
"encoding/json"
"errors"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// defaultLocaleKey is the key the default text travels under in the object
// form, next to locale keys such as "zh-CN".
const defaultLocaleKey = "default"
// LocalizedText is user-facing text with optional per-locale variants.
//
// Manifests may write it as a plain string ("Jira") or as an object keyed by
// locale ({"zh-CN": "飞书", "en-US": "Feishu"}). An object without a
// "default" key falls back to en-US, then to the first locale in sort order,
// so every non-empty value has a default. The API always emits the object
// form, which keeps the frontend type to a single shape.
type LocalizedText struct {
Default string
Locales map[string]string
}
// Text builds a LocalizedText from a default and optional locale variants.
// Empty variants are dropped.
func Text(def string, locales map[string]string) LocalizedText {
t := LocalizedText{Default: def}
for locale, v := range locales {
if v == "" {
continue
}
if t.Locales == nil {
t.Locales = make(map[string]string, len(locales))
}
t.Locales[locale] = v
}
return t
}
// IsZero reports whether the text carries nothing at all.
func (t LocalizedText) IsZero() bool {
return t.Default == "" && len(t.Locales) == 0
}
// Resolve returns the text for a locale: the exact locale, then any variant of
// the same language ("zh" for "zh-TW"), then the default.
func (t LocalizedText) Resolve(locale string) string {
if v, ok := t.Locales[locale]; ok {
return v
}
if lang, _, _ := strings.Cut(locale, "-"); lang != "" {
for _, key := range t.sortedLocales() {
if keyLang, _, _ := strings.Cut(key, "-"); strings.EqualFold(keyLang, lang) {
return t.Locales[key]
}
}
}
return t.Default
}
func (t LocalizedText) sortedLocales() []string {
keys := make([]string, 0, len(t.Locales))
for k := range t.Locales {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// MarshalJSON emits the object form: {"default": ..., "<locale>": ...}.
func (t LocalizedText) MarshalJSON() ([]byte, error) {
out := make(map[string]string, len(t.Locales)+1)
for k, v := range t.Locales {
out[k] = v
}
out[defaultLocaleKey] = t.Default
return json.Marshal(out)
}
// UnmarshalJSON accepts either a string or a locale object.
func (t *LocalizedText) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err == nil {
*t = LocalizedText{Default: s}
return nil
}
var m map[string]string
if err := json.Unmarshal(data, &m); err != nil {
return errors.New("localized text must be a string or an object of locale strings")
}
*t = fromMap(m)
return nil
}
// UnmarshalYAML accepts either a scalar or a mapping of locale strings.
func (t *LocalizedText) UnmarshalYAML(node *yaml.Node) error {
switch node.Kind {
case yaml.ScalarNode:
*t = LocalizedText{Default: node.Value}
return nil
case yaml.MappingNode:
var m map[string]string
if err := node.Decode(&m); err != nil {
return err
}
*t = fromMap(m)
return nil
default:
return errors.New("localized text must be a string or a mapping of locale strings")
}
}
func fromMap(m map[string]string) LocalizedText {
def := m[defaultLocaleKey]
delete(m, defaultLocaleKey)
t := Text(def, m)
if t.Default == "" {
if v, ok := t.Locales["en-US"]; ok {
t.Default = v
} else if keys := t.sortedLocales(); len(keys) > 0 {
t.Default = t.Locales[keys[0]]
}
}
return t
}

View File

@ -0,0 +1,154 @@
// Package registry indexes the plugins a WeKnora process knows about and the
// contributions they make, so callers can list everything at one extension
// point or resolve one contribution by ID or legacy alias.
package registry
import (
"fmt"
"sort"
"sync"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
)
// Entry is one contribution together with the plugin that provides it.
type Entry struct {
Point manifest.Point
// PluginID is the providing plugin; QualifiedID is "<plugin>/<local>".
PluginID string
QualifiedID string
Contribution manifest.Contribution
seq int // registration order, the tie-breaker after Contribution.Order
}
// Registry is safe for concurrent use. Registered manifests must not be
// mutated afterwards; the registry hands out the same pointers.
type Registry struct {
mu sync.RWMutex
plugins map[string]*manifest.Manifest
entries map[manifest.Point][]*Entry
// index resolves qualified IDs and builtin aliases per point.
index map[manifest.Point]map[string]*Entry
seq int
}
// New returns an empty registry.
func New() *Registry {
return &Registry{
plugins: make(map[string]*manifest.Manifest),
entries: make(map[manifest.Point][]*Entry),
index: make(map[manifest.Point]map[string]*Entry),
}
}
// Register validates a manifest and adds it with all its contributions. It
// fails without side effects when the plugin ID is taken or a contribution ID
// or alias collides with one already registered at the same point.
func (r *Registry) Register(m *manifest.Manifest) error {
if err := m.Validate(); err != nil {
return fmt.Errorf("plugin %s: %w", m.ID, err)
}
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.plugins[m.ID]; ok {
return fmt.Errorf("plugin %s is already registered", m.ID)
}
// Check every key before touching the index so a failure leaves nothing
// half registered.
pending := make(map[manifest.Point]map[string]string)
for _, info := range manifest.Points() {
for _, c := range m.Contributes[info.Point] {
for _, key := range lookupKeys(m.ID, c) {
if owner, ok := r.index[info.Point][key]; ok {
return fmt.Errorf("%s %q of plugin %s collides with %s",
info.Point, key, m.ID, owner.QualifiedID)
}
if other, ok := pending[info.Point][key]; ok {
return fmt.Errorf("%s %q is claimed twice by plugin %s (%s)", info.Point, key, m.ID, other)
}
if pending[info.Point] == nil {
pending[info.Point] = make(map[string]string)
}
pending[info.Point][key] = c.ID
}
}
}
r.plugins[m.ID] = m
for _, info := range manifest.Points() {
for _, c := range m.Contributes[info.Point] {
r.seq++
e := &Entry{
Point: info.Point,
PluginID: m.ID,
QualifiedID: manifest.QualifiedID(m.ID, c.ID),
Contribution: c,
seq: r.seq,
}
r.entries[info.Point] = append(r.entries[info.Point], e)
if r.index[info.Point] == nil {
r.index[info.Point] = make(map[string]*Entry)
}
for _, key := range lookupKeys(m.ID, c) {
r.index[info.Point][key] = e
}
}
}
return nil
}
func lookupKeys(pluginID string, c manifest.Contribution) []string {
return append([]string{manifest.QualifiedID(pluginID, c.ID)}, c.Aliases...)
}
// Plugins returns every registered plugin sorted by ID.
func (r *Registry) Plugins() []*manifest.Manifest {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]*manifest.Manifest, 0, len(r.plugins))
for _, m := range r.plugins {
out = append(out, m)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// Plugin returns one plugin by ID.
func (r *Registry) Plugin(id string) (*manifest.Manifest, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
m, ok := r.plugins[id]
return m, ok
}
// Contributions returns every contribution at a point, sorted by
// Contribution.Order and then registration order.
func (r *Registry) Contributions(point manifest.Point) []Entry {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]Entry, 0, len(r.entries[point]))
for _, e := range r.entries[point] {
out = append(out, *e)
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].Contribution.Order != out[j].Contribution.Order {
return out[i].Contribution.Order < out[j].Contribution.Order
}
return out[i].seq < out[j].seq
})
return out
}
// Resolve finds a contribution by qualified ID ("acme.jira/jira") or by a
// builtin's legacy alias ("feishu").
func (r *Registry) Resolve(point manifest.Point, id string) (Entry, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
e, ok := r.index[point][id]
if !ok {
return Entry{}, false
}
return *e, true
}

View File

@ -0,0 +1,118 @@
package registry
import (
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/plugin/manifest"
)
func builtin(id string, contributes manifest.Contributions) *manifest.Manifest {
return &manifest.Manifest{
SchemaVersion: manifest.SchemaVersion,
ID: id,
Version: "1.0.0",
Name: manifest.Text(id, nil),
Publisher: manifest.Publisher{ID: manifest.BuiltinPublisher},
Builtin: true,
Runtime: manifest.Runtime{Type: manifest.RuntimeBuiltin},
Contributes: contributes,
}
}
func contribution(id string, order int, aliases ...string) manifest.Contribution {
return manifest.Contribution{ID: id, Name: manifest.Text(id, nil), Order: order, Aliases: aliases}
}
func TestRegisterAndResolve(t *testing.T) {
r := New()
feishu := builtin("weknora.feishu", manifest.Contributions{
manifest.PointConnectors: {
contribution("feishu", 2, "feishu"),
contribution("feishu_drive", 3, "feishu_drive"),
},
manifest.PointIMChannels: {contribution("feishu", 1, "feishu")},
})
notion := builtin("weknora.notion", manifest.Contributions{
manifest.PointConnectors: {contribution("notion", 1, "notion")},
})
for _, m := range []*manifest.Manifest{feishu, notion} {
if err := r.Register(m); err != nil {
t.Fatalf("Register(%s): %v", m.ID, err)
}
}
// The same alias may live at two different points.
for _, point := range []manifest.Point{manifest.PointConnectors, manifest.PointIMChannels} {
e, ok := r.Resolve(point, "feishu")
if !ok || e.QualifiedID != "weknora.feishu/feishu" || e.PluginID != "weknora.feishu" {
t.Fatalf("Resolve(%s, feishu) = %+v, %v", point, e, ok)
}
}
if _, ok := r.Resolve(manifest.PointConnectors, "weknora.notion/notion"); !ok {
t.Fatal("qualified ID should resolve")
}
if _, ok := r.Resolve(manifest.PointWebSearch, "feishu"); ok {
t.Fatal("alias must not leak across points")
}
var got []string
for _, e := range r.Contributions(manifest.PointConnectors) {
got = append(got, e.QualifiedID)
}
want := "weknora.notion/notion,weknora.feishu/feishu,weknora.feishu/feishu_drive"
if strings.Join(got, ",") != want {
t.Fatalf("connector order = %v, want %s", got, want)
}
var ids []string
for _, m := range r.Plugins() {
ids = append(ids, m.ID)
}
if strings.Join(ids, ",") != "weknora.feishu,weknora.notion" {
t.Fatalf("plugins = %v", ids)
}
}
func TestRegisterRejectsCollisionsAtomically(t *testing.T) {
r := New()
if err := r.Register(builtin("weknora.feishu", manifest.Contributions{
manifest.PointConnectors: {contribution("feishu", 0, "feishu")},
})); err != nil {
t.Fatal(err)
}
clash := builtin("weknora.lark", manifest.Contributions{
manifest.PointConnectors: {contribution("lark", 0, "lark"), contribution("other", 0, "feishu")},
})
err := r.Register(clash)
if err == nil || !strings.Contains(err.Error(), "collides with weknora.feishu/feishu") {
t.Fatalf("want collision error, got %v", err)
}
if _, ok := r.Plugin("weknora.lark"); ok {
t.Fatal("failed registration must not leave the plugin behind")
}
if _, ok := r.Resolve(manifest.PointConnectors, "lark"); ok {
t.Fatal("failed registration must not leave aliases behind")
}
if err := r.Register(builtin("weknora.feishu", manifest.Contributions{
manifest.PointTools: {contribution("x", 0)},
})); err == nil {
t.Fatal("duplicate plugin ID must be rejected")
}
self := builtin("weknora.self", manifest.Contributions{
manifest.PointTools: {contribution("a", 0, "same"), contribution("b", 0, "same")},
})
if err := r.Register(self); err == nil || !strings.Contains(err.Error(), "claimed twice") {
t.Fatalf("want self-collision error, got %v", err)
}
}
func TestRegisterValidates(t *testing.T) {
m := builtin("weknora.bad", manifest.Contributions{manifest.PointTools: {{ID: "Bad ID"}}})
if err := New().Register(m); err == nil {
t.Fatal("invalid manifest must be rejected")
}
}

Some files were not shown because too many files have changed in this diff Show More