feat: Enhance agent tool compatibility and knowledge base filtering

- Introduced a unified capability requirements system for agent tools, ensuring consistent filtering of knowledge bases based on their capabilities.
- Implemented derived `kb_filter` logic to streamline compatibility checks between agent tools and knowledge bases, reducing redundancy in configuration.
- Updated frontend components to reflect new filtering logic, including improved handling of empty states and user feedback when no compatible knowledge bases are available.
- Enhanced internationalization support by adding relevant messages for tool compatibility issues across multiple languages.
This commit is contained in:
wizardchen
2026-04-23 17:22:18 +08:00
committed by lyingbug
parent 04d9b76785
commit 4c906e0431
14 changed files with 728 additions and 105 deletions
+16 -10
View File
@@ -18,6 +18,14 @@
# none_of: KB must expose NONE of the listed capability names.
# Capability names: vector, keyword, wiki, graph, faq.
# An empty kb_filter (or kb_filter absent) means "any KB is allowed".
#
# NOTE: In the default "tool-driven" mode, the frontend DERIVES the any_of
# predicate from `config.allowed_tools` via `deriveKbFilterFromTools` (see
# `frontend/src/utils/tool-capabilities.ts`). You only need to write an
# explicit `kb_filter` here when the preset requires a business rule that
# can't be inferred from the tools alone (e.g. `none_of: [faq]` on
# data-analysis). Keeping the map lean avoids the "two sources of truth"
# drift that used to plague this file.
agent_type_presets:
# --------------------------------------------------------------------------
@@ -52,8 +60,7 @@ agent_type_presets:
retain_retrieval_history: false
faq_priority_enabled: true
kb_selection_mode: "all"
kb_filter:
any_of: ["vector", "keyword", "faq"]
# kb_filter derived from allowed_tools: any_of = [vector, keyword]
# --------------------------------------------------------------------------
# Wiki Q&A — graph-navigated wiki answering.
@@ -85,8 +92,7 @@ agent_type_presets:
- "final_answer"
retain_retrieval_history: false
kb_selection_mode: "all"
kb_filter:
all_of: ["wiki"]
# kb_filter derived from allowed_tools: any_of = [wiki]
# --------------------------------------------------------------------------
# Hybrid RAG + Wiki — single agent that orchestrates both indexes.
@@ -128,12 +134,11 @@ agent_type_presets:
# - KB has only chunks → fallback to pure RAG (see prompt's "Fallback rules")
# - KB has only wiki → fallback to wiki-only answering
# - FAQ KB → allowed; knowledge_search still works on FAQ chunks
# kb_filter derived from allowed_tools: any_of = [vector, keyword, wiki].
# We only require that the KB expose AT LEAST ONE retrievable surface so
# the agent has SOMETHING to call. KBs with zero indexing (e.g. graph-only
# or completely unindexed) are still excluded since no tool will return
# anything useful.
kb_filter:
any_of: ["vector", "keyword", "wiki"]
# --------------------------------------------------------------------------
# Data Analysis — SQL / statistics over tabular files (CSV / Excel) in the KB.
@@ -172,11 +177,12 @@ agent_type_presets:
kb_selection_mode: "all"
# data_schema / data_analysis tools read ChunkTypeTableSummary /
# ChunkTypeTableColumn chunks, which are produced by the normal RAG
# ingestion pipeline (vector / keyword indexing on). FAQ-type KBs don't
# ingest tabular data, and wiki-only KBs don't carry chunk-level table
# schemas, so both are incompatible.
# ingestion pipeline (vector / keyword indexing on). The any_of predicate
# is derived automatically from allowed_tools; we only need to add the
# FAQ exclusion here since it's a business rule the tool map can't express
# (FAQ KBs technically have vector/keyword chunks but they're Q&A pairs,
# not tabular data, so data_schema would produce garbage on them).
kb_filter:
any_of: ["vector", "keyword"]
none_of: ["faq"]
# --------------------------------------------------------------------------
+104 -10
View File
@@ -19,6 +19,12 @@ import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-
import { getConversationConfig, updateConversationConfig, type ConversationConfig } from '@/api/system';
import { useI18n } from 'vue-i18n';
import AttachmentUpload, { type AttachmentFile } from './AttachmentUpload.vue';
import {
kbSatisfiesToolRequirements,
deriveKbFilterFromTools,
toolsConsumeFiles,
type ScopeCapabilities,
} from '@/utils/tool-capabilities';
const route = useRoute();
const router = useRouter();
@@ -234,6 +240,54 @@ const agentSupportedFileTypes = computed(() => {
return currentAgentConfig.value?.supported_file_types || [];
});
// 智能体配置的工具列表,驱动 @ 菜单的 KB 兼容性过滤
const agentAllowedTools = computed<string[]>(() => {
if (!hasAgentConfig.value) return [];
return currentAgentConfig.value?.allowed_tools || [];
});
// 从 KB 对象里抽能力位,优先用 backend 显式的 capabilities 字段;否则回退到 indexing_strategy,
// 最后拿 kb.type === 'faq' 兜底。shared / owned / agent-scope 三路的 KB 响应结构一致。
const kbToScopeCaps = (kb: any): Partial<ScopeCapabilities> => {
if (kb?.capabilities) {
return {
vector: !!kb.capabilities.vector,
keyword: !!kb.capabilities.keyword,
wiki: !!kb.capabilities.wiki,
graph: !!kb.capabilities.graph,
faq: !!kb.capabilities.faq,
};
}
const s = kb?.indexing_strategy;
return {
vector: s ? !!s.vector_enabled : false,
keyword: s ? !!s.keyword_enabled : false,
wiki: s ? !!s.wiki_enabled : false,
graph: s ? !!s.graph_enabled : false,
faq: kb?.type === 'faq',
};
};
// "all" 模式 + 智能体工具有 KB 依赖时的兼容性过滤;'selected'/'none' 不在这里二次过滤
// (selected 由编辑器负责,none 已经空表)。
const isKbCompatibleWithAgent = (kb: any): boolean => {
if (!hasAgentConfig.value) return true;
if (agentKBSelectionMode.value !== 'all') return true;
return kbSatisfiesToolRequirements(kbToScopeCaps(kb), agentAllowedTools.value);
};
// 仅在用户没输入搜索词、且是因智能体工具兼容性把列表清空的场景展示专用空态文案
const mentionEmptyHint = computed(() => {
if (mentionQuery.value) return '';
if (!hasAgentConfig.value) return '';
if (agentKBSelectionMode.value !== 'all') return '';
// 列表为空 && 兼容性过滤器其实是有效的(否则"全部"不会被剔空)
if (mentionItems.value.length !== 0) return '';
const filter = deriveKbFilterFromTools(agentAllowedTools.value);
if (!filter) return '';
return t('mentionDetail.noCompatibleKbForAgent');
});
// 智能体是否启用了图片上传(多模态)
const isImageUploadEnabledByAgent = computed(() => {
if (!hasAgentConfig.value) return false;
@@ -258,6 +312,9 @@ const mentionStartPos = ref(0);
const isComposing = ref(false);
const isMentionTriggeredByButton = ref(false);
const mentionHasMore = ref(false);
// 当前 @ 会话可见的 KB ID 集合(含工具兼容性过滤),分页加载文件时复用,
// 避免 append 请求把不兼容 KB 的文件漏进来。`null` 表示"不受限制"(非智能体场景)
const mentionAllowedKbIds = ref<Set<string> | null>(null);
const mentionLoading = ref(false);
const mentionOffset = ref(0);
const MENTION_PAGE_SIZE = 20;
@@ -835,13 +892,16 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
const res: any = await listKnowledgeBases({ agent_id: agentId });
const list = res?.data && Array.isArray(res.data) ? res.data : [];
const orgLabel = sharedAgentOrgName.value || '';
// 保留 capabilities / indexing_strategy,后面过滤时要用
availableKbs = list.map((kb: any) => ({
id: kb.id,
name: kb.name,
type: kb.type || 'document',
knowledge_count: kb.knowledge_count,
chunk_count: kb.chunk_count,
org_name: orgLabel
org_name: orgLabel,
capabilities: kb.capabilities,
indexing_strategy: kb.indexing_strategy,
}));
sharedAgentKbList.value = list.map((kb: any) => ({
id: kb.id,
@@ -867,7 +927,9 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
type: s.knowledge_base.type || 'document',
knowledge_count: s.knowledge_base.knowledge_count,
chunk_count: s.knowledge_base.chunk_count,
org_name: s.org_name || ''
org_name: s.org_name || '',
capabilities: s.knowledge_base.capabilities,
indexing_strategy: s.knowledge_base.indexing_strategy,
}));
const ownIds = new Set(availableKbs.map((kb: any) => kb.id));
sharedKbsForMention.forEach((kb: any) => {
@@ -880,14 +942,32 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
if (hasAgentConfig.value) {
const kbMode = agentKBSelectionMode.value;
// 共享智能体路径:`availableKbs` 已经来自 `listKnowledgeBases({agent_id})`,
// 后端按 kb_selection_mode + allowed_tools 做过权威过滤;前端不再重复一遍。
// 本人智能体路径:走 own KBs + user-shared KBs 合并,后端拿不到 agent 上下文,
// 所以 'selected' 要收敛到配置集合,'all' 要按工具派生的能力过滤。
const isSharedAgent = !!(sourceTenantId && agentId);
if (kbMode === 'none') {
availableKbs = [];
} else if (kbMode === 'selected') {
const configuredKbIds = agentKnowledgeBases.value;
availableKbs = availableKbs.filter((kb: any) => configuredKbIds.includes(kb.id));
} else if (!isSharedAgent) {
if (kbMode === 'selected') {
// 'selected' 完全信任用户在编辑器里的勾选;编辑器已经用 kb_filter 灰显
// 不兼容项,这里不再二次过滤,避免越权擦除用户明确的选择。
const configuredKbIds = agentKnowledgeBases.value;
availableKbs = availableKbs.filter((kb: any) => configuredKbIds.includes(kb.id));
} else if (kbMode === 'all') {
// 'all' 的语义是"全部兼容的 KB"——按工具派生的能力集合过滤,
// 避免 wiki-qa 选"全部"后 @ 出来一堆 wiki 工具跑不动的 KB。
availableKbs = availableKbs.filter((kb: any) => isKbCompatibleWithAgent(kb));
}
}
}
// 非智能体场景不限制文件过滤;智能体场景按当前 availableKbs 的 ID 集合过滤文件
mentionAllowedKbIds.value = hasAgentConfig.value
? new Set(availableKbs.map((kb: any) => String(kb.id)))
: null;
const kbs = availableKbs.filter((kb: any) =>
!q || (kb.name && kb.name.toLowerCase().includes(q.toLowerCase()))
);
@@ -902,9 +982,14 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
}
// Fetch Files from API
// 如果智能体禁用了知识库,也不显示文件
// 仅当满足以下两点才加载文件:
// 1. 智能体确实会用到知识库(kb_selection_mode !== 'none');
// 2. 智能体启用的工具里至少有一个能消费 @ 的文件 ID
// (比如 wiki-qa 全是 wiki_* 工具,用户 @ 的文件根本进不到任何工具里,就没必要展示)。
let fileItems: any[] = [];
const shouldLoadFiles = !hasAgentConfig.value || agentKBSelectionMode.value !== 'none';
const kbModeAllowsFiles = !hasAgentConfig.value || agentKBSelectionMode.value !== 'none';
const toolsAllowFiles = !hasAgentConfig.value || toolsConsumeFiles(agentAllowedTools.value);
const shouldLoadFiles = kbModeAllowsFiles && toolsAllowFiles;
if (shouldLoadFiles) {
mentionLoading.value = true;
@@ -923,9 +1008,17 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
console.log('[Mention] searchKnowledge response:', res);
if (res.data && Array.isArray(res.data)) {
let files = res.data;
if (!sourceTenantId && hasAgentConfig.value && agentKBSelectionMode.value === 'selected') {
const configuredKbIds = agentKnowledgeBases.value;
files = files.filter((f: any) => configuredKbIds.includes(f.knowledge_base_id ?? f.kb_id));
// 按当前 @ 会话的兼容 KB 集合过滤:
// - 非智能体场景:`mentionAllowedKbIds` 为 null,跳过;
// - 智能体场景(含 shared agent):'selected' 会把 ID 收敛到用户勾的 KB,
// 'all' 会收敛到"兼容"的 KB,'none' 根本走不到这里(shouldLoadFiles=false)。
// 这样分页 append 也能用同一份集合,不再只兜住 'selected' + 非共享的分支。
if (mentionAllowedKbIds.value) {
const allowed = mentionAllowedKbIds.value;
files = files.filter((f: any) => {
const kbId = f.knowledge_base_id ?? f.kb_id;
return kbId != null && allowed.has(String(kbId));
});
}
const sharedKbOrgMap: Record<string, string> = {};
(orgStore.sharedKnowledgeBases || []).forEach((s: any) => {
@@ -1948,6 +2041,7 @@ defineExpose({
:items="mentionItems"
:hasMore="mentionHasMore"
:loading="mentionLoading"
:emptyHint="mentionEmptyHint"
v-model:activeIndex="mentionActiveIndex"
@select="onMentionSelect"
@loadMore="loadMoreMentionItems"
+3 -1
View File
@@ -148,7 +148,7 @@
</div>
<div v-if="items.length === 0 && !loading" class="empty">
{{ $t('common.noResult') }}
{{ emptyHint || $t('common.noResult') }}
</div>
</div>
</template>
@@ -170,6 +170,8 @@ const props = defineProps<{
activeIndex: number;
hasMore?: boolean;
loading?: boolean;
// 空态下替换默认 "无结果" 文案,用于给上游(如"被智能体工具兼容性过滤掉了")透传具体原因
emptyHint?: string;
}>();
const emit = defineEmits(['select', 'update:activeIndex', 'loadMore']);
+1
View File
@@ -1289,6 +1289,7 @@ export default {
kbCount: '{count} documents',
belongsToKb: 'Knowledge base: ',
belongsToOrg: 'Space: ',
noCompatibleKbForAgent: "This agent's tools don't match any knowledge base's capabilities in scope, so nothing can be referenced.",
},
file: {
upload: 'Upload File',
+1
View File
@@ -1136,6 +1136,7 @@ export default {
belongsToKb: "지식베이스: ",
belongsToOrg: "스페이스: ",
readOnlyFromAgent: "이 대화에서는 읽기 전용이며 지식베이스 목록에는 표시되지 않습니다.",
noCompatibleKbForAgent: "현재 에이전트의 도구와 범위 내 지식베이스의 기능이 일치하지 않아 참조할 수 있는 지식베이스가 없습니다.",
},
agent: {
taskLabel: "작업:",
+2 -1
View File
@@ -1252,7 +1252,8 @@ export default {
kbCount: '{count} документов',
belongsToKb: 'База знаний: ',
belongsToOrg: 'Пространство: ',
readOnlyFromAgent: 'Только чтение (от агента)'
readOnlyFromAgent: 'Только чтение (от агента)',
noCompatibleKbForAgent: 'Инструменты текущего агента не соответствуют возможностям ни одной базы знаний в области видимости — нечего упомянуть.'
},
file: {
upload: 'Загрузить файл',
+1
View File
@@ -1158,6 +1158,7 @@ export default {
belongsToKb: "所属知识库:",
belongsToOrg: "所属空间:",
readOnlyFromAgent: "仅在此对话中只读,不显示在知识库列表中",
noCompatibleKbForAgent: "当前智能体的工具与作用域内知识库的能力不匹配,暂无可引用的知识库。",
},
agent: {
taskLabel: "任务:",
+208
View File
@@ -0,0 +1,208 @@
/**
* Tool Capability Requirements
*
* Single source of truth for the mapping from agent tool names to the
* knowledge-base capabilities each tool depends on. Used to:
* - Gray out tools whose dependencies aren't satisfied by the current scope
* (see `AgentEditorModal.vue` → `availableTools`).
* - Derive `kb_filter`-style predicates for agent type presets so the same
* declarative map drives both the tool allowlist and the KB allowlist
* (see `deriveKbFilterFromTools`).
*
* Capability names mirror the backend's KB capability set:
* - vector: vector chunk index (embedding-based retrieval)
* - keyword: keyword/BM25 chunk index
* - wiki: Wiki page indexing
* - graph: knowledge graph index
* - faq: FAQ-type KB (question/answer pairs as chunks)
*
* Requirement semantics:
* - `anyOf`: KB scope must expose at least ONE listed capability.
* - `allOf`: KB scope must expose ALL listed capabilities.
* - empty : tool has no KB requirement (always available).
*
* IMPORTANT: keep this list aligned with backend tool definitions
* (`internal/agent/tools/`). A tool missing from this map defaults to
* "always available" so new tools don't silently start disabled.
*/
export type KBCapability = 'vector' | 'keyword' | 'wiki' | 'graph' | 'faq';
export interface ToolRequirement {
anyOf?: KBCapability[];
allOf?: KBCapability[];
/**
* Whether this tool can use user-provided file references (via @ 提及) as
* an additional retrieval scope. Tools with `consumesFiles: false` ignore
* `knowledge_ids`; we use this flag in the chat `@` dropdown to decide
* whether to even offer the "文件" tab to the user.
*/
consumesFiles?: boolean;
}
export const TOOL_CAPABILITY_REQUIREMENTS: Record<string, ToolRequirement> = {
// ---- base / reasoning (no KB dependency) ----
thinking: {},
todo_write: {},
final_answer: {},
// ---- RAG / chunk retrieval (need at least one chunk-indexed KB) ----
// We use vector|keyword as the canonical "has RAG chunks" signal. FAQ KBs
// also expose chunks, but the current UX message bucket is "RAG KB"; once
// we add a dedicated `requiresFaqKb` i18n key we can include `faq` here.
knowledge_search: { anyOf: ['vector', 'keyword'], consumesFiles: true },
grep_chunks: { anyOf: ['vector', 'keyword'], consumesFiles: true },
list_knowledge_chunks: { anyOf: ['vector', 'keyword'], consumesFiles: true },
query_knowledge_graph: { anyOf: ['vector', 'keyword'], consumesFiles: true },
get_document_info: { anyOf: ['vector', 'keyword'], consumesFiles: true },
database_query: { anyOf: ['vector', 'keyword'], consumesFiles: true },
// ---- Wiki (operates on wiki pages referenced by the wiki machinery;
// arbitrary user-picked file IDs aren't meaningful here) ----
wiki_search: { allOf: ['wiki'] },
wiki_read_page: { allOf: ['wiki'] },
wiki_read_source_doc: { allOf: ['wiki'] },
wiki_flag_issue: { allOf: ['wiki'] },
wiki_write_page: { allOf: ['wiki'] },
wiki_replace_text: { allOf: ['wiki'] },
wiki_rename_page: { allOf: ['wiki'] },
wiki_delete_page: { allOf: ['wiki'] },
wiki_read_issue: { allOf: ['wiki'] },
wiki_update_issue: { allOf: ['wiki'] },
// ---- Data analysis (reads table summary/column chunks produced by RAG ingest) ----
data_analysis: { anyOf: ['vector', 'keyword'], consumesFiles: true },
data_schema: { anyOf: ['vector', 'keyword'], consumesFiles: true },
};
/**
* Aggregate KB-capability set available somewhere in the agent's KB scope.
* All fields default to `false` for unknown capabilities.
*/
export interface ScopeCapabilities {
vector: boolean;
keyword: boolean;
wiki: boolean;
graph: boolean;
faq: boolean;
}
/**
* Machine-readable reason a tool is unsatisfiable. Map to a user-facing
* string via i18n on the caller side (see `AgentEditorModal.vue`).
*/
export type RequirementMissKind = 'none' | 'needsKb' | 'needsRag' | 'needsWiki' | 'needsGraph' | 'needsFaq';
/**
* Evaluate whether a tool's requirements are satisfied by the scope.
*
* @param toolName the tool identifier (see `TOOL_CAPABILITY_REQUIREMENTS`)
* @param scope aggregate capabilities exposed by KBs currently in scope
* @param hasAnyKb whether the agent has at least one KB in scope
* (i.e. `kb_selection_mode !== 'none'`)
*/
export function evaluateToolRequirement(
toolName: string,
scope: ScopeCapabilities,
hasAnyKb: boolean,
): { ok: boolean; missKind: RequirementMissKind } {
const req = TOOL_CAPABILITY_REQUIREMENTS[toolName];
// Tools absent from the map or with no requirements: always available.
if (!req || (!req.anyOf?.length && !req.allOf?.length)) {
return { ok: true, missKind: 'none' };
}
// Any capability requirement implies needing at least one KB in scope.
if (!hasAnyKb) return { ok: false, missKind: 'needsKb' };
const has = (c: KBCapability): boolean => !!scope[c];
if (req.allOf && req.allOf.length > 0) {
for (const c of req.allOf) {
if (!has(c)) return { ok: false, missKind: primaryMissKind(c) };
}
}
if (req.anyOf && req.anyOf.length > 0) {
if (!req.anyOf.some(has)) {
return { ok: false, missKind: primaryMissKind(req.anyOf[0]) };
}
}
return { ok: true, missKind: 'none' };
}
function primaryMissKind(c: KBCapability): RequirementMissKind {
switch (c) {
case 'wiki': return 'needsWiki';
case 'graph': return 'needsGraph';
case 'faq': return 'needsFaq';
case 'vector':
case 'keyword': return 'needsRag';
}
}
/**
* Derive a `kb_filter`-style predicate for a list of tools: a KB satisfies
* the derived filter iff at least ONE of the listed tools would be usable
* on a scope consisting of just that KB.
*
* Used by Step 3 so presets don't have to hand-maintain `kb_filter` next
* to their `allowed_tools` — the two are always derived from the same map.
*
* Returns `null` when none of the input tools have any KB requirement
* (i.e. any KB is acceptable).
*/
export function deriveKbFilterFromTools(
tools: string[],
): { any_of: KBCapability[] } | null {
const caps = new Set<KBCapability>();
for (const t of tools) {
const req = TOOL_CAPABILITY_REQUIREMENTS[t];
if (!req) continue;
req.anyOf?.forEach(c => caps.add(c));
req.allOf?.forEach(c => caps.add(c));
}
if (caps.size === 0) return null;
return { any_of: Array.from(caps) };
}
/**
* Decide whether a single KB is compatible with an agent's tool set.
*
* "Compatible" here means: at least ONE tool in `allowedTools` requires a
* capability that this KB exposes — i.e. the agent has SOMETHING useful to
* do against this KB. Tools with no KB requirement don't contribute.
*
* If `allowedTools` contains no KB-dependent tool, every KB is considered
* compatible (the agent won't retrieve anything either way, so filtering
* is not meaningful).
*/
export function kbSatisfiesToolRequirements(
kbCaps: Partial<ScopeCapabilities> | undefined | null,
allowedTools: string[] | undefined | null,
): boolean {
const filter = deriveKbFilterFromTools(allowedTools || []);
if (!filter) return true;
if (!kbCaps) return false;
return filter.any_of.some(c => !!kbCaps[c]);
}
/**
* True iff any of the agent's allowed tools can consume user-provided file
* references (`knowledge_ids`). Used by the chat `@` menu to decide whether
* showing the "文件" list makes sense at all — e.g. a pure Wiki agent has no
* tool that would read an arbitrary file the user picks, so we don't offer
* it. `undefined`/`null`/empty → true (permissive fallback: if we don't
* know, show files).
*/
export function toolsConsumeFiles(
allowedTools: string[] | undefined | null,
): boolean {
if (!allowedTools || allowedTools.length === 0) return true;
for (const t of allowedTools) {
const req = TOOL_CAPABILITY_REQUIREMENTS[t];
// Unknown tools (e.g. MCP tools) are treated as potentially file-consuming.
if (!req) return true;
if (req.consumesFiles) return true;
}
return false;
}
+120 -78
View File
@@ -1363,6 +1363,7 @@ import {
type PlaceholderDefinition,
type AgentTypePreset,
type AgentType,
type AgentTypeKBFilter,
type KBCapabilities,
} from '@/api/agent';
import { listModels, type ModelConfig } from '@/api/model';
@@ -1379,6 +1380,12 @@ import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue';
import ModelSelector from '@/components/ModelSelector.vue';
import AgentShareSettings from '@/components/AgentShareSettings.vue';
import IMChannelPanel from '@/components/IMChannelPanel.vue';
import {
evaluateToolRequirement,
deriveKbFilterFromTools,
type RequirementMissKind,
type ScopeCapabilities,
} from '@/utils/tool-capabilities';
const uiStore = useUIStore();
const authStore = useAuthStore();
@@ -1446,17 +1453,11 @@ const defaultRerankThreshold = ref(0.5);
const defaultMaxCompletionTokens = ref(2048);
const defaultTemperature = ref(0.7);
// 知识库相关工具列表(RAG 向量检索工具,依赖 RAG 能力)
// 知识库相关工具列表(用于 watch(hasKnowledgeBase) 从"无"变"有"时 seed 默认工具)
const knowledgeBaseTools = ['grep_chunks', 'knowledge_search', 'list_knowledge_chunks', 'query_knowledge_graph', 'get_document_info', 'database_query'];
// Wiki 读取类工具(依赖 Wiki 能力,阅读/搜索用途)
// Wiki 读取类工具(用于 watch(agentMode) 切到 smart-reasoning 时 seed 默认工具)
const wikiReadTools = ['wiki_search', 'wiki_read_page', 'wiki_read_source_doc', 'wiki_flag_issue'];
// Wiki 编辑类工具(修改 Wiki 内容,需谨慎授权)
const wikiEditTools = ['wiki_write_page', 'wiki_replace_text', 'wiki_rename_page', 'wiki_delete_page'];
// Wiki 巡检类工具
const wikiIssueTools = ['wiki_read_issue', 'wiki_update_issue'];
// 全部 Wiki 工具
const allWikiTools = [...wikiReadTools, ...wikiEditTools, ...wikiIssueTools];
// 初始化标志,防止初始化时触发 watch 自动添加工具
const isInitializing = ref(false);
@@ -1470,39 +1471,38 @@ const mcpSelectionMode = ref<'all' | 'selected' | 'none'>('none');
// Skills 选择模式:all=全部, selected=指定, none=不使用
const skillsSelectionMode = ref<'all' | 'selected' | 'none'>('none');
// 可用工具列表 (与后台 definitions.go 保持一致)
// 可用工具列表(与后台 internal/agent/tools/definitions.go 保持一致)
// group 决定 UI 分组:base / rag / wiki_read / wiki_edit / wiki_issue / data
// requiresKB: 需要任意知识库配置才可用(配合 hasKnowledgeBase)
// requiresRag: 需要作用域内存在启用了向量/关键词索引的知识库(配合 hasRagKnowledgeBase)
// requiresWiki: 需要作用域内存在启用了 Wiki 索引的知识库(配合 hasWikiKnowledgeBase)
// danger: 写类破坏性工具,UI 上给出显著提示
// danger: 写类破坏性工具,UI 上给出显著提示
// 工具的 KB 能力依赖关系统一在 `@/utils/tool-capabilities` 声明,
// `availableTools` 通过 `evaluateToolRequirement` 读取,不在这里重复维护。
const allTools = computed(() => [
// 基础思考类
{ value: 'thinking', label: t('agentEditor.tools.thinking'), description: t('agentEditor.tools.thinkingDesc'), requiresKB: false, requiresRag: false, requiresWiki: false, group: 'base' },
{ value: 'todo_write', label: t('agentEditor.tools.todoWrite'), description: t('agentEditor.tools.todoWriteDesc'), requiresKB: false, requiresRag: false, requiresWiki: false, group: 'base' },
// 知识库语义/关键词检索(均需 RAG 能力)
{ value: 'grep_chunks', label: t('agentEditor.tools.grepChunks'), description: t('agentEditor.tools.grepChunksDesc'), requiresKB: true, requiresRag: true, requiresWiki: false, group: 'rag' },
{ value: 'knowledge_search', label: t('agentEditor.tools.knowledgeSearch'), description: t('agentEditor.tools.knowledgeSearchDesc'), requiresKB: true, requiresRag: true, requiresWiki: false, group: 'rag' },
{ value: 'list_knowledge_chunks', label: t('agentEditor.tools.listChunks'), description: t('agentEditor.tools.listChunksDesc'), requiresKB: true, requiresRag: true, requiresWiki: false, group: 'rag' },
{ value: 'query_knowledge_graph', label: t('agentEditor.tools.queryGraph'), description: t('agentEditor.tools.queryGraphDesc'), requiresKB: true, requiresRag: true, requiresWiki: false, group: 'rag' },
{ value: 'get_document_info', label: t('agentEditor.tools.getDocInfo'), description: t('agentEditor.tools.getDocInfoDesc'), requiresKB: true, requiresRag: true, requiresWiki: false, group: 'rag' },
{ value: 'database_query', label: t('agentEditor.tools.dbQuery'), description: t('agentEditor.tools.dbQueryDesc'), requiresKB: true, requiresRag: true, requiresWiki: false, group: 'rag' },
{ value: 'thinking', label: t('agentEditor.tools.thinking'), description: t('agentEditor.tools.thinkingDesc'), group: 'base' },
{ value: 'todo_write', label: t('agentEditor.tools.todoWrite'), description: t('agentEditor.tools.todoWriteDesc'), group: 'base' },
// 知识库语义/关键词检索
{ value: 'grep_chunks', label: t('agentEditor.tools.grepChunks'), description: t('agentEditor.tools.grepChunksDesc'), group: 'rag' },
{ value: 'knowledge_search', label: t('agentEditor.tools.knowledgeSearch'), description: t('agentEditor.tools.knowledgeSearchDesc'), group: 'rag' },
{ value: 'list_knowledge_chunks', label: t('agentEditor.tools.listChunks'), description: t('agentEditor.tools.listChunksDesc'), group: 'rag' },
{ value: 'query_knowledge_graph', label: t('agentEditor.tools.queryGraph'), description: t('agentEditor.tools.queryGraphDesc'), group: 'rag' },
{ value: 'get_document_info', label: t('agentEditor.tools.getDocInfo'), description: t('agentEditor.tools.getDocInfoDesc'), group: 'rag' },
{ value: 'database_query', label: t('agentEditor.tools.dbQuery'), description: t('agentEditor.tools.dbQueryDesc'), group: 'rag' },
// Wiki 读取类(阅读、搜索、标记问题)
{ value: 'wiki_search', label: t('agentEditor.tools.wikiSearch'), description: t('agentEditor.tools.wikiSearchDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_read' },
{ value: 'wiki_read_page', label: t('agentEditor.tools.wikiReadPage'), description: t('agentEditor.tools.wikiReadPageDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_read' },
{ value: 'wiki_read_source_doc', label: t('agentEditor.tools.wikiReadSourceDoc'), description: t('agentEditor.tools.wikiReadSourceDocDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_read' },
{ value: 'wiki_flag_issue', label: t('agentEditor.tools.wikiFlagIssue'), description: t('agentEditor.tools.wikiFlagIssueDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_read' },
{ value: 'wiki_search', label: t('agentEditor.tools.wikiSearch'), description: t('agentEditor.tools.wikiSearchDesc'), group: 'wiki_read' },
{ value: 'wiki_read_page', label: t('agentEditor.tools.wikiReadPage'), description: t('agentEditor.tools.wikiReadPageDesc'), group: 'wiki_read' },
{ value: 'wiki_read_source_doc', label: t('agentEditor.tools.wikiReadSourceDoc'), description: t('agentEditor.tools.wikiReadSourceDocDesc'), group: 'wiki_read' },
{ value: 'wiki_flag_issue', label: t('agentEditor.tools.wikiFlagIssue'), description: t('agentEditor.tools.wikiFlagIssueDesc'), group: 'wiki_read' },
// Wiki 编辑类(会直接修改 Wiki 内容)
{ value: 'wiki_write_page', label: t('agentEditor.tools.wikiWritePage'), description: t('agentEditor.tools.wikiWritePageDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_edit', danger: true },
{ value: 'wiki_replace_text', label: t('agentEditor.tools.wikiReplaceText'), description: t('agentEditor.tools.wikiReplaceTextDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_edit', danger: true },
{ value: 'wiki_rename_page', label: t('agentEditor.tools.wikiRenamePage'), description: t('agentEditor.tools.wikiRenamePageDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_edit', danger: true },
{ value: 'wiki_delete_page', label: t('agentEditor.tools.wikiDeletePage'), description: t('agentEditor.tools.wikiDeletePageDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_edit', danger: true },
{ value: 'wiki_write_page', label: t('agentEditor.tools.wikiWritePage'), description: t('agentEditor.tools.wikiWritePageDesc'), group: 'wiki_edit', danger: true },
{ value: 'wiki_replace_text', label: t('agentEditor.tools.wikiReplaceText'), description: t('agentEditor.tools.wikiReplaceTextDesc'), group: 'wiki_edit', danger: true },
{ value: 'wiki_rename_page', label: t('agentEditor.tools.wikiRenamePage'), description: t('agentEditor.tools.wikiRenamePageDesc'), group: 'wiki_edit', danger: true },
{ value: 'wiki_delete_page', label: t('agentEditor.tools.wikiDeletePage'), description: t('agentEditor.tools.wikiDeletePageDesc'), group: 'wiki_edit', danger: true },
// Wiki 巡检类
{ value: 'wiki_read_issue', label: t('agentEditor.tools.wikiReadIssue'), description: t('agentEditor.tools.wikiReadIssueDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_issue' },
{ value: 'wiki_update_issue', label: t('agentEditor.tools.wikiUpdateIssue'), description: t('agentEditor.tools.wikiUpdateIssueDesc'), requiresKB: true, requiresRag: false, requiresWiki: true, group: 'wiki_issue' },
// 数据分析(不依赖检索类能力,只需要作用域里有 KB 存放数据文件)
{ value: 'data_analysis', label: t('agentEditor.tools.dataAnalysis'), description: t('agentEditor.tools.dataAnalysisDesc'), requiresKB: true, requiresRag: false, requiresWiki: false, group: 'data' },
{ value: 'data_schema', label: t('agentEditor.tools.dataSchema'), description: t('agentEditor.tools.dataSchemaDesc'), requiresKB: true, requiresRag: false, requiresWiki: false, group: 'data' },
{ value: 'wiki_read_issue', label: t('agentEditor.tools.wikiReadIssue'), description: t('agentEditor.tools.wikiReadIssueDesc'), group: 'wiki_issue' },
{ value: 'wiki_update_issue', label: t('agentEditor.tools.wikiUpdateIssue'), description: t('agentEditor.tools.wikiUpdateIssueDesc'), group: 'wiki_issue' },
// 数据分析
{ value: 'data_analysis', label: t('agentEditor.tools.dataAnalysis'), description: t('agentEditor.tools.dataAnalysisDesc'), group: 'data' },
{ value: 'data_schema', label: t('agentEditor.tools.dataSchema'), description: t('agentEditor.tools.dataSchemaDesc'), group: 'data' },
]);
// 工具分组元信息
@@ -1560,27 +1560,52 @@ const hasFaqKnowledgeBase = computed(() => {
return kbOptions.value.some(kb => selectedKbIds.includes(kb.value) && kb.type === 'faq');
});
const availableTools = computed(() => {
return allTools.value.map(tool => {
// 通用知识库依赖:未配置任何知识库时禁用,优先级最高
const needKbAndMissing = tool.requiresKB && !hasKnowledgeBase.value;
// Wiki 依赖:有 KB 但作用域内没有启用 Wiki 的 KB
const needWikiAndMissing = tool.requiresWiki && !hasWikiKnowledgeBase.value;
// RAG 依赖:有 KB 但作用域内没有启用向量/关键词索引的 KB
const needRagAndMissing = tool.requiresRag && !hasRagKnowledgeBase.value;
const disabled = needKbAndMissing || needWikiAndMissing || needRagAndMissing;
let disabledReason: string | undefined;
if (needKbAndMissing) {
disabledReason = t('agentEditor.tools.requiresKb');
} else if (needWikiAndMissing) {
disabledReason = t('agentEditor.tools.requiresWikiKb');
} else if (needRagAndMissing) {
disabledReason = t('agentEditor.tools.requiresRagKb');
// 把"作用域内 KB 能力"聚合成一个 ScopeCapabilities 对象,交给
// `evaluateToolRequirement` 统一判定;UI 上的所有可用性提示都应出自此处。
const scopeCapabilities = computed<ScopeCapabilities>(() => {
const scope: ScopeCapabilities = { vector: false, keyword: false, wiki: false, graph: false, faq: false };
for (const kb of kbsInScope.value) {
const caps = kb.capabilities;
if (caps) {
if (caps.vector) scope.vector = true;
if (caps.keyword) scope.keyword = true;
if (caps.wiki) scope.wiki = true;
if (caps.graph) scope.graph = true;
if (caps.faq) scope.faq = true;
} else {
// 向后兼容:capabilities 尚未加载时,退回到 ragEnabled/wikiEnabled 推断
if (kb.ragEnabled) { scope.vector = true; scope.keyword = true; }
if (kb.wikiEnabled) scope.wiki = true;
if (kb.type === 'faq') scope.faq = true;
}
}
return scope;
});
// 把 evaluateToolRequirement 返回的 missKind 映射到 i18n 文案。
// 新增的 needsGraph / needsFaq 暂时复用 requiresRagKb 文案("需要 RAG 知识库"),
// 后续可按需增加独立的 i18n 键。
const missKindToReason = (kind: RequirementMissKind): string | undefined => {
switch (kind) {
case 'needsKb': return t('agentEditor.tools.requiresKb');
case 'needsWiki': return t('agentEditor.tools.requiresWikiKb');
case 'needsRag':
case 'needsGraph':
case 'needsFaq': return t('agentEditor.tools.requiresRagKb');
case 'none':
default: return undefined;
}
};
const availableTools = computed(() => {
const scope = scopeCapabilities.value;
const hasAnyKb = hasKnowledgeBase.value;
return allTools.value.map(tool => {
const { ok, missKind } = evaluateToolRequirement(tool.value, scope, hasAnyKb);
return {
...tool,
disabled,
disabledReason,
disabled: !ok,
disabledReason: ok ? undefined : missKindToReason(missKind),
};
});
});
@@ -1908,9 +1933,35 @@ const presetKbMismatchReason = (preset: AgentTypePreset): string => {
return t('agentEditor.agentType.kbMismatch.generic');
};
// 计算预设的"有效 KB 过滤器":工具推导 + YAML 增量叠加。
//
// 设计原则:
// - 工具 → any_of("KB 至少要能被其中一个工具用得上")由
// `deriveKbFilterFromTools` 自动算出;
// - YAML 里的 `kb_filter` 只负责**工具推不出来**的业务规则(如
// data-analysis 的 `none_of: ["faq"]`),作为增量合并,而不是整体覆盖;
// - `all_of` / `none_of` 直接从 YAML 继承(工具不表达这类约束)。
//
// 这样 rag-qa / wiki-qa / hybrid 在 YAML 里彻底不写 `kb_filter`,
// data-analysis 只需声明额外的 `none_of`,"工具→能力"的映射只在
// `@/utils/tool-capabilities` 维护一份。
const effectiveKbFilter = (preset: AgentTypePreset | null): AgentTypeKBFilter | null => {
if (!preset) return null;
const derived = deriveKbFilterFromTools(preset.config?.allowed_tools || []);
const yaml = preset.kb_filter;
// YAML 提供 any_of 时整体覆盖推导(给显式控制留口子);否则用推导的
const anyOf = (yaml?.any_of && yaml.any_of.length > 0) ? yaml.any_of : (derived?.any_of ?? []);
const allOf = yaml?.all_of ?? [];
const noneOf = yaml?.none_of ?? [];
if (anyOf.length === 0 && allOf.length === 0 && noneOf.length === 0) return null;
return { any_of: anyOf, all_of: allOf, none_of: noneOf };
};
// 评估单个 KB 是否满足给定预设的 kb_filter
const kbSatisfiesPresetFilter = (kb: { capabilities?: KBCapabilities; ragEnabled?: boolean; wikiEnabled?: boolean; type?: string }, preset: AgentTypePreset | null): { ok: boolean; reason: string } => {
if (!preset || !preset.kb_filter) return { ok: true, reason: '' };
const filter = effectiveKbFilter(preset);
if (!preset || !filter) return { ok: true, reason: '' };
const caps = kb.capabilities || {
vector: !!kb.ragEnabled,
keyword: !!kb.ragEnabled,
@@ -1928,20 +1979,19 @@ const kbSatisfiesPresetFilter = (kb: { capabilities?: KBCapabilities; ragEnabled
default: return false;
}
};
const f = preset.kb_filter;
const reason = presetKbMismatchReason(preset);
if (f.all_of && f.all_of.length > 0) {
for (const n of f.all_of) {
if (filter.all_of && filter.all_of.length > 0) {
for (const n of filter.all_of) {
if (!has(n)) return { ok: false, reason };
}
}
if (f.any_of && f.any_of.length > 0) {
if (!f.any_of.some(n => has(n))) {
if (filter.any_of && filter.any_of.length > 0) {
if (!filter.any_of.some(n => has(n))) {
return { ok: false, reason };
}
}
if (f.none_of && f.none_of.length > 0) {
for (const n of f.none_of) {
if (filter.none_of && filter.none_of.length > 0) {
for (const n of filter.none_of) {
if (has(n)) return { ok: false, reason };
}
}
@@ -2363,7 +2413,14 @@ watch(agentMode, (val, _oldVal) => {
}
});
// 监听知识库配置变化,自动移除/添加 RAG 工具
// 监听知识库启用状态变化:
// - 从"无"变"有":自动补齐 RAG 基础工具,方便用户开箱即用(仅 seed 行为);
// - 从"有"变"无":**不再**自动擦工具,依赖不满足时由 `availableTools` 灰显
// + 运行时工具注册器过滤。`allowed_tools` 代表用户意图,只应在用户显式操作
// (切 agent_type / 切 agent_mode / 手勾工具)时变更。
// 历史背景:旧版本在 KB 能力消失时会擦除 KB/Wiki 工具,导致用户切换
// `kb_selection_mode` 到 "selected"、但尚未勾具体 KB 的过渡期里静默丢失工具,
// 对默认工具全是 wiki_* 的内置"维基问答"智能体尤为致命。
watch(hasKnowledgeBase, (hasKB, oldHasKB) => {
// 如果当前在检索策略页面但没有知识库能力了,切换到基础设置
if (!hasKB && currentSection.value === 'retrieval') {
@@ -2374,25 +2431,10 @@ watch(hasKnowledgeBase, (hasKB, oldHasKB) => {
if (isInitializing.value || !isAgentMode.value) return;
if (hasKB && !oldHasKB) {
// 从无知识库变为有知识库,自动添加知识库相关工具
// 从无知识库变为有知识库,seed 默认的 RAG 工具(仅补齐未勾的)
const currentTools = formData.value.config.allowed_tools || [];
const toolsToAdd = knowledgeBaseTools.filter((tool: string) => !currentTools.includes(tool));
formData.value.config.allowed_tools = [...currentTools, ...toolsToAdd];
} else if (!hasKB && oldHasKB) {
// 从有知识库变为无知识库,移除所有 KB 依赖工具(含 Wiki)
formData.value.config.allowed_tools = formData.value.config.allowed_tools.filter(
(tool: string) => !knowledgeBaseTools.includes(tool) && !allWikiTools.includes(tool)
);
}
});
// 监听 Wiki 能力变化:当 Wiki 能力消失时移除已勾选的 Wiki 工具(避免"勾了但跑不起来")
watch(hasWikiKnowledgeBase, (hasWiki, oldHasWiki) => {
if (isInitializing.value || !isAgentMode.value) return;
if (!hasWiki && oldHasWiki) {
formData.value.config.allowed_tools = formData.value.config.allowed_tools.filter(
(tool: string) => !allWikiTools.includes(tool)
);
}
});
+176
View File
@@ -0,0 +1,176 @@
// Package tools — capability requirements for built-in agent tools.
//
// 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.
//
// 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
// authoritative last line of defense in the retrieval pipeline — a client
// that skips the frontend filter (old tab, curl, rogue plugin) shouldn't be
// able to hand incompatible KBs/files to a tool that would just silently
// skip them.
package tools
import (
"github.com/Tencent/WeKnora/internal/types"
)
// KBCapability names the capability flags a knowledge base can expose.
// Values mirror the keys of `types.KBCapabilities`.
type KBCapability string
const (
CapVector KBCapability = "vector"
CapKeyword KBCapability = "keyword"
CapWiki KBCapability = "wiki"
CapGraph KBCapability = "graph"
CapFAQ KBCapability = "faq"
)
// ToolRequirement declares what a tool needs from the KB scope.
//
// - AnyOf: scope must expose at least ONE listed capability.
// - AllOf: scope must expose ALL listed capabilities.
// - ConsumesFiles: the tool reads user-provided file refs from
// `knowledge_ids`; the chat input uses this to decide whether to
// even offer the `@file` list to the user.
//
// A nil/zero requirement means "no KB dependency" — the tool is always
// available and doesn't care about files.
type ToolRequirement struct {
AnyOf []KBCapability
AllOf []KBCapability
ConsumesFiles bool
}
// ToolCapabilityRequirements maps tool names to their capability needs.
// Keep this aligned with `frontend/src/utils/tool-capabilities.ts`.
//
// Tools absent from this map default to "no requirement" and are treated
// as always available / file-consuming (permissive fallback: unknown MCP
// tools shouldn't silently break).
var ToolCapabilityRequirements = map[string]ToolRequirement{
// ---- base / reasoning (no KB dependency, no file consumption) ----
"thinking": {},
"todo_write": {},
"final_answer": {},
// ---- RAG / chunk retrieval (need at least one chunk-indexed KB) ----
"knowledge_search": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
"grep_chunks": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
"list_knowledge_chunks": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
"query_knowledge_graph": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
"get_document_info": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
"database_query": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
// ---- Wiki (operates on wiki pages; doesn't consume arbitrary file IDs) ----
"wiki_search": {AllOf: []KBCapability{CapWiki}},
"wiki_read_page": {AllOf: []KBCapability{CapWiki}},
"wiki_read_source_doc": {AllOf: []KBCapability{CapWiki}},
"wiki_flag_issue": {AllOf: []KBCapability{CapWiki}},
"wiki_write_page": {AllOf: []KBCapability{CapWiki}},
"wiki_replace_text": {AllOf: []KBCapability{CapWiki}},
"wiki_rename_page": {AllOf: []KBCapability{CapWiki}},
"wiki_delete_page": {AllOf: []KBCapability{CapWiki}},
"wiki_read_issue": {AllOf: []KBCapability{CapWiki}},
"wiki_update_issue": {AllOf: []KBCapability{CapWiki}},
// ---- Data analysis (reads table summary/column chunks from RAG ingest) ----
"data_analysis": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
"data_schema": {AnyOf: []KBCapability{CapVector, CapKeyword}, ConsumesFiles: true},
}
func hasCap(caps types.KBCapabilities, c KBCapability) bool {
switch c {
case CapVector:
return caps.Vector
case CapKeyword:
return caps.Keyword
case CapWiki:
return caps.Wiki
case CapGraph:
return caps.Graph
case CapFAQ:
return caps.FAQ
}
return false
}
// KBFilter is the derived "KB must expose at least one of these capabilities"
// predicate for a set of allowed tools (see DeriveKBFilterFromTools).
type KBFilter struct {
AnyOf []KBCapability
}
// IsEmpty reports whether the filter imposes no constraint
// (either no capability accumulated, or explicit zero value).
func (f KBFilter) IsEmpty() bool { return len(f.AnyOf) == 0 }
// DeriveKBFilterFromTools derives a capability filter such that a KB passes
// iff at least ONE of the allowed tools has a requirement the KB satisfies.
// Tools without any KB requirement don't contribute — if the allowed-tools
// list contains only such tools, the returned filter is empty (accept all).
func DeriveKBFilterFromTools(allowedTools []string) KBFilter {
seen := make(map[KBCapability]struct{})
for _, t := range allowedTools {
req, ok := ToolCapabilityRequirements[t]
if !ok {
continue
}
for _, c := range req.AnyOf {
seen[c] = struct{}{}
}
for _, c := range req.AllOf {
seen[c] = struct{}{}
}
}
if len(seen) == 0 {
return KBFilter{}
}
out := make([]KBCapability, 0, len(seen))
for c := range seen {
out = append(out, c)
}
return KBFilter{AnyOf: out}
}
// KBSatisfiesToolRequirements reports whether a single KB is compatible
// with the agent's tool set. "Compatible" means: the KB exposes at least
// one capability that some tool in `allowedTools` requires. When the tool
// set imposes no KB requirement at all, every KB is considered compatible.
func KBSatisfiesToolRequirements(caps types.KBCapabilities, allowedTools []string) bool {
f := DeriveKBFilterFromTools(allowedTools)
if f.IsEmpty() {
return true
}
for _, c := range f.AnyOf {
if hasCap(caps, c) {
return true
}
}
return false
}
// ToolsConsumeFiles reports whether any tool in the allowed-tools list can
// use user-provided file references. Used to gate the `@file` listing in
// the chat input (and potentially SearchKnowledge defensively on the
// backend). An empty allowed-tools list is treated as "unknown → permissive".
func ToolsConsumeFiles(allowedTools []string) bool {
if len(allowedTools) == 0 {
return true
}
for _, t := range allowedTools {
req, ok := ToolCapabilityRequirements[t]
// Unknown tools (e.g. MCP tools, new builtin not yet registered here):
// assume potentially file-consuming to avoid accidentally hiding the
// file picker for users who just added a custom tool.
if !ok {
return true
}
if req.ConsumesFiles {
return true
}
}
return false
}
@@ -6,6 +6,7 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/tools"
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/event"
@@ -328,6 +329,22 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
switch customAgent.Config.KBSelectionMode {
case "all":
// Authoritative capability filter for the runtime path. The frontend
// editor and @mention dropdown apply the same filter, but we don't
// trust the client here: a stale session payload or API caller could
// still ask us to retrieve against an incompatible KB and we'd rather
// just drop it (and log) than feed it to tools that would no-op.
capFilter := tools.DeriveKBFilterFromTools(customAgent.Config.AllowedTools)
accept := func(kb *types.KnowledgeBase) bool {
if kb == nil {
return false
}
if capFilter.IsEmpty() {
return true
}
return tools.KBSatisfiesToolRequirements(kb.Capabilities(), customAgent.Config.AllowedTools)
}
// Get own knowledge bases (uses ctx TenantID = agent's tenant)
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
if err != nil {
@@ -335,7 +352,12 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
}
kbIDSet := make(map[string]bool)
kbIDs := make([]string, 0, len(allKBs))
ownSkipped := 0
for _, kb := range allKBs {
if !accept(kb) {
ownSkipped++
continue
}
kbIDs = append(kbIDs, kb.ID)
kbIDSet[kb.ID] = true
}
@@ -344,6 +366,7 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
// tenant's own KBs. Including the current user's shared KBs would leak
// unrelated KBs from other organisations into the agent's retrieval scope.
isSharedAgent := sessionTenantID != 0 && sessionTenantID != customAgent.TenantID
sharedSkipped := 0
if !isSharedAgent {
tenantID := types.MustTenantIDFromContext(ctx)
userIDVal := ctx.Value(types.UserIDContextKey)
@@ -354,10 +377,15 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
} else {
for _, info := range sharedList {
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
kbIDSet[info.KnowledgeBase.ID] = true
if info == nil || info.KnowledgeBase == nil || kbIDSet[info.KnowledgeBase.ID] {
continue
}
if !accept(info.KnowledgeBase) {
sharedSkipped++
continue
}
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
kbIDSet[info.KnowledgeBase.ID] = true
}
}
}
@@ -367,6 +395,11 @@ func (s *sessionService) resolveKnowledgeBasesFromAgent(
sessionTenantID, customAgent.TenantID)
}
if ownSkipped+sharedSkipped > 0 {
logger.Infof(ctx,
"KBSelectionMode=all: tool-capability filter removed %d own + %d shared KBs (agent=%s, tools=%v)",
ownSkipped, sharedSkipped, customAgent.ID, customAgent.Config.AllowedTools)
}
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases (own + shared)", len(kbIDs))
return kbIDs
case "selected":
+18 -2
View File
@@ -13,6 +13,7 @@ import (
goerrors "errors"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
@@ -1397,10 +1398,25 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
c.Error(errors.NewInternalServerError("Failed to list knowledge bases").WithDetails(err.Error()))
return
}
// `all` mode: authoritative server-side capability filter. Mirrors the
// logic in ListKnowledgeBases so @file search, KB listing, and runtime
// all agree on what "mode=all" actually means for this agent.
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
removed := 0
for _, kb := range kbs {
if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument {
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
if kb == nil || kb.Type != types.KnowledgeBaseTypeDocument {
continue
}
if !filter.IsEmpty() && !tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
removed++
continue
}
scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID})
}
if removed > 0 {
logger.Infof(ctx,
"SearchKnowledge(agent=%s, mode=all): tool-capability filter removed %d KBs",
agentID, removed)
}
}
knowledges, hasMore, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes)
+25
View File
@@ -7,6 +7,7 @@ import (
"strconv"
"time"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
@@ -346,6 +347,30 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
}
kbs = filtered
}
// `all` mode: authoritative server-side capability filter so a client
// that bypassed the frontend (old tab, curl, rogue plugin) can't @ a
// KB whose capabilities don't match any allowed tool of this agent.
// Non-`all` modes already constrain the scope explicitly.
if mode == "all" && len(agent.Config.AllowedTools) > 0 {
filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools)
if !filter.IsEmpty() {
before := len(kbs)
kept := make([]*types.KnowledgeBase, 0, before)
for _, kb := range kbs {
if tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) {
kept = append(kept, kb)
}
}
if removed := before - len(kept); removed > 0 {
logger.Infof(ctx,
"ListKnowledgeBases(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
agentID, removed, before)
}
kbs = kept
}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": kbs,
+17
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
@@ -50,9 +52,24 @@ func (c *SearchCommand) Execute(ctx context.Context, cmdCtx *CommandContext, arg
case "all":
allKBs, err := c.kbService.ListKnowledgeBases(ctx)
if err == nil {
// Same tool-capability filter as the QA pipeline's
// resolveKnowledgeBasesFromAgent (`all` branch) so `/search`
// agrees with what the agent's tools can actually reach.
filter := tools.DeriveKBFilterFromTools(cmdCtx.CustomAgent.Config.AllowedTools)
skipped := 0
for _, kb := range allKBs {
if !filter.IsEmpty() &&
!tools.KBSatisfiesToolRequirements(kb.Capabilities(), cmdCtx.CustomAgent.Config.AllowedTools) {
skipped++
continue
}
kbIDs = append(kbIDs, kb.ID)
}
if skipped > 0 {
logger.Infof(ctx,
"/search(agent=%s, mode=all): tool-capability filter removed %d of %d KBs",
cmdCtx.CustomAgent.ID, skipped, len(allKBs))
}
}
case "none":
// No knowledge bases configured — will return empty results.