Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(agent): make agent tool selection match the tools the runtime registers (#4211)

Ochan Kwon809bda7b2f2d
diff --git a/docs/docs.go b/docs/docs.go
index c29fdffbb..bc63e8547 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -367,6 +367,38 @@ const docTemplate = `{
}
}
},
+ "/agents/tools": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "返回编辑器可勾选的内置工具(含分组和知识库能力要求)、工具列表未设置时生效的默认工具,以及由开关控制、写入工具列表也不生效的工具",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "智能体"
+ ],
+ "summary": "获取智能体可选工具",
+ "responses": {
+ "200": {
+ "description": "工具目录",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
"/agents/type-presets": {
"get": {
"security": [
diff --git a/docs/swagger.json b/docs/swagger.json
index 7f857e191..657eb48ae 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -360,6 +360,38 @@
}
}
},
+ "/agents/tools": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ },
+ {
+ "ApiKeyAuth": []
+ }
+ ],
+ "description": "返回编辑器可勾选的内置工具(含分组和知识库能力要求)、工具列表未设置时生效的默认工具,以及由开关控制、写入工具列表也不生效的工具",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "智能体"
+ ],
+ "summary": "获取智能体可选工具",
+ "responses": {
+ "200": {
+ "description": "工具目录",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
+ }
+ },
"/agents/type-presets": {
"get": {
"security": [
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index 6e1ebcb37..fa6d9b0d5 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -7195,6 +7195,25 @@ paths:
summary: 获取占位符定义
tags:
- 智能体
+ /agents/tools:
+ get:
+ consumes:
+ - application/json
+ description: 返回编辑器可勾选的内置工具(含分组和知识库能力要求)、工具列表未设置时生效的默认工具,以及由开关控制、写入工具列表也不生效的工具
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 工具目录
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ - ApiKeyAuth: []
+ summary: 获取智能体可选工具
+ tags:
+ - 智能体
/agents/type-presets:
get:
consumes:
diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts
index 59c789f76..5303bfd9a 100644
--- a/frontend/src/api/agent/index.ts
+++ b/frontend/src/api/agent/index.ts
@@ -55,7 +55,7 @@ export interface CustomAgentConfig {
// ===== Agent模式设置 =====
max_iterations?: number; // 最大迭代次数;-1 表示不限制
llm_call_timeout?: number; // LLM调用超时时间(秒)
- allowed_tools?: string[]; // 允许的工具
+ allowed_tools?: string[] | null; // 允许的工具;null/未设置 = 后端默认工具,[] = 不使用内置工具
reflection_enabled?: boolean; // 是否启用反思
// MCP服务选择模式:all=全部启用的MCP服务, selected=指定服务, none=不使用MCP
mcp_selection_mode?: 'all' | 'selected' | 'none';
@@ -209,13 +209,19 @@ export function getAgentById(id: string) {
}
// 创建智能体
+// 保存时后端对 allowed_tools 的处理说明(不阻止保存)
+export interface AllowedToolsWarnings {
+ kept_unknown?: string[]; // 已保存、但当前版本没有的工具名,保留不动
+ dropped?: string[]; // 由其他设置控制的工具,已从列表移除
+}
+
export function createAgent(data: CreateAgentRequest) {
- return post<{ data: CustomAgent }>('/api/v1/agents', data);
+ return post<{ data: CustomAgent; allowed_tools_warnings?: AllowedToolsWarnings }>('/api/v1/agents', data);
}
// 更新智能体
export function updateAgent(id: string, data: UpdateAgentRequest) {
- return put<{ data: CustomAgent }>(`/api/v1/agents/${id}`, data);
+ return put<{ data: CustomAgent; allowed_tools_warnings?: AllowedToolsWarnings }>(`/api/v1/agents/${id}`, data);
}
// 删除智能体
@@ -304,6 +310,35 @@ export function getAgentTypePresets() {
return get<{ data: AgentTypePreset[] }>('/api/v1/agents/type-presets');
}
+// 智能体可选工具目录(编辑器用,来自后端 AvailableToolDefinitions)
+export type AgentToolKBCapability = 'vector' | 'keyword' | 'wiki' | 'graph' | 'faq';
+
+export interface AgentToolRequirement {
+ any_of?: AgentToolKBCapability[];
+ all_of?: AgentToolKBCapability[];
+}
+
+export interface AgentToolDefinition {
+ name: string;
+ label: string;
+ description: string;
+ group: string;
+ danger?: boolean;
+ requirement: AgentToolRequirement;
+}
+
+export interface AgentToolCatalog {
+ tools: AgentToolDefinition[];
+ // allowed_tools 未设置(null)时运行时使用的工具
+ default_tools: string[];
+ // 由智能体的其他设置决定是否注册的工具;写进 allowed_tools 不会注册
+ switch_managed_tools: string[];
+}
+
+export function getAgentTools() {
+ return get<{ data: AgentToolCatalog }>('/api/v1/agents/tools');
+}
+
// ===== IM渠道 =====
export interface IMChannel {
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 4ef8e158f..857902ca1 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -6614,6 +6614,13 @@ export default {
kbMetricRag: 'RAG KBs',
kbMetricWiki: 'Wiki KBs',
statusInactive: '{count} ticked tool(s) cannot take effect with the current config',
+ searchConversations: 'Search past conversations',
+ searchConversationsDesc: 'Look up what was discussed in this user\'s own earlier conversations',
+ groupStored: 'Stored, not offered here',
+ switchManagedDesc: 'Controlled by other settings of this agent, not by this list, so ticking it here does not turn it on. Untick it to remove it.',
+ unrecognizedDesc: 'Not a tool this version offers, so the agent cannot call it. Untick it to remove it.',
+ keptUnknownWarning: 'Saved. These stored tools are not offered by this version and were kept, but the agent cannot call them: {names}',
+ droppedWarning: 'Saved. These tools are controlled by other settings of this agent and were removed from the tool list: {names}',
effectiveLabel: 'Effective Tools',
effectiveDesc: 'Computed from the current config — these are the tools the agent will actually be able to call',
effectiveEmpty: 'No tool available — the agent will fall back to plain model chat'
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index b2837e560..0a258b7bb 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -6614,6 +6614,13 @@ export default {
kbMetricRag: 'RAGナレッジベース',
kbMetricWiki: 'Wikiナレッジベース',
statusInactive: '選択済みの{count}個のツールは、現在の設定では有効になりません',
+ searchConversations: '過去の会話を検索',
+ searchConversationsDesc: 'ユーザー自身の過去の会話から以前話した内容を探します',
+ groupStored: '保存済み(ここでは提供されていません)',
+ switchManagedDesc: 'このリストではなくエージェントの他の設定で制御されるため、ここでチェックしても有効になりません。チェックを外すと削除されます。',
+ unrecognizedDesc: 'このバージョンにはないツールのため、エージェントは呼び出せません。チェックを外すと削除されます。',
+ keptUnknownWarning: '保存しました。次の保存済みツールはこのバージョンにはないため残しましたが、エージェントは呼び出せません:{names}',
+ droppedWarning: '保存しました。次のツールはエージェントの他の設定で制御されるため、ツールリストから削除しました:{names}',
effectiveLabel: '有効なツール',
effectiveDesc: '現在の設定から算出された、エージェントが実際に呼び出せるツールです',
effectiveEmpty: '利用可能なツールがありません。エージェントは通常のモデル対話にフォールバックします'
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 3339563ca..48032c619 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -1556,6 +1556,13 @@ export default {
kbMetricRag: 'RAG 지식베이스',
kbMetricWiki: 'Wiki 지식베이스',
statusInactive: '{count}개의 체크된 도구가 현재 설정에서는 작동하지 않습니다',
+ searchConversations: '이전 대화 검색',
+ searchConversationsDesc: '사용자 본인의 이전 대화에서 나눴던 내용을 찾습니다',
+ groupStored: '저장되었지만 여기서 제공하지 않는 도구',
+ switchManagedDesc: '이 목록이 아니라 에이전트의 다른 설정으로 제어되는 도구라, 여기서 체크해도 켜지지 않습니다. 체크를 해제하면 삭제됩니다.',
+ unrecognizedDesc: '이 버전에 없는 도구라 에이전트가 호출할 수 없습니다. 체크를 해제하면 삭제됩니다.',
+ keptUnknownWarning: '저장했습니다. 다음 도구는 이 버전에 없어 그대로 남겨 두었지만, 에이전트가 호출할 수 없습니다: {names}',
+ droppedWarning: '저장했습니다. 다음 도구는 에이전트의 다른 설정으로 제어되므로 도구 목록에서 뺐습니다: {names}',
effectiveLabel: '최종 활성 도구',
effectiveDesc: '현재 설정 기준 저장 시 에이전트가 실제 호출할 수 있는 도구 집합',
effectiveEmpty: '사용 가능한 도구가 없어 일반 모델 대화로 동작합니다'
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 5376346ca..d28174b4e 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -1556,6 +1556,13 @@ export default {
kbMetricRag: 'RAG баз',
kbMetricWiki: 'Wiki баз',
statusInactive: '{count} отмеченных инструментов не смогут работать при текущей конфигурации',
+ searchConversations: 'Поиск по прошлым диалогам',
+ searchConversationsDesc: 'Ищет то, что обсуждалось в прежних диалогах этого пользователя',
+ groupStored: 'Сохранены, но здесь не предлагаются',
+ switchManagedDesc: 'Управляется другими настройками агента, а не этим списком, поэтому отметка здесь его не включает. Снимите отметку, чтобы удалить запись.',
+ unrecognizedDesc: 'Этого инструмента нет в текущей версии, агент не может его вызвать. Снимите отметку, чтобы удалить запись.',
+ keptUnknownWarning: 'Сохранено. Этих сохранённых инструментов нет в текущей версии; они оставлены, но агент не может их вызвать: {names}',
+ droppedWarning: 'Сохранено. Эти инструменты управляются другими настройками агента и удалены из списка инструментов: {names}',
effectiveLabel: 'Итоговые активные инструменты',
effectiveDesc: 'Рассчитано на основе текущей конфигурации — это набор инструментов, которые агент сможет вызывать после сохранения',
effectiveEmpty: 'Нет доступных инструментов — агент перейдёт к простому чату с моделью'
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 7a6c9c41f..935f7d5d3 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -1558,6 +1558,13 @@ export default {
kbMetricRag: 'RAG 知识库',
kbMetricWiki: 'Wiki 知识库',
statusInactive: '有 {count} 个已勾选工具在当前配置下无法生效',
+ searchConversations: '回顾历史对话',
+ searchConversationsDesc: '在用户自己的历史会话中查找之前聊过的内容',
+ groupStored: '已保存但未提供的工具',
+ switchManagedDesc: '由智能体的其他设置控制,而不是由此列表决定,在此勾选不会启用它。取消勾选即可移除。',
+ unrecognizedDesc: '当前版本不提供该工具,智能体无法调用它。取消勾选即可移除。',
+ keptUnknownWarning: '已保存。以下已保存的工具在当前版本中不提供,已保留,但智能体无法调用:{names}',
+ droppedWarning: '已保存。以下工具由智能体的其他设置控制,已从工具列表中移除:{names}',
effectiveLabel: '最终启用的工具',
effectiveDesc: '根据当前配置计算,这是智能体保存后实际能调用的工具集合',
effectiveEmpty: '当前没有可用工具,智能体将退化为纯模型问答'
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 655a91479..6465601a4 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -1558,6 +1558,13 @@ export default {
kbMetricRag: 'RAG 知識庫',
kbMetricWiki: 'Wiki 知識庫',
statusInactive: '有 {count} 個已勾選工具在當前設定下無法生效',
+ searchConversations: '回顧歷史對話',
+ searchConversationsDesc: '在使用者自己的歷史會話中查找之前聊過的內容',
+ groupStored: '已儲存但未提供的工具',
+ switchManagedDesc: '由智慧體的其他設定控制,而不是由此列表決定,在此勾選不會啟用它。取消勾選即可移除。',
+ unrecognizedDesc: '目前版本不提供此工具,智慧體無法呼叫它。取消勾選即可移除。',
+ keptUnknownWarning: '已儲存。以下已儲存的工具在目前版本中不提供,已保留,但智慧體無法呼叫:{names}',
+ droppedWarning: '已儲存。以下工具由智慧體的其他設定控制,已從工具列表中移除:{names}',
effectiveLabel: '最終啟用的工具',
effectiveDesc: '根據當前設定計算,這是智慧代理儲存後實際能呼叫的工具集合',
effectiveEmpty: '當前沒有可用工具,智慧代理將退化為純模型問答'
diff --git a/frontend/src/stores/editorResources.ts b/frontend/src/stores/editorResources.ts
index ff9069169..f67d7ea29 100644
--- a/frontend/src/stores/editorResources.ts
+++ b/frontend/src/stores/editorResources.ts
@@ -19,7 +19,7 @@ import {
type SkillCatalogItem,
type SkillInfo,
} from '@/api/skill'
-import { getAgentTypePresets, getPlaceholders, type AgentTypePreset, type PlaceholdersResponse } from '@/api/agent'
+import { getAgentTools, getAgentTypePresets, getPlaceholders, type AgentToolCatalog, type AgentTypePreset, type PlaceholdersResponse } from '@/api/agent'
import { getTenantRetrievalConfig } from '@/api/retrieval'
import { isStorageConfigDenied } from './storageEngineAccess'
import { createCachedResource } from './resourceCache'
@@ -51,6 +51,7 @@ type EditorResourceKey =
| 'skills'
| 'skillCatalog'
| 'agentTypePresets'
+ | 'agentTools'
| 'promptTemplates'
| 'placeholders'
| 'tenantRetrievalConfig'
@@ -73,6 +74,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
const skillsConfigId = ref('')
const skillCatalog = ref<SkillCatalogItem[]>([])
const agentTypePresets = ref<AgentTypePreset[]>([])
+ const agentTools = ref<AgentToolCatalog | null>(null)
const promptTemplates = ref<PromptTemplatesConfig | null>(null)
const placeholders = ref<PlaceholdersResponse | null>(null)
const tenantRetrievalConfig = ref<Record<string, unknown> | null>(null)
@@ -173,6 +175,16 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
},
)
+ const agentToolsResource = createCachedResource(
+ async () => {
+ const res: any = await getAgentTools()
+ return res?.data && Array.isArray(res.data.tools) ? (res.data as AgentToolCatalog) : null
+ },
+ (catalog) => {
+ agentTools.value = catalog
+ },
+ )
+
const promptTemplatesResource = createCachedResource(
async () => {
const tmplRes = await getPromptTemplates()
@@ -229,6 +241,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
skills: skillsResource,
skillCatalog: skillCatalogResource,
agentTypePresets: agentTypePresetsResource,
+ agentTools: agentToolsResource,
promptTemplates: promptTemplatesResource,
placeholders: placeholdersResource,
tenantRetrievalConfig: tenantRetrievalConfigResource,
@@ -282,6 +295,10 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
return agentTypePresetsResource.ensure(force)
}
+ async function ensureAgentTools(force = false): Promise<void> {
+ return agentToolsResource.ensure(force)
+ }
+
async function ensurePromptTemplates(force = false): Promise<void> {
return promptTemplatesResource.ensure(force)
}
@@ -309,6 +326,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
// are this workspace's too.
ensureMcpServices(undefined, force),
ensureAgentTypePresets(force),
+ ensureAgentTools(force),
ensurePromptTemplates(force),
ensureStorageEngine(force),
ensurePlaceholders(force),
@@ -331,6 +349,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
skillsRequestScope = { key: '', configId: '' }
skillCatalog.value = []
agentTypePresets.value = []
+ agentTools.value = null
promptTemplates.value = null
placeholders.value = null
tenantRetrievalConfig.value = null
@@ -350,6 +369,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
skillsAvailable,
skillCatalog,
agentTypePresets,
+ agentTools,
promptTemplates,
placeholders,
tenantRetrievalConfig,
@@ -361,6 +381,7 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
ensureSkills,
ensureSkillCatalog,
ensureAgentTypePresets,
+ ensureAgentTools,
ensurePromptTemplates,
ensurePlaceholders,
ensureTenantRetrievalConfig,
diff --git a/frontend/src/utils/agent-readiness.test.mjs b/frontend/src/utils/agent-readiness.test.mjs
index d8a4f3660..748e4ea80 100644
--- a/frontend/src/utils/agent-readiness.test.mjs
+++ b/frontend/src/utils/agent-readiness.test.mjs
@@ -74,10 +74,20 @@ test('does not require rerank for wiki-only tools', () => {
})
test('matches backend default-tool behavior', () => {
+ // Never set: the backend's default tools, which include search_knowledge.
assert.equal(agentRequiresRerankModel({
kb_selection_mode: 'all',
- allowed_tools: [],
+ allowed_tools: undefined,
+ }), true)
+ assert.equal(agentRequiresRerankModel({
+ kb_selection_mode: 'all',
+ allowed_tools: null,
}), true)
+ // Empty: no built-in tools, so nothing calls the reranker.
+ assert.equal(agentRequiresRerankModel({
+ kb_selection_mode: 'all',
+ allowed_tools: [],
+ }), false)
assert.equal(agentRequiresRerankModel({
kb_selection_mode: 'none',
allowed_tools: [],
@@ -129,7 +139,7 @@ test('getAgentNotReadyReasonKeys does not treat current shared context as shared
), ['summary_model'])
})
-test('getAgentNotReadyReasonKeys treats empty allowed_tools as ready via backend defaults', () => {
+test('getAgentNotReadyReasonKeys treats an empty allowed_tools with a rerank model as ready', () => {
assert.deepEqual(getAgentNotReadyReasonKeys(
{
model_id: 'chat-1',
diff --git a/frontend/src/utils/agent-readiness.ts b/frontend/src/utils/agent-readiness.ts
index 955e57f69..518c1e4be 100644
--- a/frontend/src/utils/agent-readiness.ts
+++ b/frontend/src/utils/agent-readiness.ts
@@ -38,12 +38,11 @@ export function agentRequiresRerankModel(
): boolean {
if (!config || config.kb_selection_mode === 'none') return false
- const allowedTools = config.allowed_tools || []
- // The backend falls back to DefaultAllowedTools when the list is empty,
- // and that default includes search_knowledge.
- if (allowedTools.length === 0) return true
+ // An unset list selects the backend's DefaultAllowedTools, which include
+ // search_knowledge. An empty list registers no built-in tool.
+ if (config.allowed_tools == null) return true
- return allowedToolsInclude(allowedTools, 'search_knowledge')
+ return allowedToolsInclude(config.allowed_tools, 'search_knowledge')
}
export function getAgentNotReadyReasonKeys(
diff --git a/frontend/src/utils/agent-tool-list.test.ts b/frontend/src/utils/agent-tool-list.test.ts
new file mode 100644
index 000000000..e6a6528a0
--- /dev/null
+++ b/frontend/src/utils/agent-tool-list.test.ts
@@ -0,0 +1,130 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import type { AgentToolCatalog } from '../api/agent'
+import {
+ allowedToolsToSave,
+ buildToolOptions,
+ effectiveToolSelection,
+ resolveLoadedAllowedTools,
+ storedExtraTools,
+} from './agent-tool-list.ts'
+import type { ScopeCapabilities } from './tool-capabilities.ts'
+
+// Shaped like GET /api/v1/agents/tools, trimmed to the cases under test.
+const catalog: AgentToolCatalog = {
+ tools: [
+ { name: 'thinking', label: '思考', description: 'd', group: 'base', requirement: {} },
+ { name: 'search_conversations', label: '回顾历史对话', description: 'd', group: 'base', requirement: {} },
+ { name: 'search_knowledge', label: '检索知识库', description: 'd', group: 'rag', requirement: { any_of: ['vector', 'keyword'] } },
+ { name: 'read_document', label: '阅读文档', description: 'd', group: 'rag', requirement: { any_of: ['vector', 'keyword', 'wiki'] } },
+ { name: 'wiki_delete_page', label: '删除Wiki', description: 'd', group: 'wiki_edit', danger: true, requirement: { all_of: ['wiki'] } },
+ ],
+ default_tools: ['search_knowledge', 'read_document', 'search_conversations'],
+ switch_managed_tools: ['web_search', 'search_memory'],
+}
+
+const noKb: ScopeCapabilities = { vector: false, keyword: false, wiki: false, graph: false, faq: false }
+const ragKb: ScopeCapabilities = { ...noKb, vector: true, keyword: true }
+const noText = () => undefined
+
+test('every catalog tool becomes a checkbox, including ones the editor has no translation for', () => {
+ const options = buildToolOptions(catalog, [], ragKb, true, (name) =>
+ name === 'thinking' ? { label: 'Thinking', description: 'Reflect' } : undefined,
+ )
+ assert.deepEqual(options.map((o) => o.value), catalog.tools.map((t) => t.name))
+ const thinking = options.find((o) => o.value === 'thinking')!
+ assert.equal(thinking.label, 'Thinking')
+ const conversations = options.find((o) => o.value === 'search_conversations')!
+ assert.equal(conversations.label, '回顾历史对话')
+ assert.equal(options.find((o) => o.value === 'wiki_delete_page')!.danger, true)
+})
+
+test('a missing capability blocks ticking a tool but never unticking it', () => {
+ const unticked = buildToolOptions(catalog, [], noKb, false, noText).find((o) => o.value === 'search_knowledge')!
+ assert.equal(unticked.unmet, true)
+ assert.equal(unticked.missKind, 'needsKb')
+ assert.equal(unticked.disabled, true)
+
+ // The knowledge-base-less agent that stores search_knowledge must be able to untick it.
+ const ticked = buildToolOptions(catalog, ['search_knowledge'], noKb, false, noText).find((o) => o.value === 'search_knowledge')!
+ assert.equal(ticked.unmet, true)
+ assert.equal(ticked.disabled, false)
+})
+
+test('stored names the catalog does not offer stay visible and removable', () => {
+ const stored = ['search_knowledge', 'web_search', 'none', 'search_memory', 'none']
+ const extras = storedExtraTools(catalog, stored, stored)
+ assert.deepEqual(extras, [
+ { value: 'web_search', kind: 'switch_managed', disabled: false },
+ { value: 'none', kind: 'unrecognized', disabled: false },
+ { value: 'search_memory', kind: 'switch_managed', disabled: false },
+ ])
+
+ // Unticking keeps the entry on screen, but it cannot be ticked again.
+ const afterUntick = storedExtraTools(catalog, stored, ['search_knowledge'])
+ assert.deepEqual(afterUntick.map((e) => [e.value, e.disabled]), [
+ ['web_search', true], ['none', true], ['search_memory', true],
+ ])
+})
+
+test('without a catalog nothing is classified, so stored values are left alone', () => {
+ assert.deepEqual(buildToolOptions(null, ['none'], ragKb, true, noText), [])
+ assert.deepEqual(storedExtraTools(null, ['none'], ['none']), [])
+})
+
+test('an unset list shows the default tools the runtime uses', () => {
+ const withKb = effectiveToolSelection(catalog, null, ragKb, true)
+ assert.equal(withKb.usesDefaults, true)
+ assert.deepEqual(withKb.names, ['search_conversations', 'search_knowledge', 'read_document'])
+ assert.deepEqual(withKb.inactive, [])
+
+ // Without a knowledge base the runtime drops the retrieval defaults, so an
+ // agent that never set a list ends up with search_conversations alone.
+ const withoutKb = effectiveToolSelection(catalog, undefined, noKb, false)
+ assert.deepEqual(withoutKb.names, ['search_conversations'])
+ assert.deepEqual(withoutKb.inactive, [])
+})
+
+test('a non-empty list registers the ticked tools the scope can serve and ignores the rest', () => {
+ const selection = effectiveToolSelection(catalog, ['search_knowledge', 'thinking', 'web_search', 'none'], noKb, false)
+ assert.equal(selection.usesDefaults, false)
+ assert.deepEqual(selection.names, ['thinking'])
+ assert.deepEqual(selection.inactive, ['search_knowledge'])
+})
+
+test('an empty list registers no built-in tool', () => {
+ const selection = effectiveToolSelection(catalog, [], ragKb, true)
+ assert.equal(selection.usesDefaults, false)
+ assert.deepEqual(selection.names, [])
+})
+
+test('a list holding only names the catalog does not offer registers no default tool', () => {
+ const selection = effectiveToolSelection(catalog, ['none', 'web_search'], ragKb, true)
+ assert.equal(selection.usesDefaults, false)
+ assert.deepEqual(selection.names, [])
+ assert.deepEqual(selection.inactive, [])
+})
+
+test('an unset list loads as the ticked default tools of a smart-reasoning agent', () => {
+ assert.deepEqual(resolveLoadedAllowedTools(null, 'smart-reasoning', catalog),
+ { tools: catalog.default_tools, keepUnset: false })
+ assert.deepEqual(resolveLoadedAllowedTools(undefined, 'smart-reasoning', catalog),
+ { tools: catalog.default_tools, keepUnset: false })
+})
+
+test('an unset list stays unset without a catalog or outside smart-reasoning', () => {
+ for (const [mode, cat] of [['smart-reasoning', null], ['quick-answer', catalog], [undefined, catalog]] as const) {
+ const loaded = resolveLoadedAllowedTools(null, mode, cat)
+ assert.deepEqual(loaded, { tools: [], keepUnset: true })
+ assert.equal(allowedToolsToSave(loaded.tools, loaded.keepUnset), null, 'an untouched unset list saves as null')
+ assert.deepEqual(allowedToolsToSave(['thinking'], loaded.keepUnset), ['thinking'], 'a ticked tool is saved as a list')
+ }
+})
+
+test('a stored list, empty or not, loads and saves as it is', () => {
+ assert.deepEqual(resolveLoadedAllowedTools([], 'smart-reasoning', catalog), { tools: [], keepUnset: false })
+ assert.deepEqual(allowedToolsToSave([], false), [])
+ assert.deepEqual(resolveLoadedAllowedTools(['knowledge_search'], 'smart-reasoning', catalog),
+ { tools: ['knowledge_search'], keepUnset: false })
+})
diff --git a/frontend/src/utils/agent-tool-list.ts b/frontend/src/utils/agent-tool-list.ts
new file mode 100644
index 000000000..818a962d4
--- /dev/null
+++ b/frontend/src/utils/agent-tool-list.ts
@@ -0,0 +1,178 @@
+/**
+ * Agent editor tool list.
+ *
+ * Builds what the agent editor shows for `allowed_tools` from the backend
+ * tool catalog (`GET /api/v1/agents/tools`), so that the checkboxes, the
+ * stored config and the tools the runtime registers can be read off the same
+ * source. Two rules keep stored values reachable:
+ * - a capability that the scope lacks only blocks ticking a tool; a ticked
+ * tool stays clickable so it can be unticked;
+ * - stored names the catalog does not offer are shown, ticked, so they can
+ * be removed instead of being saved back unseen.
+ */
+import type { AgentToolCatalog, AgentToolRequirement } from '../api/agent'
+import {
+ evaluateRequirement,
+ type RequirementMissKind,
+ type ScopeCapabilities,
+} from './tool-capabilities'
+
+export interface ToolText {
+ label: string
+ description: string
+}
+
+export interface EditorToolOption extends ToolText {
+ value: string
+ group: string
+ danger: boolean
+ /** The current knowledge base scope lacks what the tool needs. */
+ unmet: boolean
+ missKind: RequirementMissKind
+ /** Only adding is blocked, so a ticked tool is never disabled. */
+ disabled: boolean
+}
+
+export type StoredExtraKind = 'switch_managed' | 'unrecognized'
+
+export interface StoredExtraTool {
+ value: string
+ kind: StoredExtraKind
+ /** Once unticked it cannot be ticked again; the catalog does not offer it. */
+ disabled: boolean
+}
+
+function toRequirement(requirement: AgentToolRequirement | undefined) {
+ return { anyOf: requirement?.any_of, allOf: requirement?.all_of }
+}
+
+/**
+ * The selectable tools in catalog order. `text` supplies translated labels;
+ * when it returns nothing for a tool, the catalog's own label is used, so a
+ * tool the frontend has no translation for still appears.
+ */
+export function buildToolOptions(
+ catalog: AgentToolCatalog | null | undefined,
+ selected: readonly string[],
+ scope: ScopeCapabilities,
+ hasAnyKb: boolean,
+ text: (name: string) => ToolText | undefined,
+): EditorToolOption[] {
+ if (!catalog) return []
+ const chosen = new Set(selected)
+ return catalog.tools.map((tool) => {
+ const { ok, missKind } = evaluateRequirement(toRequirement(tool.requirement), scope, hasAnyKb)
+ const translated = text(tool.name)
+ return {
+ value: tool.name,
+ label: translated?.label || tool.label || tool.name,
+ description: translated?.description || tool.description || '',
+ group: tool.group,
+ danger: !!tool.danger,
+ unmet: !ok,
+ missKind,
+ disabled: !ok && !chosen.has(tool.name),
+ }
+ })
+}
+
+/**
+ * Stored or selected names the catalog does not offer as checkboxes, in the
+ * order they appear. Pass the names stored when the editor opened together
+ * with the current selection, so an entry stays visible after it is unticked.
+ */
+export function storedExtraTools(
+ catalog: AgentToolCatalog | null | undefined,
+ names: readonly string[],
+ selected: readonly string[],
+): StoredExtraTool[] {
+ // Without a catalog nothing can be classified; the values are left as they are.
+ if (!catalog) return []
+ const offered = new Set(catalog.tools.map((tool) => tool.name))
+ const switchManaged = new Set(catalog.switch_managed_tools)
+ const chosen = new Set(selected)
+ const seen = new Set<string>()
+ const extras: StoredExtraTool[] = []
+ for (const name of names) {
+ if (!name || offered.has(name) || seen.has(name)) continue
+ seen.add(name)
+ extras.push({
+ value: name,
+ kind: switchManaged.has(name) ? 'switch_managed' : 'unrecognized',
+ disabled: !chosen.has(name),
+ })
+ }
+ return extras
+}
+
+export interface EffectiveToolSelection {
+ /** Tools the runtime registers from the list, in display order. */
+ names: string[]
+ /** Ticked tools the current scope cannot serve. */
+ inactive: string[]
+ /** The list was never set, so the runtime uses the default tools. */
+ usesDefaults: boolean
+}
+
+/**
+ * The built-in tools a smart-reasoning run registers from `allowed_tools`.
+ * Mirrors the runtime: an unset list means the catalog's default tools and an
+ * empty one means none, names the catalog does not offer register nothing,
+ * and tools whose capability is missing are dropped. Switch-managed tools are
+ * left to their switches.
+ */
+export function effectiveToolSelection(
+ catalog: AgentToolCatalog | null | undefined,
+ selected: readonly string[] | null | undefined,
+ scope: ScopeCapabilities,
+ hasAnyKb: boolean,
+): EffectiveToolSelection {
+ if (!catalog) return { names: [], inactive: [], usesDefaults: false }
+ const usesDefaults = selected == null
+ const requested = new Set(selected ?? catalog.default_tools)
+ const names: string[] = []
+ const inactive: string[] = []
+ for (const tool of catalog.tools) {
+ if (!requested.has(tool.name)) continue
+ if (evaluateRequirement(toRequirement(tool.requirement), scope, hasAnyKb).ok) {
+ names.push(tool.name)
+ } else if (!usesDefaults) {
+ inactive.push(tool.name)
+ }
+ }
+ return { names, inactive, usesDefaults }
+}
+
+export interface LoadedAllowedTools {
+ /** The list to edit, with retired names already rewritten by the caller. */
+ tools: string[]
+ /**
+ * The stored list was never set and stays unset: saving an untouched,
+ * empty list sends null so the agent keeps the default tools.
+ */
+ keepUnset: boolean
+}
+
+/**
+ * How the editor loads a stored `allowed_tools`. An unset list selects the
+ * default tools at runtime, while an empty one means none, so an unset list
+ * must not turn into an empty one on save. For a smart-reasoning agent the
+ * catalog's default tools are written in and ticked, so the editor shows what
+ * runs; without a catalog, or for another mode, the list stays unset.
+ */
+export function resolveLoadedAllowedTools(
+ stored: readonly string[] | null | undefined,
+ agentMode: string | undefined,
+ catalog: AgentToolCatalog | null | undefined,
+): LoadedAllowedTools {
+ if (stored != null) return { tools: [...stored], keepUnset: false }
+ if (agentMode === 'smart-reasoning' && catalog) {
+ return { tools: [...catalog.default_tools], keepUnset: false }
+ }
+ return { tools: [], keepUnset: true }
+}
+
+/** The `allowed_tools` value to send on save. */
+export function allowedToolsToSave(tools: readonly string[], keepUnset: boolean): string[] | null {
+ return keepUnset && tools.length === 0 ? null : [...tools]
+}
diff --git a/frontend/src/utils/tool-capabilities.ts b/frontend/src/utils/tool-capabilities.ts
index 6f7ff91a9..68d98e849 100644
--- a/frontend/src/utils/tool-capabilities.ts
+++ b/frontend/src/utils/tool-capabilities.ts
@@ -123,8 +123,20 @@ export function evaluateToolRequirement(
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.
+ return evaluateRequirement(TOOL_CAPABILITY_REQUIREMENTS[toolName], scope, hasAnyKb);
+}
+
+/**
+ * Evaluate a requirement given directly, such as one served by the backend
+ * tool catalog (`GET /api/v1/agents/tools`). An absent or empty requirement
+ * is always satisfied.
+ */
+export function evaluateRequirement(
+ req: Pick<ToolRequirement, 'anyOf' | 'allOf'> | undefined,
+ scope: ScopeCapabilities,
+ hasAnyKb: boolean,
+): { ok: boolean; missKind: RequirementMissKind } {
+ // No requirements: always available.
if (!req || (!req.anyOf?.length && !req.allOf?.length)) {
return { ok: true, missKind: 'none' };
}
diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue
index 26a4a702b..50dccda1c 100644
--- a/frontend/src/views/agent/AgentEditorModal.vue
+++ b/frontend/src/views/agent/AgentEditorModal.vue
@@ -1171,13 +1171,36 @@
</span>
</div>
<span v-if="tool.description" class="tool-card-desc">{{ tool.description }}</span>
- <span v-if="tool.disabled && tool.disabledReason" class="tool-card-hint">
+ <span v-if="tool.unmet && tool.disabledReason" class="tool-card-hint">
{{ tool.disabledReason }}
</span>
</div>
</t-checkbox>
</div>
</section>
+ <section v-if="storedExtras.length > 0" class="tool-group tool-group--stored">
+ <header class="tool-group-header">
+ <span class="tool-group-bar" />
+ <span class="tool-group-title">{{ $t('agentEditor.tools.groupStored') }}</span>
+ <span class="tool-group-count">{{ storedExtras.length }}</span>
+ </header>
+ <div class="tool-grid">
+ <t-checkbox v-for="extra in storedExtras" :key="extra.value" :value="extra.value"
+ :disabled="extra.disabled"
+ :class="['tool-card', { 'tool-card--disabled': extra.disabled }]">
+ <div class="tool-card-body">
+ <div class="tool-card-head">
+ <span class="tool-card-name">{{ extra.value }}</span>
+ </div>
+ <span class="tool-card-desc">
+ {{ extra.kind === 'switch_managed'
+ ? $t('agentEditor.tools.switchManagedDesc')
+ : $t('agentEditor.tools.unrecognizedDesc') }}
+ </span>
+ </div>
+ </t-checkbox>
+ </div>
+ </section>
</t-checkbox-group>
</div>
</div>
@@ -1847,6 +1870,8 @@ import {
type CustomAgent,
type PlaceholderDefinition,
type AgentTypePreset,
+ type AgentToolCatalog,
+ type AllowedToolsWarnings,
type AgentType,
type AgentTypeKBFilter,
type KBCapabilities,
@@ -1884,11 +1909,18 @@ import { getRootZoom, rectToCssPx } from '@/utils/zoom';
import { integrationSectionKey } from '@/config/settingsRoute';
import { toolboxLocation } from '@/config/toolbox';
import {
- evaluateToolRequirement,
deriveKbFilterFromTools,
type RequirementMissKind,
type ScopeCapabilities,
} from '@/utils/tool-capabilities';
+import {
+ allowedToolsToSave as allowedToolsForSave,
+ buildToolOptions,
+ effectiveToolSelection,
+ resolveLoadedAllowedTools,
+ storedExtraTools,
+ type ToolText,
+} from '@/utils/agent-tool-list';
import {
clampLevel,
levelDescriptionKey,
@@ -2449,38 +2481,37 @@ const kbSelectionMode = ref<'all' | 'selected' | 'none'>('none');
// MCP 服务选择模式:all=全部, selected=指定, none=不使用
const mcpSelectionMode = ref<'all' | 'selected' | 'none'>('none');
-// 可用工具列表(与后台 internal/agent/tools/definitions.go 保持一致)
-// group 决定 UI 分组:base / rag / wiki_read / wiki_edit / wiki_issue / data
-// danger: 写类破坏性工具,UI 上给出显著提示
-// 工具的 KB 能力依赖关系统一在 `@/utils/tool-capabilities` 声明,
-// `availableTools` 通过 `evaluateToolRequirement` 读取,不在这里重复维护。
-const allTools = computed(() => [
- // 基础思考类
- { 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' },
- // 知识库检索 / 文档阅读(旧的 grep_chunks / knowledge_search / list_knowledge_chunks /
- // get_document_info 已合并,旧配置加载时由 normalizeLegacyToolNames 映射到新名字)
- { value: 'search_knowledge', label: t('agentEditor.tools.searchKnowledge'), description: t('agentEditor.tools.searchKnowledgeDesc'), group: 'rag' },
- { value: 'read_document', label: t('agentEditor.tools.readDocument'), description: t('agentEditor.tools.readDocumentDesc'), group: 'rag' },
- { value: 'list_documents', label: t('agentEditor.tools.listDocuments'), description: t('agentEditor.tools.listDocumentsDesc'), group: 'rag' },
- { value: 'query_knowledge_graph', label: t('agentEditor.tools.queryGraph'), description: t('agentEditor.tools.queryGraphDesc'), 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'), group: 'wiki_read' },
- { value: 'wiki_read_page', label: t('agentEditor.tools.wikiReadPage'), description: t('agentEditor.tools.wikiReadPageDesc'), 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'), 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'), 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' },
-]);
+// 可选工具来自后端工具目录(GET /api/v1/agents/tools):工具本身、分组、danger 标记
+// 和知识库能力要求都以后端为准,前端不再维护工具清单。这里只提供翻译文案;
+// 没有翻译的工具(例如后端新增的工具)直接使用目录里的名称和描述,不会被隐藏。
+const agentToolCatalog = ref<AgentToolCatalog | null>(null);
+// 打开编辑器时已保存的 allowed_tools,用来在取消勾选后继续展示目录之外的保存值。
+const storedToolNames = ref<string[]>([]);
+// allowed_tools 未设置(null)表示使用后端默认工具,空列表表示不使用内置工具。
+// 加载时无法显式写入默认工具(工具目录不可用,或不是智能推理模式)时保持未设置,
+// 列表未被修改则保存时原样发送 null。
+const keepAllowedToolsUnset = ref(false);
+const toolTexts = computed<Record<string, ToolText>>(() => ({
+ thinking: { label: t('agentEditor.tools.thinking'), description: t('agentEditor.tools.thinkingDesc') },
+ todo_write: { label: t('agentEditor.tools.todoWrite'), description: t('agentEditor.tools.todoWriteDesc') },
+ search_conversations: { label: t('agentEditor.tools.searchConversations'), description: t('agentEditor.tools.searchConversationsDesc') },
+ search_knowledge: { label: t('agentEditor.tools.searchKnowledge'), description: t('agentEditor.tools.searchKnowledgeDesc') },
+ read_document: { label: t('agentEditor.tools.readDocument'), description: t('agentEditor.tools.readDocumentDesc') },
+ list_documents: { label: t('agentEditor.tools.listDocuments'), description: t('agentEditor.tools.listDocumentsDesc') },
+ query_knowledge_graph: { label: t('agentEditor.tools.queryGraph'), description: t('agentEditor.tools.queryGraphDesc') },
+ database_query: { label: t('agentEditor.tools.dbQuery'), description: t('agentEditor.tools.dbQueryDesc') },
+ wiki_search: { label: t('agentEditor.tools.wikiSearch'), description: t('agentEditor.tools.wikiSearchDesc') },
+ wiki_read_page: { label: t('agentEditor.tools.wikiReadPage'), description: t('agentEditor.tools.wikiReadPageDesc') },
+ wiki_flag_issue: { label: t('agentEditor.tools.wikiFlagIssue'), description: t('agentEditor.tools.wikiFlagIssueDesc') },
+ wiki_write_page: { label: t('agentEditor.tools.wikiWritePage'), description: t('agentEditor.tools.wikiWritePageDesc') },
+ wiki_replace_text: { label: t('agentEditor.tools.wikiReplaceText'), description: t('agentEditor.tools.wikiReplaceTextDesc') },
+ wiki_rename_page: { label: t('agentEditor.tools.wikiRenamePage'), description: t('agentEditor.tools.wikiRenamePageDesc') },
+ wiki_delete_page: { label: t('agentEditor.tools.wikiDeletePage'), description: t('agentEditor.tools.wikiDeletePageDesc') },
+ wiki_read_issue: { label: t('agentEditor.tools.wikiReadIssue'), description: t('agentEditor.tools.wikiReadIssueDesc') },
+ wiki_update_issue: { label: t('agentEditor.tools.wikiUpdateIssue'), description: t('agentEditor.tools.wikiUpdateIssueDesc') },
+ data_analysis: { label: t('agentEditor.tools.dataAnalysis'), description: t('agentEditor.tools.dataAnalysisDesc') },
+ data_schema: { label: t('agentEditor.tools.dataSchema'), description: t('agentEditor.tools.dataSchemaDesc') },
+}));
// 工具分组元信息
const toolGroups = computed(() => [
@@ -2579,19 +2610,33 @@ const missKindToReason = (kind: RequirementMissKind): string | undefined => {
}
};
+// 保存时的 allowed_tools:保持未设置的列表在未被修改时以 null 发送。
+const allowedToolsToSave = (): string[] | null =>
+ allowedToolsForSave(formData.value.config.allowed_tools || [], keepAllowedToolsUnset.value);
+
+// 能力不满足时只禁止新勾选;已勾选的工具保持可点击,以便取消勾选(并显示原因)。
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: !ok,
- disabledReason: ok ? undefined : missKindToReason(missKind),
- };
- });
+ const options = buildToolOptions(
+ agentToolCatalog.value,
+ formData.value.config.allowed_tools || [],
+ scopeCapabilities.value,
+ hasKnowledgeBase.value,
+ (name) => toolTexts.value[name],
+ );
+ return options.map(tool => ({
+ ...tool,
+ disabledReason: tool.unmet ? missKindToReason(tool.missKind) : undefined,
+ }));
});
+// 已保存但目录未提供的工具:开关控制的工具或无法识别的名称。
+// 勾选状态展示出来以便移除,取消勾选后不能再勾回。
+const storedExtras = computed(() => storedExtraTools(
+ agentToolCatalog.value,
+ [...storedToolNames.value, ...(formData.value.config.allowed_tools || [])],
+ formData.value.config.allowed_tools || [],
+));
+
// 按分组切片后的工具列表,用于模板分组渲染
const groupedAvailableTools = computed(() => {
const map: Record<string, typeof availableTools.value> = {};
@@ -2600,7 +2645,12 @@ const groupedAvailableTools = computed(() => {
if (!map[g]) map[g] = [];
map[g].push(tool);
}
- return toolGroups.value
+ // 后端新增的分组没有文案时以分组名显示,不隐藏其中的工具
+ const known = new Set(toolGroups.value.map(g => g.key));
+ const extraGroups = Object.keys(map)
+ .filter(key => !known.has(key))
+ .map(key => ({ key, label: key }));
+ return [...toolGroups.value, ...extraGroups]
.map(g => ({
...g,
tools: map[g.key] || [],
@@ -2609,21 +2659,28 @@ const groupedAvailableTools = computed(() => {
});
// ==================== 有效工具预览 ====================
-// 最终运行时智能体实际能使用的工具集合(仅做预览展示)
-// 规则:基于 allowed_tools 过滤
-// 1) 勾选但缺失对应能力(无 KB / 无 Wiki 能力 KB)的工具会被灰显/隐藏
-// 2) 无论是否勾选,web_search / web_fetch 随 web_search_enabled 出现
-// 3) 当 kb_selection_mode === 'none' 时,RAG/Wiki 工具都视为不可用
+// 最终运行时智能体实际能使用的工具集合(仅做预览展示),与运行时注册规则一致:
+// 1) allowed_tools 未设置(null)时,运行时使用目录中的默认工具(default_tools),
+// 空列表则不注册任何内置工具;
+// 2) 勾选但缺失对应能力(无 KB / 无 Wiki 能力 KB)的工具不会生效,灰显展示;
+// 3) 目录之外的保存值(开关控制的工具、无法识别的名称)自身不会注册任何工具;
+// 4) 无论是否勾选,web_search / web_fetch 随 web_search_enabled 出现。
+const effectiveSelection = computed(() => effectiveToolSelection(
+ agentToolCatalog.value,
+ allowedToolsToSave(),
+ scopeCapabilities.value,
+ hasKnowledgeBase.value,
+));
const effectiveTools = computed(() => {
- const chosen = new Set(formData.value.config.allowed_tools || []);
+ const active = new Set(effectiveSelection.value.names);
+ const inactive = new Set(effectiveSelection.value.inactive);
const items: Array<{ value: string; label: string; reason?: string; active: boolean }> = [];
+ // 按工具目录顺序展示
for (const tool of availableTools.value) {
- const picked = chosen.has(tool.value);
- if (!picked) continue;
- if (tool.disabled) {
- items.push({ value: tool.value, label: tool.label, active: false, reason: tool.disabledReason });
- } else {
+ if (active.has(tool.value)) {
items.push({ value: tool.value, label: tool.label, active: true });
+ } else if (inactive.has(tool.value)) {
+ items.push({ value: tool.value, label: tool.label, active: false, reason: tool.disabledReason });
}
}
if (formData.value.config.web_search_enabled) {
@@ -3553,8 +3610,9 @@ watch(() => props.visible, async (val) => {
if (!agentData.config.knowledge_bases) agentData.config.knowledge_bases = [];
// 旧配置里可能还带着已合并的工具名(knowledge_search / grep_chunks /
// list_knowledge_chunks / get_document_info / wiki_read_source_doc),
- // 映射到新名字并去重,否则复选框对不上 allTools。
- agentData.config.allowed_tools = normalizeLegacyToolNames(agentData.config.allowed_tools);
+ // 映射到新名字并去重,否则复选框对不上工具目录。
+ const storedAllowedTools = agentData.config.allowed_tools;
+ agentData.config.allowed_tools = normalizeLegacyToolNames(storedAllowedTools);
if (!agentData.config.mcp_services) agentData.config.mcp_services = [];
// 授权等待超时:旧数据缺省时用默认 600 秒
if (agentData.config.mcp_auth_wait_timeout == null || agentData.config.mcp_auth_wait_timeout <= 0) {
@@ -3576,6 +3634,17 @@ watch(() => props.visible, async (val) => {
const isAgent = agentData.config.max_iterations < 0 || agentData.config.max_iterations > 1 || (agentData.config.allowed_tools && agentData.config.allowed_tools.length > 0);
agentData.config.agent_mode = isAgent ? 'smart-reasoning' : 'quick-answer';
}
+ // 从未设置工具列表(null)的智能推理智能体使用后端默认工具:把默认工具显式写入并勾选,
+ // 否则空列表一经保存就变成"不使用内置工具",悄悄改变行为。无法写入时保持未设置。
+ // 放在模式推断之后,旧数据推断出的智能推理模式同样适用。
+ const loadedTools = resolveLoadedAllowedTools(
+ storedAllowedTools == null ? null : agentData.config.allowed_tools,
+ agentData.config.agent_mode,
+ agentToolCatalog.value,
+ );
+ agentData.config.allowed_tools = loadedTools.tools;
+ keepAllowedToolsUnset.value = loadedTools.keepUnset;
+ storedToolNames.value = [...loadedTools.tools];
// 设置初始化标志,防止 watch 自动添加工具
isInitializing.value = true;
@@ -3597,6 +3666,8 @@ watch(() => props.visible, async (val) => {
void loadAgentIntegrationCounts(agentData.id);
} else {
// 创建新智能体,使用系统默认值
+ storedToolNames.value = [];
+ keepAllowedToolsUnset.value = false;
const newFormData = JSON.parse(JSON.stringify(defaultFormData));
// 应用系统默认检索参数
newFormData.config.embedding_top_k = defaultEmbeddingTopK.value;
@@ -3847,7 +3918,10 @@ watch(agentMode, (val, _oldVal) => {
// 切换到 Agent 模式,根据知识库配置启用工具。
// 注意:默认不注入 thinking / todo_write —— 它们用于显式反思或多步计划,
// 会显著增加 token 消耗,用户按需手动勾选。
- if (formData.value.config.allowed_tools.length === 0) {
+ // 加载智能体时不补工具:空列表表示"不使用内置工具",是保存的值而不是待填的空白。
+ // 用户主动切换模式后列表即为显式选择,不再保持未设置。
+ if (!isInitializing.value) keepAllowedToolsUnset.value = false;
+ if (!isInitializing.value && formData.value.config.allowed_tools.length === 0) {
const tools: string[] = [];
if (hasRagKnowledgeBase.value) {
tools.push(...knowledgeBaseTools);
@@ -3899,8 +3973,8 @@ watch(agentMode, (val, _oldVal) => {
// 监听知识库启用状态变化:
// - 从"无"变"有":自动补齐 RAG 基础工具,方便用户开箱即用(仅 seed 行为);
-// - 从"有"变"无":**不再**自动擦工具,依赖不满足时由 `availableTools` 灰显
-// + 运行时工具注册器过滤。`allowed_tools` 代表用户意图,只应在用户显式操作
+// - 从"有"变"无":**不再**自动擦工具,依赖不满足时由 `availableTools` 标注原因
+// (未勾选的工具禁止勾选)+ 运行时工具注册器过滤。`allowed_tools` 代表用户意图,只应在用户显式操作
// (切 agent_type / 切 agent_mode / 手勾工具)时变更。
// 历史背景:旧版本在 KB 能力消失时会擦除 KB/Wiki 工具,导致用户切换
// `kb_selection_mode` 到 "selected"、但尚未勾具体 KB 的过渡期里静默丢失工具,
@@ -3914,7 +3988,8 @@ watch(hasKnowledgeBase, (hasKB, oldHasKB) => {
// 初始化期间或非 Agent 模式下不自动调整工具
if (isInitializing.value || !isAgentMode.value) return;
- if (hasKB && !oldHasKB) {
+ // 保持未设置(使用默认工具)时不补工具,否则保存后会丢掉默认工具。
+ if (hasKB && !oldHasKB && !keepAllowedToolsUnset.value) {
// 从无知识库变为有知识库,seed 默认的 RAG 工具(仅补齐未勾的)
const currentTools = formData.value.config.allowed_tools || [];
const toolsToAdd = knowledgeBaseTools.filter((tool: string) => !currentTools.includes(tool));
@@ -4008,6 +4083,16 @@ const applyPromptTemplateDefaults = (cfg: PromptTemplatesConfig | null) => {
}
};
+// 保存成功但后端调整了工具列表时提示用户(保留了无法识别的名称,或移除了由其他设置控制的工具)
+const notifyAllowedToolsWarnings = (warnings?: AllowedToolsWarnings) => {
+ if (warnings?.kept_unknown?.length) {
+ MessagePlugin.warning(t('agentEditor.tools.keptUnknownWarning', { names: warnings.kept_unknown.join(', ') }));
+ }
+ if (warnings?.dropped?.length) {
+ MessagePlugin.warning(t('agentEditor.tools.droppedWarning', { names: warnings.dropped.join(', ') }));
+ }
+};
+
// 加载依赖数据(复用空间级缓存,避免重复请求)
const loadDependencies = async () => {
try {
@@ -4031,6 +4116,7 @@ const loadDependencies = async () => {
kbOptions.value = [...myKbs, ...sharedKbs];
agentTypePresets.value = editorResources.agentTypePresets as AgentTypePreset[];
+ agentToolCatalog.value = editorResources.agentTools as AgentToolCatalog | null;
applyPromptTemplateDefaults(editorResources.promptTemplates);
storageEngineStatus.value = editorResources.storageStatus;
@@ -4958,7 +5044,7 @@ const handleSave = async () => {
if (hostOnly.value) formData.value.config.sandbox_config_id = ''
- const payload = { ...formData.value, config: serializeAgentPrompts(formData.value.config, promptTemplates.value) };
+ const payload = { ...formData.value, config: serializeAgentPrompts({ ...formData.value.config, allowed_tools: allowedToolsToSave() }, promptTemplates.value) };
saving.value = true;
try {
if (editorMode.value === 'create') {
@@ -4969,17 +5055,26 @@ const handleSave = async () => {
}
savedAgent.value = created;
formData.value.id = created.id;
+ // 后端可能改写了工具列表(旧名称映射、移除由其他设置控制的工具),与之同步,
+ // 避免再次保存时重复提示。
+ if (Array.isArray(created.config?.allowed_tools)) {
+ formData.value.config.allowed_tools = normalizeLegacyToolNames(created.config.allowed_tools);
+ storedToolNames.value = [...formData.value.config.allowed_tools];
+ keepAllowedToolsUnset.value = false;
+ }
modalShell.markClean();
markContextualGuideDone('agentCreate')
currentSection.value = 'basic';
void loadAgentIntegrationCounts(created.id);
MessagePlugin.success(t('agent.messages.created'));
+ notifyAllowedToolsWarnings(result?.allowed_tools_warnings);
emit('success', created);
} else {
- await updateAgent(formData.value.id, payload);
+ const updated: any = await updateAgent(formData.value.id, payload);
MessagePlugin.success(t('agent.messages.updated'));
emit('success');
handleClose();
+ notifyAllowedToolsWarnings(updated?.allowed_tools_warnings);
}
} catch (e: any) {
MessagePlugin.error(e?.message || t('agent.messages.saveFailed'));
diff --git a/internal/agent/tools/allowed.go b/internal/agent/tools/allowed.go
new file mode 100644
index 000000000..903e42982
--- /dev/null
+++ b/internal/agent/tools/allowed.go
@@ -0,0 +1,77 @@
+package tools
+
+// EffectiveAllowedTools returns the built-in tools an agent's allowed_tools
+// value asks for. A nil list means the value was never set, as on agents
+// saved before allowed_tools existed, and selects the default tools. Any
+// other list, including an empty one, is taken as given: an empty list means
+// no built-in tools. Retired names are rewritten to their successors.
+//
+// Tool registration, the session config and the rerank requirement all go
+// through this function, so they cannot disagree about what an empty list
+// means.
+func EffectiveAllowedTools(allowed []string) []string {
+ if allowed == nil {
+ return DefaultAllowedTools()
+ }
+ if len(allowed) == 0 {
+ return []string{}
+ }
+ return NormalizeAllowedTools(allowed)
+}
+
+// AllowedToolsCheck is the outcome of checking an allowed_tools list on save.
+type AllowedToolsCheck struct {
+ // Tools is the list to store: retired names rewritten, duplicates and
+ // switch-managed tools removed. Nil when the request left the list unset.
+ Tools []string
+ // Rejected are names no built-in tool answers to that the request adds.
+ Rejected []string
+ // KeptUnknown are such names that were already stored. They are kept so
+ // that an agent saved before an upgrade can still be saved.
+ KeptUnknown []string
+ // Dropped are names removed from the list because naming them there has
+ // no effect: switch-managed tools, which other agent settings decide on,
+ // and retired skill tools without a successor.
+ Dropped []string
+}
+
+// CheckAllowedTools validates a requested allowed_tools list against the
+// selectable tools. stored is the list currently saved for the agent, nil for
+// a new agent.
+func CheckAllowedTools(stored, requested []string) AllowedToolsCheck {
+ if requested == nil {
+ return AllowedToolsCheck{}
+ }
+ selectable := make(map[string]struct{})
+ for _, tool := range AvailableToolDefinitions() {
+ selectable[tool.Name] = struct{}{}
+ }
+ dropped := make(map[string]struct{})
+ for _, name := range SwitchManagedTools() {
+ dropped[name] = struct{}{}
+ }
+ for _, name := range []string{LegacyToolReadSkill, LegacyToolExecuteSkillScript, LegacyToolReadSandboxFile} {
+ dropped[name] = struct{}{}
+ }
+ already := make(map[string]struct{}, len(stored))
+ for _, name := range NormalizeAllowedTools(stored) {
+ already[name] = struct{}{}
+ }
+
+ check := AllowedToolsCheck{Tools: []string{}}
+ for _, name := range NormalizeAllowedTools(requested) {
+ if _, ok := dropped[name]; ok {
+ check.Dropped = append(check.Dropped, name)
+ continue
+ }
+ if _, ok := selectable[name]; !ok {
+ if _, kept := already[name]; !kept {
+ check.Rejected = append(check.Rejected, name)
+ continue
+ }
+ check.KeptUnknown = append(check.KeptUnknown, name)
+ }
+ check.Tools = append(check.Tools, name)
+ }
+ return check
+}
diff --git a/internal/agent/tools/allowed_test.go b/internal/agent/tools/allowed_test.go
new file mode 100644
index 000000000..cc80d790d
--- /dev/null
+++ b/internal/agent/tools/allowed_test.go
@@ -0,0 +1,73 @@
+package tools
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestEffectiveAllowedToolsSeparatesUnsetFromEmpty(t *testing.T) {
+ require.Equal(t, DefaultAllowedTools(), EffectiveAllowedTools(nil), "an unset list selects the defaults")
+
+ empty := EffectiveAllowedTools([]string{})
+ require.NotNil(t, empty, "an empty list must stay distinguishable from an unset one")
+ require.Empty(t, empty, "an empty list means no built-in tools")
+
+ require.Equal(t,
+ []string{ToolSearchKnowledge, ToolThinking},
+ EffectiveAllowedTools([]string{LegacyToolKnowledgeSearch, ToolThinking, LegacyToolGrepChunks}),
+ "retired names map to their successors without duplicates")
+}
+
+func TestCheckAllowedTools(t *testing.T) {
+ t.Run("an unset list stays unset", func(t *testing.T) {
+ require.Equal(t, AllowedToolsCheck{}, CheckAllowedTools([]string{"none"}, nil))
+ })
+
+ t.Run("an empty list is stored as given", func(t *testing.T) {
+ check := CheckAllowedTools(nil, []string{})
+ require.NotNil(t, check.Tools)
+ require.Empty(t, check.Tools)
+ })
+
+ t.Run("retired names are rewritten", func(t *testing.T) {
+ check := CheckAllowedTools(nil, []string{LegacyToolKnowledgeSearch, LegacyToolGetDocumentInfo})
+ require.Equal(t, []string{ToolSearchKnowledge, ToolReadDocument}, check.Tools)
+ require.Empty(t, check.Rejected)
+ })
+
+ t.Run("names the request adds that no tool answers to are rejected", func(t *testing.T) {
+ check := CheckAllowedTools([]string{ToolThinking}, []string{ToolThinking, "none", "serch_knowledge"})
+ require.Equal(t, []string{"none", "serch_knowledge"}, check.Rejected)
+ })
+
+ t.Run("unknown names already stored are kept", func(t *testing.T) {
+ check := CheckAllowedTools([]string{"none", ToolThinking}, []string{ToolThinking, "none"})
+ require.Empty(t, check.Rejected)
+ require.Equal(t, []string{"none"}, check.KeptUnknown)
+ require.Equal(t, []string{ToolThinking, "none"}, check.Tools)
+ })
+
+ t.Run("switch-managed tools are dropped", func(t *testing.T) {
+ check := CheckAllowedTools(nil, []string{ToolWebSearch, ToolThinking, ToolSearchMemory, ToolDiscoverMCPTools})
+ require.Equal(t, []string{ToolThinking}, check.Tools)
+ require.Equal(t, []string{ToolWebSearch, ToolSearchMemory, ToolDiscoverMCPTools}, check.Dropped)
+ require.Empty(t, check.Rejected)
+ })
+
+ t.Run("retired skill tools without a successor are dropped", func(t *testing.T) {
+ check := CheckAllowedTools(
+ []string{LegacyToolReadSkill},
+ []string{LegacyToolReadSkill, LegacyToolExecuteSkillScript},
+ )
+ require.Empty(t, check.Tools)
+ require.Equal(t, []string{LegacyToolReadSkill, LegacyToolExecuteSkillScript}, check.Dropped)
+ require.Empty(t, check.KeptUnknown)
+ })
+
+ t.Run("a retired name stored under its old spelling still counts as stored", func(t *testing.T) {
+ check := CheckAllowedTools([]string{LegacyToolKnowledgeSearch}, []string{ToolSearchKnowledge})
+ require.Empty(t, check.Rejected)
+ require.Empty(t, check.KeptUnknown)
+ })
+}
diff --git a/internal/agent/tools/catalog.go b/internal/agent/tools/catalog.go
new file mode 100644
index 000000000..db3fc01e5
--- /dev/null
+++ b/internal/agent/tools/catalog.go
@@ -0,0 +1,51 @@
+package tools
+
+// AgentToolRequirement is the JSON form of a tool's ToolRequirement: the
+// knowledge base capabilities the agent's scope must expose for the tool to
+// be registered.
+type AgentToolRequirement struct {
+ AnyOf []KBCapability `json:"any_of,omitempty"`
+ AllOf []KBCapability `json:"all_of,omitempty"`
+}
+
+// AgentToolInfo is a selectable tool together with its capability
+// requirement.
+type AgentToolInfo struct {
+ AvailableTool
+ Requirement AgentToolRequirement `json:"requirement"`
+}
+
+// AgentToolCatalog is everything the agent editor needs to show an
+// allowed_tools list the way the runtime reads it.
+type AgentToolCatalog struct {
+ // Tools are the selectable tools, in display order.
+ Tools []AgentToolInfo `json:"tools"`
+ // DefaultTools apply when an agent's allowed_tools was never set (null).
+ DefaultTools []string `json:"default_tools"`
+ // SwitchManagedTools follow other agent settings; naming them in the list
+ // does not register them.
+ SwitchManagedTools []string `json:"switch_managed_tools"`
+}
+
+// BuildAgentToolCatalog assembles the catalog from the tool definitions and
+// the capability map, so the editor never keeps its own copy of either.
+func BuildAgentToolCatalog() AgentToolCatalog {
+ definitions := AvailableToolDefinitions()
+ infos := make([]AgentToolInfo, 0, len(definitions))
+ for _, definition := range definitions {
+ requirement := ToolCapabilityRequirements[definition.Name]
+ infos = append(infos, AgentToolInfo{
+ AvailableTool: definition,
+ // Copies, so a caller cannot reach into the shared capability map.
+ Requirement: AgentToolRequirement{
+ AnyOf: append([]KBCapability(nil), requirement.AnyOf...),
+ AllOf: append([]KBCapability(nil), requirement.AllOf...),
+ },
+ })
+ }
+ return AgentToolCatalog{
+ Tools: infos,
+ DefaultTools: DefaultAllowedTools(),
+ SwitchManagedTools: SwitchManagedTools(),
+ }
+}
diff --git a/internal/agent/tools/catalog_test.go b/internal/agent/tools/catalog_test.go
new file mode 100644
index 000000000..0292baba9
--- /dev/null
+++ b/internal/agent/tools/catalog_test.go
@@ -0,0 +1,53 @@
+package tools
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildAgentToolCatalogDescribesEverySelectableTool(t *testing.T) {
+ catalog := BuildAgentToolCatalog()
+ groups := map[string]bool{
+ ToolGroupBase: true, ToolGroupRAG: true, ToolGroupWikiRead: true,
+ ToolGroupWikiEdit: true, ToolGroupWikiIssue: true, ToolGroupData: true,
+ }
+
+ require.Len(t, catalog.Tools, len(AvailableToolDefinitions()))
+ selectable := make(map[string]bool, len(catalog.Tools))
+ for _, tool := range catalog.Tools {
+ require.False(t, selectable[tool.Name], "duplicate tool %s", tool.Name)
+ selectable[tool.Name] = true
+ require.True(t, groups[tool.Group], "tool %s has unknown group %q", tool.Name, tool.Group)
+ requirement := ToolCapabilityRequirements[tool.Name]
+ require.Equal(t, requirement.AnyOf, nilIfEmpty(tool.Requirement.AnyOf), tool.Name)
+ require.Equal(t, requirement.AllOf, nilIfEmpty(tool.Requirement.AllOf), tool.Name)
+ }
+ // The editor never offered this tool before it read the catalog.
+ require.True(t, selectable[ToolSearchConversations])
+
+ for _, name := range catalog.DefaultTools {
+ require.True(t, selectable[name], "default tool %s must be selectable", name)
+ }
+ for _, managed := range catalog.SwitchManagedTools {
+ require.False(t, selectable[managed], "switch-managed %s must not be a checkbox", managed)
+ }
+}
+
+func TestBuildAgentToolCatalogDoesNotShareTheCapabilityMap(t *testing.T) {
+ catalog := BuildAgentToolCatalog()
+ for _, tool := range catalog.Tools {
+ if tool.Name != ToolSearchKnowledge {
+ continue
+ }
+ tool.Requirement.AnyOf[0] = CapGraph
+ }
+ require.Equal(t, CapVector, ToolCapabilityRequirements[ToolSearchKnowledge].AnyOf[0])
+}
+
+func nilIfEmpty(values []KBCapability) []KBCapability {
+ if len(values) == 0 {
+ return nil
+ }
+ return values
+}
diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.go
index 45e87bce1..9d64e9897 100644
--- a/internal/agent/tools/definitions.go
+++ b/internal/agent/tools/definitions.go
@@ -75,40 +75,109 @@ const (
ToolWikiUpdateIssue = "wiki_update_issue"
)
-// AvailableTool defines a simple tool metadata used by settings APIs.
+// Tool groups the agent editor sections its checkboxes by.
+const (
+ ToolGroupBase = "base"
+ ToolGroupRAG = "rag"
+ ToolGroupWikiRead = "wiki_read"
+ ToolGroupWikiEdit = "wiki_edit"
+ ToolGroupWikiIssue = "wiki_issue"
+ ToolGroupData = "data"
+)
+
+// AvailableTool describes a tool an agent's allowed_tools list may select.
+// The agent editor renders its tool checkboxes from these definitions.
type AvailableTool struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
+ Group string `json:"group"`
+ // Danger marks tools that modify content, which the editor highlights.
+ Danger bool `json:"danger,omitempty"`
}
-// AvailableToolDefinitions returns the list of tools exposed to the UI.
-// Keep this in sync with registered tools in this package.
+// AvailableToolDefinitions returns the tools an agent's allowed_tools list
+// may select, in the order the agent editor shows them. Keep this in sync
+// with registered tools in this package.
func AvailableToolDefinitions() []AvailableTool {
return []AvailableTool{
- {Name: ToolThinking, Label: "思考", Description: "动态和反思性的问题解决思考工具"},
- {Name: ToolTodoWrite, Label: "制定计划", Description: "创建结构化的研究计划"},
- {Name: ToolSearchKnowledge, Label: "检索知识库", Description: "语义、关键词或混合检索知识库分块"},
- {Name: ToolReadDocument, Label: "阅读文档", Description: "读取文档元数据与分块内容,支持分页和文内查找"},
- {Name: ToolListDocuments, Label: "浏览文档列表", Description: "分页列出知识库中的文档"},
- {Name: ToolQueryKnowledgeGraph, Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
+ {Name: ToolThinking, Label: "思考", Description: "动态和反思性的问题解决思考工具", Group: ToolGroupBase},
+ {Name: ToolTodoWrite, Label: "制定计划", Description: "创建结构化的研究计划", Group: ToolGroupBase},
{
Name: ToolSearchConversations,
Label: "回顾历史对话",
Description: "在用户自己的历史会话中查找之前聊过的内容",
+ Group: ToolGroupBase,
+ },
+ {Name: ToolSearchKnowledge, Label: "检索知识库", Description: "语义、关键词或混合检索知识库分块", Group: ToolGroupRAG},
+ {Name: ToolReadDocument, Label: "阅读文档", Description: "读取文档元数据与分块内容,支持分页和文内查找", Group: ToolGroupRAG},
+ {Name: ToolListDocuments, Label: "浏览文档列表", Description: "分页列出知识库中的文档", Group: ToolGroupRAG},
+ {Name: ToolQueryKnowledgeGraph, Label: "查询知识图谱", Description: "从知识图谱中查询关系", Group: ToolGroupRAG},
+ {Name: ToolDatabaseQuery, Label: "查询数据库", Description: "查询数据库中的信息", Group: ToolGroupRAG},
+ {Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面", Group: ToolGroupWikiRead},
+ {Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容", Group: ToolGroupWikiRead},
+ {
+ Name: ToolWikiFlagIssue,
+ Label: "标记Wiki问题",
+ Description: "标记页面中存在的事实错误或合并冲突问题",
+ Group: ToolGroupWikiRead,
+ },
+ {
+ Name: ToolWikiWritePage,
+ Label: "创建/覆盖Wiki",
+ Description: "创建新页面或完全覆盖已有页面",
+ Group: ToolGroupWikiEdit,
+ Danger: true,
+ },
+ {
+ Name: ToolWikiReplaceText,
+ Label: "局部替换Wiki",
+ Description: "替换Wiki页面中的特定文本",
+ Group: ToolGroupWikiEdit,
+ Danger: true,
},
- {Name: ToolDatabaseQuery, Label: "查询数据库", Description: "查询数据库中的信息"},
- {Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析"},
- {Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
- {Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
- {Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
- {Name: ToolWikiFlagIssue, Label: "标记Wiki问题", Description: "标记页面中存在的事实错误或合并冲突问题"},
- {Name: ToolWikiWritePage, Label: "创建/覆盖Wiki", Description: "创建新页面或完全覆盖已有页面"},
- {Name: ToolWikiReplaceText, Label: "局部替换Wiki", Description: "替换Wiki页面中的特定文本"},
- {Name: ToolWikiRenamePage, Label: "重命名Wiki", Description: "重命名Wiki页面并自动更新关联链接"},
- {Name: ToolWikiDeletePage, Label: "删除Wiki", Description: "删除Wiki页面并自动清理关联死链"},
- {Name: ToolWikiReadIssue, Label: "查看Wiki问题", Description: "查看特定的Wiki页面问题详情"},
- {Name: ToolWikiUpdateIssue, Label: "更新Wiki问题状态", Description: "更新特定的Wiki页面问题状态"},
+ {
+ Name: ToolWikiRenamePage,
+ Label: "重命名Wiki",
+ Description: "重命名Wiki页面并自动更新关联链接",
+ Group: ToolGroupWikiEdit,
+ Danger: true,
+ },
+ {
+ Name: ToolWikiDeletePage,
+ Label: "删除Wiki",
+ Description: "删除Wiki页面并自动清理关联死链",
+ Group: ToolGroupWikiEdit,
+ Danger: true,
+ },
+ {Name: ToolWikiReadIssue, Label: "查看Wiki问题", Description: "查看特定的Wiki页面问题详情", Group: ToolGroupWikiIssue},
+ {Name: ToolWikiUpdateIssue, Label: "更新Wiki问题状态", Description: "更新特定的Wiki页面问题状态", Group: ToolGroupWikiIssue},
+ {Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析", Group: ToolGroupData},
+ {Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息", Group: ToolGroupData},
+ }
+}
+
+// SwitchManagedTools returns the tools an allowed_tools entry does not
+// register: other agent settings register or withhold them, such as the web search,
+// memory, skills, sandbox and MCP settings, or the built-in skill installer.
+// registerTools either strips them from the list and re-adds them from their
+// switch, or skips them and leaves them to the code that owns them. The agent
+// editor uses this list to explain such stored entries instead of offering
+// them as checkboxes.
+func SwitchManagedTools() []string {
+ return []string{
+ ToolWebSearch,
+ ToolWebFetch,
+ ToolSearchMemory,
+ ToolShellExec,
+ ToolReadFile,
+ ToolListSandboxFiles,
+ ToolWriteSandboxFile,
+ ToolEditSandboxFile,
+ ToolWriteSkillFile,
+ ToolEditSkillFile,
+ ToolDiscoverMCPTools,
+ ToolCallMCPTool,
}
}
diff --git a/internal/application/service/agent_allowed_tools_test.go b/internal/application/service/agent_allowed_tools_test.go
new file mode 100644
index 000000000..f55e96716
--- /dev/null
+++ b/internal/application/service/agent_allowed_tools_test.go
@@ -0,0 +1,64 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/config"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+// An agent's allowed_tools is read in three places: the session config, tool
+// registration and the rerank requirement. These tests pin all three to the
+// same meaning: an unset list selects the default tools and an empty list
+// means no built-in tools.
+
+func TestBuildAgentConfigSeparatesUnsetFromEmptyToolList(t *testing.T) {
+ svc := &sessionService{cfg: &config.Config{}, webSearchProviderRepo: &sharedAgentWebSearchRepo{}}
+ build := func(allowed []string) []string {
+ req := &types.QARequest{
+ Session: &types.Session{ID: "session", TenantID: 1},
+ CustomAgent: &types.CustomAgent{TenantID: 1, Config: types.CustomAgentConfig{
+ AgentMode: types.AgentModeSmartReasoning, AllowedTools: allowed,
+ }},
+ }
+ cfg, err := svc.buildAgentConfig(t.Context(), req, &types.Tenant{ID: 1}, 1)
+ require.NoError(t, err)
+ return cfg.AllowedTools
+ }
+
+ require.Equal(t, tools.DefaultAllowedTools(), build(nil))
+ empty := build([]string{})
+ require.NotNil(t, empty, "the empty list must reach tool registration as empty, not unset")
+ require.Empty(t, empty)
+ require.Equal(t, []string{tools.ToolSearchKnowledge}, build([]string{tools.LegacyToolKnowledgeSearch}))
+}
+
+func TestRegisterToolsSeparatesUnsetFromEmptyToolList(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ offered := func(allowed []string) []string {
+ chatModel := &fakeAgentChatModel{}
+ engine, err := (&agentService{}).CreateAgentEngine(
+ ctx, &types.AgentConfig{AllowedTools: allowed}, chatModel, nil, nil, "sess-1", "msg-1")
+ require.NoError(t, err)
+ _, err = engine.Execute(ctx, "sess-1", "msg-1", "hello", nil)
+ require.NoError(t, err)
+ return chatModel.lastToolNames
+ }
+
+ // Without a knowledge base the retrieval defaults are dropped, which
+ // leaves search_conversations as the visible part of the defaults.
+ require.Contains(t, offered(nil), tools.ToolSearchConversations)
+ require.NotContains(t, offered([]string{}), tools.ToolSearchConversations)
+ require.Empty(t, offered([]string{}), "an empty list registers no built-in tool")
+}
+
+func TestRerankRequirementSeparatesUnsetFromEmptyToolList(t *testing.T) {
+ agent := func(allowed []string) *types.CustomAgent {
+ return &types.CustomAgent{Config: types.CustomAgentConfig{KBSelectionMode: "all", AllowedTools: allowed}}
+ }
+ require.True(t, agentRequiresRerankModel(agent(nil)), "the default tools include search_knowledge")
+ require.False(t, agentRequiresRerankModel(agent([]string{})), "no tool calls the reranker")
+}
diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go
index a38f7d863..b540a35d2 100644
--- a/internal/application/service/agent_service.go
+++ b/internal/application/service/agent_service.go
@@ -1017,17 +1017,11 @@ func (s *agentService) registerTools(
// - We still *filter out* tools whose capability prerequisites are missing
// (no KB in scope, no Wiki-capable KB, etc.) so the LLM can't call tools
// that would error at runtime.
- // - Legacy agents without AllowedTools fall back to DefaultAllowedTools().
- var allowedTools []string
- if len(config.AllowedTools) > 0 {
- // Retired retrieval tool names in stored configs map onto their
- // successors here, so no data migration is needed.
- allowedTools = tools.NormalizeAllowedTools(config.AllowedTools)
- logger.Infof(ctx, "Using custom allowed tools from config: %v", allowedTools)
- } else {
- allowedTools = tools.DefaultAllowedTools()
- logger.Infof(ctx, "Using default allowed tools: %v", allowedTools)
- }
+ // - Agents whose AllowedTools was never set fall back to
+ // DefaultAllowedTools(); an empty list means no built-in tools.
+ // tools.EffectiveAllowedTools also rewrites retired names.
+ allowedTools := tools.EffectiveAllowedTools(config.AllowedTools)
+ logger.Infof(ctx, "Using allowed tools: %v (set in config: %v)", allowedTools, config.AllowedTools != nil)
if config.SharedAgentReadOnly {
allowedTools = withoutWikiWriteTools(allowedTools)
}
diff --git a/internal/application/service/agent_service_test.go b/internal/application/service/agent_service_test.go
index 97b878d8e..55afc4aaa 100644
--- a/internal/application/service/agent_service_test.go
+++ b/internal/application/service/agent_service_test.go
@@ -781,3 +781,29 @@ func TestValidInstallDirUsesTheHostVersionsRoot(t *testing.T) {
_, ok = noRoot.validInstallDir(host)
require.False(t, ok)
}
+
+// TestSwitchManagedToolsIgnoreTheAllowlist pins tools.SwitchManagedTools to
+// what registerTools does: with every switch off, naming those tools in the
+// allowlist must not offer any of them. The agent editor relies on this list
+// to tell users that such stored entries have no effect. It covers the
+// allowlist path only: registering a listed tool from the allowlist, or no
+// longer stripping a web or memory tool, fails it. The code that registers
+// sandbox, skill and MCP tools from their own settings is tested elsewhere.
+func TestSwitchManagedToolsIgnoreTheAllowlist(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ allowed := []string{tools.ToolThinking}
+ allowed = append(allowed, tools.SwitchManagedTools()...)
+ chatModel := &fakeAgentChatModel{}
+ config := &types.AgentConfig{AllowedTools: allowed}
+
+ engine, err := (&agentService{}).CreateAgentEngine(ctx, config, chatModel, nil, nil, "sess-1", "msg-1")
+ require.NoError(t, err)
+ _, err = engine.Execute(ctx, "sess-1", "msg-1", "hello", nil)
+ require.NoError(t, err)
+
+ require.True(t, toolOffered(chatModel.lastToolNames, tools.ToolThinking), "the run must have offered tools at all")
+ for _, managed := range tools.SwitchManagedTools() {
+ require.False(t, toolOffered(chatModel.lastToolNames, managed),
+ "%s follows another agent setting, not the allowlist", managed)
+ }
+}
diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go
index bc9c7b86e..a7fd83039 100644
--- a/internal/application/service/agent_share.go
+++ b/internal/application/service/agent_share.go
@@ -41,9 +41,9 @@ var (
// therefore don't need a rerank model configured, even when knowledge bases
// are attached.
//
-// When AllowedTools is empty the runtime falls back to
-// tools.DefaultAllowedTools(), which includes search_knowledge, so we treat
-// that case as requiring the reranker.
+// When AllowedTools was never set the runtime uses
+// tools.DefaultAllowedTools(), which includes search_knowledge, so that case
+// requires the reranker; an empty list registers no tool and does not.
func agentRequiresRerankModel(agent *types.CustomAgent) bool {
if agent == nil {
return false
@@ -51,11 +51,7 @@ func agentRequiresRerankModel(agent *types.CustomAgent) bool {
if agent.Config.KBSelectionMode == "none" {
return false
}
- allowed := agent.Config.AllowedTools
- if len(allowed) == 0 {
- allowed = tools.DefaultAllowedTools()
- }
- for _, t := range allowed {
+ for _, t := range tools.EffectiveAllowedTools(agent.Config.AllowedTools) {
if tools.SuccessorToolName(t) == tools.ToolSearchKnowledge {
return true
}
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index 7fbb91235..689b78335 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -402,12 +402,8 @@ func (s *sessionService) buildAgentConfig(
agentConfig.KnowledgeBases = kbIDs
agentConfig.KnowledgeIDs = knowledgeIDs
- // Use custom agent's allowed tools if specified, otherwise use defaults
- if len(customAgent.Config.AllowedTools) > 0 {
- agentConfig.AllowedTools = customAgent.Config.AllowedTools
- } else {
- agentConfig.AllowedTools = tools.DefaultAllowedTools()
- }
+ // An unset list selects the default tools; an empty one means none.
+ agentConfig.AllowedTools = tools.EffectiveAllowedTools(customAgent.Config.AllowedTools)
// Apply per-turn @Skill / @MCP scope. Each helper narrows the agent's
// whitelist to the mentioned items and records the pinned set used for the
// <must_use> hint, keeping all scope logic in one place per resource type.
diff --git a/internal/database/migration_postgres_agent_allowed_tools_test.go b/internal/database/migration_postgres_agent_allowed_tools_test.go
new file mode 100644
index 000000000..4b50ae385
--- /dev/null
+++ b/internal/database/migration_postgres_agent_allowed_tools_test.go
@@ -0,0 +1,75 @@
+package database
+
+import (
+ "database/sql"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/golang-migrate/migrate/v4"
+ "github.com/stretchr/testify/require"
+)
+
+// TestPostgresMigrationsKeepAgentToolsWhenAnEmptyListMeansNone runs the
+// versioned migrations against a real PostgreSQL; see
+// TestPostgresMigrationsServeAgentHistory for how to start one. It stops
+// before 000116, stores every kind of allowed_tools value, and checks that
+// the upgrade keeps each agent's effective tools.
+func TestPostgresMigrationsKeepAgentToolsWhenAnEmptyListMeansNone(t *testing.T) {
+ dsn := os.Getenv("WEKNORA_MIGRATION_TEST_POSTGRES_DSN")
+ if dsn == "" {
+ t.Skip("set WEKNORA_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
+ }
+ root := sqliteRepoRoot(t)
+ chdirAndRestore(t, root)
+ m, err := migrate.New("file://migrations/versioned", dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _, _ = m.Close() })
+ require.NoError(t, ignoreNoChange(m.Migrate(versionedMigrationBefore(t, root, 116))))
+
+ db, err := sql.Open("postgres", dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = db.Close() })
+ const tenantID = 990116
+ cleanup := func() { _, _ = db.Exec(`DELETE FROM custom_agents WHERE tenant_id = $1`, tenantID) }
+ cleanup()
+ t.Cleanup(cleanup)
+ for id, config := range agentToolListRows {
+ _, err := db.Exec(`INSERT INTO custom_agents (id, name, tenant_id, config) VALUES ($1, $1, $2, $3::jsonb)`,
+ id, tenantID, config)
+ require.NoError(t, err)
+ }
+
+ require.NoError(t, RunMigrationsWithOptions(dsn, MigrationOptions{}))
+ requireAgentToolListsUpgraded(t, db,
+ `SELECT config::text FROM custom_agents WHERE tenant_id = 990116 AND id = $1`)
+}
+
+// versionedMigrationBefore returns the highest versioned migration below
+// version, so the test does not depend on how many migrations precede it.
+func versionedMigrationBefore(t *testing.T, root string, version int) uint {
+ t.Helper()
+ entries, err := os.ReadDir(filepath.Join(root, "migrations", "versioned"))
+ require.NoError(t, err)
+ before := 0
+ for _, e := range entries {
+ prefix, _, ok := strings.Cut(e.Name(), "_")
+ if !ok {
+ continue
+ }
+ if n, err := strconv.Atoi(prefix); err == nil && n < version && n > before {
+ before = n
+ }
+ }
+ require.NotZero(t, before)
+ return uint(before)
+}
+
+func ignoreNoChange(err error) error {
+ if err == migrate.ErrNoChange {
+ return nil
+ }
+ return err
+}
diff --git a/internal/database/migration_sqlite_agent_allowed_tools_test.go b/internal/database/migration_sqlite_agent_allowed_tools_test.go
new file mode 100644
index 000000000..a32c99954
--- /dev/null
+++ b/internal/database/migration_sqlite_agent_allowed_tools_test.go
@@ -0,0 +1,94 @@
+package database
+
+import (
+ "database/sql"
+ "encoding/json"
+ "path/filepath"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/stretchr/testify/require"
+)
+
+// agentToolListRows is the custom_agents data both upgrade tests start from:
+// every way an allowed_tools value can be stored, in both agent modes.
+var agentToolListRows = map[string]string{
+ "reasoning-empty": `{"agent_mode":"smart-reasoning","allowed_tools":[]}`,
+ "reasoning-null": `{"agent_mode":"smart-reasoning","allowed_tools":null}`,
+ "reasoning-missing": `{"agent_mode":"smart-reasoning"}`,
+ "reasoning-picked": `{"agent_mode":"smart-reasoning","allowed_tools":["thinking"]}`,
+ "quick-empty": `{"agent_mode":"quick-answer","allowed_tools":[]}`,
+ // Malformed values must neither break the migration nor be rewritten.
+ "reasoning-string": `{"agent_mode":"smart-reasoning","allowed_tools":"thinking"}`,
+ "reasoning-object": `{"agent_mode":"smart-reasoning","allowed_tools":{}}`,
+}
+
+// requireAgentToolListsUpgraded checks that an upgrade keeps every agent's
+// effective tools: the empty smart-reasoning list, which used to select the
+// default tools, now names them, and nothing else changes.
+func requireAgentToolListsUpgraded(t *testing.T, db *sql.DB, query string) {
+ t.Helper()
+ for _, id := range []string{"reasoning-string", "reasoning-object"} {
+ var raw string
+ require.NoError(t, db.QueryRow(query, id).Scan(&raw), id)
+ var got, want struct {
+ AllowedTools json.RawMessage `json:"allowed_tools"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(raw), &got), id)
+ require.NoError(t, json.Unmarshal([]byte(agentToolListRows[id]), &want), id)
+ require.JSONEq(t, string(want.AllowedTools), string(got.AllowedTools), "%s must be left as it is", id)
+ }
+ want := map[string][]string{
+ "reasoning-empty": tools.DefaultAllowedTools(),
+ "reasoning-null": nil,
+ "reasoning-missing": nil,
+ "reasoning-picked": {"thinking"},
+ "quick-empty": {},
+ }
+ for id, expected := range want {
+ var raw string
+ require.NoError(t, db.QueryRow(query, id).Scan(&raw), id)
+ var config struct {
+ AllowedTools []string `json:"allowed_tools"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(raw), &config), id)
+ require.Equal(t, expected, config.AllowedTools, id)
+ // The default tools still apply to the agents that never set a list.
+ before := tools.EffectiveAllowedTools(decodeAllowedTools(t, agentToolListRows[id]))
+ require.ElementsMatch(t, before, tools.EffectiveAllowedTools(config.AllowedTools),
+ "%s must keep its effective tools", id)
+ }
+}
+
+// decodeAllowedTools reads a pre-upgrade row under the old meaning, in which
+// an empty list also selected the default tools.
+func decodeAllowedTools(t *testing.T, raw string) []string {
+ t.Helper()
+ var config struct {
+ AgentMode string `json:"agent_mode"`
+ AllowedTools []string `json:"allowed_tools"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(raw), &config))
+ if config.AgentMode == "smart-reasoning" && config.AllowedTools != nil && len(config.AllowedTools) == 0 {
+ return nil
+ }
+ return config.AllowedTools
+}
+
+func TestSQLiteMigrationsKeepAgentToolsWhenAnEmptyListMeansNone(t *testing.T) {
+ repoRoot := sqliteRepoRoot(t)
+ chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 34))
+ dbPath := filepath.Join(t.TempDir(), "upgrade-agent-tools.db")
+ opts := MigrationOptions{SQLiteDBPath: dbPath}
+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
+ db := openSQLiteDB(t, dbPath)
+ for id, config := range agentToolListRows {
+ _, err := db.Exec(`INSERT INTO custom_agents (id, name, tenant_id, config) VALUES (?, ?, 1, ?)`,
+ id, id, config)
+ require.NoError(t, err)
+ }
+
+ chdirAndRestore(t, repoRoot)
+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
+ requireAgentToolListsUpgraded(t, db, `SELECT config FROM custom_agents WHERE id = ?`)
+}
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index 2fccaf0ec..2cfe0d916 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -71,7 +71,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
-const expectedSQLiteMigrationVersion = 34
+const expectedSQLiteMigrationVersion = 35
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go
index ee4ba38b8..04b8d28e6 100644
--- a/internal/handler/custom_agent.go
+++ b/internal/handler/custom_agent.go
@@ -8,6 +8,7 @@ import (
"strconv"
"strings"
+ "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/im"
@@ -115,6 +116,11 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
_ = c.Error(err)
return
}
+ toolWarnings, err := checkAgentAllowedTools(nil, &req.Config)
+ if err != nil {
+ _ = c.Error(err)
+ return
+ }
// Build agent object
agent := &types.CustomAgent{
@@ -157,10 +163,14 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s",
secutils.SanitizeForLog(createdAgent.ID), secutils.SanitizeForLog(createdAgent.Name))
- c.JSON(http.StatusCreated, gin.H{
+ resp := gin.H{
"success": true,
"data": createdAgent,
- })
+ }
+ if toolWarnings != nil {
+ resp["allowed_tools_warnings"] = toolWarnings
+ }
+ c.JSON(http.StatusCreated, resp)
}
// GetAgent godoc
@@ -385,6 +395,22 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
_ = c.Error(err)
return
}
+ // Names already stored are kept, so the stored list is needed first.
+ existing, err := h.service.GetAgentByID(ctx, id)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"agent_id": id})
+ if err == service.ErrAgentNotFound {
+ _ = c.Error(errors.NewNotFoundError("Agent not found"))
+ return
+ }
+ _ = c.Error(errors.NewInternalServerError("Failed to update agent"))
+ return
+ }
+ toolWarnings, err := checkAgentAllowedTools(existing.Config.AllowedTools, &req.Config)
+ if err != nil {
+ _ = c.Error(err)
+ return
+ }
// Only a sent avatar is validated: nil means the caller never touched the
// field, so there is no value to bound. Checking the length here is what
@@ -441,10 +467,14 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
}
logger.Infof(ctx, "Custom agent updated successfully, ID: %s", secutils.SanitizeForLog(id))
- c.JSON(http.StatusOK, gin.H{
+ resp := gin.H{
"success": true,
"data": updatedAgent,
- })
+ }
+ if toolWarnings != nil {
+ resp["allowed_tools_warnings"] = toolWarnings
+ }
+ c.JSON(http.StatusOK, resp)
}
// DeleteAgent godoc
@@ -639,6 +669,23 @@ func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) {
})
}
+// GetAgentTools godoc
+// @Summary 获取智能体可选工具
+// @Description 返回编辑器可勾选的内置工具(含分组和知识库能力要求)、工具列表未设置时生效的默认工具,以及由开关控制、写入工具列表也不生效的工具
+// @Tags 智能体
+// @Accept json
+// @Produce json
+// @Success 200 {object} map[string]interface{} "工具目录"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /agents/tools [get]
+func (h *CustomAgentHandler) GetAgentTools(c *gin.Context) {
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": tools.BuildAgentToolCatalog(),
+ })
+}
+
// GetSuggestedQuestions godoc
// @Summary 获取推荐问题
// @Description 基于智能体关联的知识库,返回推荐问题供用户快捷提问
diff --git a/internal/handler/custom_agent_test.go b/internal/handler/custom_agent_test.go
index 4d8e2d179..8349b4710 100644
--- a/internal/handler/custom_agent_test.go
+++ b/internal/handler/custom_agent_test.go
@@ -2,10 +2,15 @@ package handler
import (
"context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
"testing"
+ "github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
+ "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -16,3 +21,49 @@ func TestValidateAgentSandboxConfigRejectsAnyConfigOnLite(t *testing.T) {
require.Error(t, err)
require.NoError(t, h.validateAgentSandboxConfig(ctx, types.CustomAgentConfig{}))
}
+
+func TestGetAgentToolsServesTheToolCatalog(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/agents/tools", nil)
+
+ (&CustomAgentHandler{}).GetAgentTools(c)
+
+ require.Equal(t, http.StatusOK, recorder.Code)
+ var body struct {
+ Success bool `json:"success"`
+ Data struct {
+ Tools []struct {
+ Name string `json:"name"`
+ Group string `json:"group"`
+ Danger bool `json:"danger"`
+ Requirement struct {
+ AnyOf []string `json:"any_of"`
+ AllOf []string `json:"all_of"`
+ } `json:"requirement"`
+ } `json:"tools"`
+ DefaultTools []string `json:"default_tools"`
+ SwitchManagedTools []string `json:"switch_managed_tools"`
+ } `json:"data"`
+ }
+ require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &body))
+ require.True(t, body.Success)
+
+ byName := make(map[string]int, len(body.Data.Tools))
+ for i, tool := range body.Data.Tools {
+ byName[tool.Name] = i
+ }
+ for _, name := range []string{
+ tools.ToolSearchConversations, tools.ToolSearchKnowledge, tools.ToolWikiDeletePage, tools.ToolWikiSearch,
+ } {
+ require.Contains(t, byName, name)
+ }
+ search := body.Data.Tools[byName[tools.ToolSearchKnowledge]]
+ require.Equal(t, tools.ToolGroupRAG, search.Group)
+ require.ElementsMatch(t, []string{"vector", "keyword"}, search.Requirement.AnyOf)
+ require.True(t, body.Data.Tools[byName[tools.ToolWikiDeletePage]].Danger)
+ require.Equal(t, []string{"wiki"}, body.Data.Tools[byName[tools.ToolWikiSearch]].Requirement.AllOf)
+ require.Equal(t, tools.DefaultAllowedTools(), body.Data.DefaultTools)
+ require.Equal(t, tools.SwitchManagedTools(), body.Data.SwitchManagedTools)
+}
diff --git a/internal/handler/custom_agent_tools.go b/internal/handler/custom_agent_tools.go
new file mode 100644
index 000000000..7dc4592ba
--- /dev/null
+++ b/internal/handler/custom_agent_tools.go
@@ -0,0 +1,39 @@
+package handler
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// allowedToolsWarnings tells the caller what saving did to an allowed_tools
+// list without rejecting it.
+type allowedToolsWarnings struct {
+ // KeptUnknown are stored names no built-in tool answers to. They stay so
+ // the agent can still be saved, but the agent cannot call them.
+ KeptUnknown []string `json:"kept_unknown,omitempty"`
+ // Dropped are tools other agent settings decide on; listing them had no
+ // effect, so they are not stored.
+ Dropped []string `json:"dropped,omitempty"`
+}
+
+// checkAgentAllowedTools validates config.AllowedTools before an agent is
+// saved and rewrites it to the list that will be stored. stored is the
+// agent's current list, nil for a new agent. Names a request adds that no
+// built-in tool answers to are rejected, so a typo cannot silently leave an
+// agent without the tool it was meant to get.
+func checkAgentAllowedTools(stored []string, config *types.CustomAgentConfig) (*allowedToolsWarnings, error) {
+ check := tools.CheckAllowedTools(stored, config.AllowedTools)
+ if len(check.Rejected) > 0 {
+ return nil, errors.NewBadRequestError(fmt.Sprintf(
+ "allowed_tools contains unknown tools: %s", strings.Join(check.Rejected, ", ")))
+ }
+ config.AllowedTools = check.Tools
+ if len(check.KeptUnknown) == 0 && len(check.Dropped) == 0 {
+ return nil, nil
+ }
+ return &allowedToolsWarnings{KeptUnknown: check.KeptUnknown, Dropped: check.Dropped}, nil
+}
diff --git a/internal/handler/custom_agent_tools_test.go b/internal/handler/custom_agent_tools_test.go
new file mode 100644
index 000000000..11eeb28eb
--- /dev/null
+++ b/internal/handler/custom_agent_tools_test.go
@@ -0,0 +1,127 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// savingAgentService stores what the handler hands it, so a test can read
+// the allowed_tools list that would reach the database.
+type savingAgentService struct {
+ interfaces.CustomAgentService
+ stored *types.CustomAgent
+ lookupErr error
+ saved *types.CustomAgent
+}
+
+func (s *savingAgentService) GetAgentByID(context.Context, string) (*types.CustomAgent, error) {
+ return s.stored, s.lookupErr
+}
+
+func (s *savingAgentService) CreateAgent(_ context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
+ s.saved = agent
+ return agent, nil
+}
+
+func (s *savingAgentService) UpdateAgent(
+ _ context.Context, agent *types.CustomAgent, _ *string,
+) (*types.CustomAgent, error) {
+ s.saved = agent
+ return agent, nil
+}
+
+func sendAgent(t *testing.T, svc *savingAgentService, method, allowedTools string) *httptest.ResponseRecorder {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.Use(middleware.ErrorHandler())
+ h := &CustomAgentHandler{service: svc}
+ r.POST("/agents", h.CreateAgent)
+ r.PUT("/agents/:id", h.UpdateAgent)
+ path := "/agents"
+ if method == http.MethodPut {
+ path = "/agents/agent-1"
+ }
+ body := `{"name":"agent","config":{"agent_mode":"smart-reasoning","allowed_tools":` + allowedTools + `}}`
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ r.ServeHTTP(rec, req)
+ return rec
+}
+
+func TestSavingAnAgentChecksItsToolList(t *testing.T) {
+ t.Run("create rejects names no tool answers to", func(t *testing.T) {
+ svc := &savingAgentService{}
+ rec := sendAgent(t, svc, http.MethodPost, `["thinking","serch_knowledge"]`)
+ require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
+ require.Contains(t, rec.Body.String(), "serch_knowledge")
+ require.Nil(t, svc.saved)
+ })
+
+ t.Run("create rewrites retired names and drops switch-managed tools", func(t *testing.T) {
+ svc := &savingAgentService{}
+ rec := sendAgent(t, svc, http.MethodPost, `["knowledge_search","web_search"]`)
+ require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String())
+ require.Equal(t, []string{tools.ToolSearchKnowledge}, svc.saved.Config.AllowedTools)
+ var body struct {
+ Warnings allowedToolsWarnings `json:"allowed_tools_warnings"`
+ }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
+ require.Equal(t, []string{tools.ToolWebSearch}, body.Warnings.Dropped)
+ })
+
+ t.Run("create keeps an empty list empty and an unset list unset", func(t *testing.T) {
+ svc := &savingAgentService{}
+ require.Equal(t, http.StatusCreated, sendAgent(t, svc, http.MethodPost, `[]`).Code)
+ require.NotNil(t, svc.saved.Config.AllowedTools)
+ require.Empty(t, svc.saved.Config.AllowedTools)
+
+ svc = &savingAgentService{}
+ require.Equal(t, http.StatusCreated, sendAgent(t, svc, http.MethodPost, `null`).Code)
+ require.Nil(t, svc.saved.Config.AllowedTools)
+ })
+
+ t.Run("update keeps unknown names that were already stored", func(t *testing.T) {
+ svc := &savingAgentService{stored: &types.CustomAgent{
+ ID: "agent-1", Config: types.CustomAgentConfig{AllowedTools: []string{"thinking", "none"}},
+ }}
+ rec := sendAgent(t, svc, http.MethodPut, `["thinking","none"]`)
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.Equal(t, []string{"thinking", "none"}, svc.saved.Config.AllowedTools)
+ var body struct {
+ Warnings allowedToolsWarnings `json:"allowed_tools_warnings"`
+ }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
+ require.Equal(t, []string{"none"}, body.Warnings.KeptUnknown)
+ })
+
+ t.Run("update rejects unknown names it adds", func(t *testing.T) {
+ svc := &savingAgentService{stored: &types.CustomAgent{
+ ID: "agent-1", Config: types.CustomAgentConfig{AllowedTools: []string{"none"}},
+ }}
+ rec := sendAgent(t, svc, http.MethodPut, `["none","nothing"]`)
+ require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
+ require.Contains(t, rec.Body.String(), "nothing")
+ require.Nil(t, svc.saved)
+ })
+
+ t.Run("update of a missing agent answers 404 before checking tools", func(t *testing.T) {
+ svc := &savingAgentService{lookupErr: service.ErrAgentNotFound}
+ rec := sendAgent(t, svc, http.MethodPut, `["nothing"]`)
+ require.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String())
+ require.Nil(t, svc.saved)
+ })
+}
diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go
index 73dd49b0d..893229a8f 100644
--- a/internal/router/router_api_key_capabilities_test.go
+++ b/internal/router/router_api_key_capabilities_test.go
@@ -158,6 +158,7 @@ func TestAgentReadRoutesDeclareReadAgentsCapability(t *testing.T) {
}{
{http.MethodGet, "/api/v1/agents/placeholders"},
{http.MethodGet, "/api/v1/agents/type-presets"},
+ {http.MethodGet, "/api/v1/agents/tools"},
{http.MethodGet, "/api/v1/agents"},
{http.MethodGet, "/api/v1/agents/:id"},
{http.MethodGet, "/api/v1/agents/:id/suggested-questions"},
diff --git a/internal/router/routes_agent.go b/internal/router/routes_agent.go
index 883213462..c495a47bd 100644
--- a/internal/router/routes_agent.go
+++ b/internal/router/routes_agent.go
@@ -34,6 +34,8 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
agentsRead.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
// List smart-reasoning agent type presets (rag-qa / wiki-qa / hybrid / custom) — Viewer+
agentsRead.GET("/type-presets", g.Viewer(), agentHandler.GetAgentTypePresets)
+ // List the built-in tools an agent may select — Viewer+
+ agentsRead.GET("/tools", g.Viewer(), agentHandler.GetAgentTools)
// Create custom agent — Contributor+
agentsWrite.POST("", g.Contributor(), agentHandler.CreateAgent)
// List all agents (including built-in) — Viewer+
diff --git a/internal/types/custom_agent_allowed_tools_test.go b/internal/types/custom_agent_allowed_tools_test.go
new file mode 100644
index 000000000..038c60698
--- /dev/null
+++ b/internal/types/custom_agent_allowed_tools_test.go
@@ -0,0 +1,21 @@
+package types
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// An unset allowed_tools selects the default tools and an empty one means no
+// built-in tools, so the difference must survive a round trip through the
+// database column.
+func TestCustomAgentConfigKeepsUnsetAndEmptyToolListsApart(t *testing.T) {
+ for _, allowed := range [][]string{nil, {}, {"thinking"}} {
+ value, err := CustomAgentConfig{AllowedTools: allowed}.Value()
+ require.NoError(t, err)
+ var loaded CustomAgentConfig
+ require.NoError(t, loaded.Scan(value))
+ require.Equal(t, allowed == nil, loaded.AllowedTools == nil, "%v", allowed)
+ require.Equal(t, len(allowed), len(loaded.AllowedTools), "%v", allowed)
+ }
+}
diff --git a/migrations/sqlite/000035_agent_allowed_tools_explicit_defaults.down.sql b/migrations/sqlite/000035_agent_allowed_tools_explicit_defaults.down.sql
new file mode 100644
index 000000000..554d1e7d5
--- /dev/null
+++ b/migrations/sqlite/000035_agent_allowed_tools_explicit_defaults.down.sql
@@ -0,0 +1,2 @@
+-- Nothing to revert; see the up migration.
+SELECT 1;
diff --git a/migrations/sqlite/000035_agent_allowed_tools_explicit_defaults.up.sql b/migrations/sqlite/000035_agent_allowed_tools_explicit_defaults.up.sql
new file mode 100644
index 000000000..f1cc3a437
--- /dev/null
+++ b/migrations/sqlite/000035_agent_allowed_tools_explicit_defaults.up.sql
@@ -0,0 +1,13 @@
+-- Mirrors postgres migration 000116: an empty allowed_tools list now means
+-- no built-in tools, so smart-reasoning agents that stored one get the
+-- default tools (DefaultAllowedTools() as of this migration) written in.
+-- See the postgres migration for how this narrows an "all" knowledge base
+-- scope to the bases search_knowledge can use.
+UPDATE custom_agents
+SET config = json_set(
+ config,
+ '$.allowed_tools',
+ json('["search_knowledge", "read_document", "list_documents", "search_conversations"]'))
+WHERE json_extract(config, '$.agent_mode') = 'smart-reasoning'
+ AND json_type(config, '$.allowed_tools') = 'array'
+ AND json_array_length(config, '$.allowed_tools') = 0;
diff --git a/migrations/versioned/000116_agent_allowed_tools_explicit_defaults.down.sql b/migrations/versioned/000116_agent_allowed_tools_explicit_defaults.down.sql
new file mode 100644
index 000000000..1624b5211
--- /dev/null
+++ b/migrations/versioned/000116_agent_allowed_tools_explicit_defaults.down.sql
@@ -0,0 +1,4 @@
+-- The rewritten rows cannot be told apart from lists users saved with the
+-- same tools, so nothing is reverted. The explicit list behaves the same
+-- under both meanings of an empty list.
+DO $$ BEGIN RAISE NOTICE '[Migration 000116 down] Nothing to revert'; END $$;
diff --git a/migrations/versioned/000116_agent_allowed_tools_explicit_defaults.up.sql b/migrations/versioned/000116_agent_allowed_tools_explicit_defaults.up.sql
new file mode 100644
index 000000000..86d6ba244
--- /dev/null
+++ b/migrations/versioned/000116_agent_allowed_tools_explicit_defaults.up.sql
@@ -0,0 +1,22 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000116] Writing default tools into empty agent tool lists...'; END $$;
+
+-- An empty allowed_tools list used to select the default tools at runtime.
+-- It now means no built-in tools, and only an unset list selects the
+-- defaults. Smart-reasoning agents that stored an empty list relied on the
+-- old meaning, so write the defaults into them explicitly and they keep the
+-- tools they ran with. The list is DefaultAllowedTools() as of this
+-- migration. Other modes register no tools and are left as they are.
+--
+-- The knowledge base filter of an agent whose scope is "all" follows the
+-- stored list, so a rewritten agent now gets the same scope as one that
+-- ticked the default tools explicitly: knowledge bases search_knowledge
+-- cannot use (wiki-only ones) leave the scope.
+UPDATE custom_agents
+SET config = jsonb_set(
+ config,
+ '{allowed_tools}',
+ '["search_knowledge", "read_document", "list_documents", "search_conversations"]'::jsonb)
+WHERE config->>'agent_mode' = 'smart-reasoning'
+ AND config->'allowed_tools' = '[]'::jsonb;
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000116] Empty agent tool lists rewritten'; END $$;