Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(agent): let the assistant delete and move documents in batches (#4319)
lyingbugaaa1accebdf6
diff --git a/config/prompt_templates/agent_system_prompt.yaml b/config/prompt_templates/agent_system_prompt.yamlindex c51e437cd..0a6085232 100644--- a/config/prompt_templates/agent_system_prompt.yaml+++ b/config/prompt_templates/agent_system_prompt.yaml@@ -155,7 +155,7 @@ templates:2. Look before you change. Diagnose with read operations first — for a failed document, knowledge.get then knowledge.get_parse_progress — and tell the user what you found before proposing a fix.3. Change only what was asked. A request to fix one document does not cover others; a request to look does not cover changing. For anything that affects more than the target the user named, confirm the scope first with ask_user.4. Every write or destructive operation shows the user a confirmation card. Run one at a time so each card is clear. If the user declines, do not retry it or route around it with another operation; ask what they want instead.- 5. Asynchronous work (reparse, URL import, delete) is accepted, not finished. Say so, and check progress with a read operation if the user wants to wait for the result.+ 5. Asynchronous work (reparse, URL import, move, delete) is accepted, not finished. Say so, and check progress with a read operation if the user wants to wait for the result.Questions about WeKnora itself:- For how a feature works, how to configure or deploy it, environment variables, the API or what changed in a release, search the documentation with search_weknora_docs and read the relevant section with read_weknora_doc before answering. It is the documentation of the version the user is running.- The documentation explains how WeKnora works; operations show how this workspace actually is. When the two seem to disagree, trust the operation result and say so.diff --git a/docs/docs.go b/docs/docs.goindex d5b83bd55..541b85836 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -6705,6 +6705,7 @@ const docTemplate = `{"parameters": [{"type": "string",+ "x-agent": "knowledge_base_id","description": "源知识库 ID","name": "id","in": "path",@@ -6757,7 +6758,12 @@ const docTemplate = `{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}- }+ },+ "x-agent": {+ "id": "knowledge_base.list_move_targets",+ "risk": "read"+ },+ "x-agent-hint": "Knowledge bases the documents of this one can be moved to: same type and embedding model."}},"/knowledge-bases/{id}/pin": {@@ -7668,7 +7674,20 @@ const docTemplate = `{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}- }+ },+ "x-agent": {+ "id": "knowledge.batch_delete",+ "items": {+ "as": "knowledge_id",+ "label": "title",+ "param": "knowledge_ids",+ "target": "knowledge.get"+ },+ "label": "name",+ "risk": "destructive",+ "target": "knowledge_base.get"+ },+ "x-agent-hint": "Removes up to 20 documents of one knowledge base with their chunks, embeddings and graph data. Cannot be undone; the confirmation lists every document."}},"/knowledge/batch-reparse": {@@ -7975,7 +7994,19 @@ const docTemplate = `{"200": {"description": "任务信息","schema": {- "$ref": "#/definitions/internal_handler.MoveKnowledgeResponse"+ "allOf": [+ {+ "$ref": "#/definitions/internal_handler.DataResponse"+ },+ {+ "type": "object",+ "properties": {+ "data": {+ "$ref": "#/definitions/internal_handler.MoveKnowledgeResponse"+ }+ }+ }+ ]}},"400": {@@ -7984,7 +8015,20 @@ const docTemplate = `{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}- }+ },+ "x-agent": {+ "id": "knowledge.move",+ "items": {+ "as": "knowledge_id",+ "label": "title",+ "param": "knowledge_ids",+ "target": "knowledge.get"+ },+ "label": "name",+ "risk": "write",+ "target": "knowledge_base.get"+ },+ "x-agent-hint": "Moves up to 20 documents to another knowledge base of the same workspace; knowledge_base_id is the destination, from knowledge_base.list_move_targets. Runs in the background; follow with knowledge.get_move_progress."}},"/knowledge/move/progress/{task_id}": {@@ -8008,6 +8052,7 @@ const docTemplate = `{"parameters": [{"type": "string",+ "x-agent": true,"description": "移动任务 ID","name": "task_id","in": "path",@@ -8018,7 +8063,19 @@ const docTemplate = `{"200": {"description": "进度信息","schema": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeMoveProgress"+ "allOf": [+ {+ "$ref": "#/definitions/internal_handler.DataResponse"+ },+ {+ "type": "object",+ "properties": {+ "data": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeMoveProgress"+ }+ }+ }+ ]}},"404": {@@ -8027,6 +8084,10 @@ const docTemplate = `{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}+ },+ "x-agent": {+ "id": "knowledge.get_move_progress",+ "risk": "read"}}},@@ -26303,29 +26364,39 @@ const docTemplate = `{},"error": {"description": "错误信息",- "type": "string"+ "type": "string",+ "x-agent": true},"failed": {"description": "失败数",- "type": "integer"+ "type": "integer",+ "x-agent": true},"message": {"description": "状态消息",- "type": "string"+ "type": "string",+ "x-agent": true},"processed": {"description": "已处理数",- "type": "integer"+ "type": "integer",+ "x-agent": true},"progress": {"description": "0-100",- "type": "integer"+ "type": "integer",+ "x-agent": true},"source_kb_id": {"type": "string"},"status": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KBCloneTaskStatus"+ "allOf": [+ {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KBCloneTaskStatus"+ }+ ],+ "x-agent": true},"target_kb_id": {"type": "string"@@ -26335,7 +26406,8 @@ const docTemplate = `{},"total": {"description": "总知识数",- "type": "integer"+ "type": "integer",+ "x-agent": true},"updated_at": {"description": "最后更新时间",@@ -32612,13 +32684,18 @@ const docTemplate = `{],"properties": {"ids": {+ "description": "Documents to delete.","type": "array","items": {"type": "string"- }+ },+ "x-agent": "knowledge_ids",+ "x-agent-maximum": "20"},"kb_id": {- "type": "string"+ "description": "Knowledge base the documents belong to.",+ "type": "string",+ "x-agent": "knowledge_base_id"}}},@@ -34343,24 +34420,33 @@ const docTemplate = `{],"properties": {"knowledge_ids": {+ "description": "Documents to move.","type": "array","minItems": 1,"items": {"type": "string"- }+ },+ "x-agent": true,+ "x-agent-maximum": "20"},"mode": {+ "description": "reuse_vectors keeps the embeddings; reparse processes the documents again.","type": "string","enum": ["reuse_vectors","reparse"- ]+ ],+ "x-agent": true},"source_kb_id": {- "type": "string"+ "description": "Knowledge base the documents are in now.",+ "type": "string",+ "x-agent": "source_knowledge_base_id"},"target_kb_id": {- "type": "string"+ "description": "Knowledge base to move them to.",+ "type": "string",+ "x-agent": "knowledge_base_id"}}},@@ -34368,7 +34454,8 @@ const docTemplate = `{"type": "object","properties": {"knowledge_count": {- "type": "integer"+ "type": "integer",+ "x-agent": true},"message": {"type": "string"@@ -34380,7 +34467,8 @@ const docTemplate = `{"type": "string"},"task_id": {- "type": "string"+ "type": "string",+ "x-agent": true}}},@@ -35168,7 +35256,8 @@ const docTemplate = `{"type": "object","properties": {"deleted_count": {- "type": "integer"+ "type": "integer",+ "x-agent": true},"reparse_count": {"type": "integer",diff --git a/docs/swagger.json b/docs/swagger.jsonindex 5aacbea5b..b7ff0aa87 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -6698,6 +6698,7 @@"parameters": [{"type": "string",+ "x-agent": "knowledge_base_id","description": "源知识库 ID","name": "id","in": "path",@@ -6750,7 +6751,12 @@"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}- }+ },+ "x-agent": {+ "id": "knowledge_base.list_move_targets",+ "risk": "read"+ },+ "x-agent-hint": "Knowledge bases the documents of this one can be moved to: same type and embedding model."}},"/knowledge-bases/{id}/pin": {@@ -7661,7 +7667,20 @@"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}- }+ },+ "x-agent": {+ "id": "knowledge.batch_delete",+ "items": {+ "as": "knowledge_id",+ "label": "title",+ "param": "knowledge_ids",+ "target": "knowledge.get"+ },+ "label": "name",+ "risk": "destructive",+ "target": "knowledge_base.get"+ },+ "x-agent-hint": "Removes up to 20 documents of one knowledge base with their chunks, embeddings and graph data. Cannot be undone; the confirmation lists every document."}},"/knowledge/batch-reparse": {@@ -7968,7 +7987,19 @@"200": {"description": "任务信息","schema": {- "$ref": "#/definitions/internal_handler.MoveKnowledgeResponse"+ "allOf": [+ {+ "$ref": "#/definitions/internal_handler.DataResponse"+ },+ {+ "type": "object",+ "properties": {+ "data": {+ "$ref": "#/definitions/internal_handler.MoveKnowledgeResponse"+ }+ }+ }+ ]}},"400": {@@ -7977,7 +8008,20 @@"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}- }+ },+ "x-agent": {+ "id": "knowledge.move",+ "items": {+ "as": "knowledge_id",+ "label": "title",+ "param": "knowledge_ids",+ "target": "knowledge.get"+ },+ "label": "name",+ "risk": "write",+ "target": "knowledge_base.get"+ },+ "x-agent-hint": "Moves up to 20 documents to another knowledge base of the same workspace; knowledge_base_id is the destination, from knowledge_base.list_move_targets. Runs in the background; follow with knowledge.get_move_progress."}},"/knowledge/move/progress/{task_id}": {@@ -8001,6 +8045,7 @@"parameters": [{"type": "string",+ "x-agent": true,"description": "移动任务 ID","name": "task_id","in": "path",@@ -8011,7 +8056,19 @@"200": {"description": "进度信息","schema": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeMoveProgress"+ "allOf": [+ {+ "$ref": "#/definitions/internal_handler.DataResponse"+ },+ {+ "type": "object",+ "properties": {+ "data": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeMoveProgress"+ }+ }+ }+ ]}},"404": {@@ -8020,6 +8077,10 @@"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"}}+ },+ "x-agent": {+ "id": "knowledge.get_move_progress",+ "risk": "read"}}},@@ -26296,29 +26357,39 @@},"error": {"description": "错误信息",- "type": "string"+ "type": "string",+ "x-agent": true},"failed": {"description": "失败数",- "type": "integer"+ "type": "integer",+ "x-agent": true},"message": {"description": "状态消息",- "type": "string"+ "type": "string",+ "x-agent": true},"processed": {"description": "已处理数",- "type": "integer"+ "type": "integer",+ "x-agent": true},"progress": {"description": "0-100",- "type": "integer"+ "type": "integer",+ "x-agent": true},"source_kb_id": {"type": "string"},"status": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KBCloneTaskStatus"+ "allOf": [+ {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.KBCloneTaskStatus"+ }+ ],+ "x-agent": true},"target_kb_id": {"type": "string"@@ -26328,7 +26399,8 @@},"total": {"description": "总知识数",- "type": "integer"+ "type": "integer",+ "x-agent": true},"updated_at": {"description": "最后更新时间",@@ -32605,13 +32677,18 @@],"properties": {"ids": {+ "description": "Documents to delete.","type": "array","items": {"type": "string"- }+ },+ "x-agent": "knowledge_ids",+ "x-agent-maximum": "20"},"kb_id": {- "type": "string"+ "description": "Knowledge base the documents belong to.",+ "type": "string",+ "x-agent": "knowledge_base_id"}}},@@ -34336,24 +34413,33 @@],"properties": {"knowledge_ids": {+ "description": "Documents to move.","type": "array","minItems": 1,"items": {"type": "string"- }+ },+ "x-agent": true,+ "x-agent-maximum": "20"},"mode": {+ "description": "reuse_vectors keeps the embeddings; reparse processes the documents again.","type": "string","enum": ["reuse_vectors","reparse"- ]+ ],+ "x-agent": true},"source_kb_id": {- "type": "string"+ "description": "Knowledge base the documents are in now.",+ "type": "string",+ "x-agent": "source_knowledge_base_id"},"target_kb_id": {- "type": "string"+ "description": "Knowledge base to move them to.",+ "type": "string",+ "x-agent": "knowledge_base_id"}}},@@ -34361,7 +34447,8 @@"type": "object","properties": {"knowledge_count": {- "type": "integer"+ "type": "integer",+ "x-agent": true},"message": {"type": "string"@@ -34373,7 +34460,8 @@"type": "string"},"task_id": {- "type": "string"+ "type": "string",+ "x-agent": true}}},@@ -35161,7 +35249,8 @@"type": "object","properties": {"deleted_count": {- "type": "integer"+ "type": "integer",+ "x-agent": true},"reparse_count": {"type": "integer",diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex 15b67b545..23e54d53a 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -4084,22 +4084,29 @@ definitions:error:description: 错误信息type: string+ x-agent: truefailed:description: 失败数type: integer+ x-agent: truemessage:description: 状态消息type: string+ x-agent: trueprocessed:description: 已处理数type: integer+ x-agent: trueprogress:description: 0-100type: integer+ x-agent: truesource_kb_id:type: stringstatus:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KBCloneTaskStatus'+ allOf:+ - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KBCloneTaskStatus'+ x-agent: truetarget_kb_id:type: stringtask_id:@@ -4107,6 +4114,7 @@ definitions:total:description: 总知识数type: integer+ x-agent: trueupdated_at:description: 最后更新时间type: integer@@ -9054,11 +9062,16 @@ definitions:internal_handler.BatchDeleteKnowledgeRequest:properties:ids:+ description: Documents to delete.items:type: stringtype: array+ x-agent: knowledge_ids+ x-agent-maximum: "20"kb_id:+ description: Knowledge base the documents belong to.type: string+ x-agent: knowledge_base_idrequired:- ids- kb_id@@ -10271,19 +10284,29 @@ definitions:internal_handler.MoveKnowledgeRequest:properties:knowledge_ids:+ description: Documents to move.items:type: stringminItems: 1type: array+ x-agent: true+ x-agent-maximum: "20"mode:+ description: reuse_vectors keeps the embeddings; reparse processes the documents+ again.enum:- reuse_vectors- reparsetype: string+ x-agent: truesource_kb_id:+ description: Knowledge base the documents are in now.type: string+ x-agent: source_knowledge_base_idtarget_kb_id:+ description: Knowledge base to move them to.type: string+ x-agent: knowledge_base_idrequired:- knowledge_ids- mode@@ -10294,6 +10317,7 @@ definitions:properties:knowledge_count:type: integer+ x-agent: truemessage:type: stringsource_kb_id:@@ -10302,6 +10326,7 @@ definitions:type: stringtask_id:type: string+ x-agent: truetype: objectinternal_handler.MoveKnowledgeToFolderRequest:properties:@@ -10849,6 +10874,7 @@ definitions:properties:deleted_count:type: integer+ x-agent: truereparse_count:type: integerx-agent: true@@ -16041,6 +16067,7 @@ paths:name: idrequired: truetype: string+ x-agent: knowledge_base_idproduces:- application/jsonresponses:@@ -16077,6 +16104,11 @@ paths:summary: 获取可移动目标知识库列表tags:- 知识库+ x-agent:+ id: knowledge_base.list_move_targets+ risk: read+ x-agent-hint: 'Knowledge bases the documents of this one can be moved to: same+ type and embedding model.'/knowledge-bases/{id}/pin:put:consumes:@@ -17067,6 +17099,19 @@ paths:summary: 批量删除知识tags:- 知识管理+ x-agent:+ id: knowledge.batch_delete+ items:+ as: knowledge_id+ label: title+ param: knowledge_ids+ target: knowledge.get+ label: name+ risk: destructive+ target: knowledge_base.get+ x-agent-hint: Removes up to 20 documents of one knowledge base with their chunks,+ embeddings and graph data. Cannot be undone; the confirmation lists every+ document./knowledge/batch-reparse:post:consumes:@@ -17253,7 +17298,12 @@ paths:"200":description: 任务信息schema:- $ref: '#/definitions/internal_handler.MoveKnowledgeResponse'+ allOf:+ - $ref: '#/definitions/internal_handler.DataResponse'+ - properties:+ data:+ $ref: '#/definitions/internal_handler.MoveKnowledgeResponse'+ type: object"400":description: 请求参数错误schema:@@ -17264,6 +17314,19 @@ paths:summary: 移动知识到其他知识库tags:- 知识+ x-agent:+ id: knowledge.move+ items:+ as: knowledge_id+ label: title+ param: knowledge_ids+ target: knowledge.get+ label: name+ risk: write+ target: knowledge_base.get+ x-agent-hint: Moves up to 20 documents to another knowledge base of the same+ workspace; knowledge_base_id is the destination, from knowledge_base.list_move_targets.+ Runs in the background; follow with knowledge.get_move_progress./knowledge/move/progress/{task_id}:get:description: 按任务 ID 查询移动进度@@ -17273,13 +17336,19 @@ paths:name: task_idrequired: truetype: string+ x-agent: trueproduces:- application/jsonresponses:"200":description: 进度信息schema:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeMoveProgress'+ allOf:+ - $ref: '#/definitions/internal_handler.DataResponse'+ - properties:+ data:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.KnowledgeMoveProgress'+ type: object"404":description: 任务不存在schema:@@ -17290,6 +17359,9 @@ paths:summary: 获取知识移动进度tags:- 知识+ x-agent:+ id: knowledge.get_move_progress+ risk: read/knowledge/search:get:consumes:diff --git a/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjs b/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjsnew file mode 100644index 000000000..0fd1d6bc8--- /dev/null+++ b/frontend/src/views/chat/components/ToolApprovalCard.description.test.mjs@@ -0,0 +1,30 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import { runInNewContext } from 'node:vm'+import test from 'node:test'++const source = readFileSync(new URL('./ToolApprovalCard.vue', import.meta.url), 'utf8')+const styles = readFileSync(new URL('./agent-interaction-card.less', import.meta.url), 'utf8')+const descriptionCode = source.slice(+ source.indexOf('const descriptionParts ='), source.indexOf('const isJsonValid ='),+).replace(' as string[]', '')+const parse = description => JSON.parse(JSON.stringify(runInNewContext(+ descriptionCode + '\ndescriptionParts', { props: { description }, computed: fn => fn() },+)))++test('batch approval retains every title in the separate item list', () => {+ const titles = Array.from({ length: 20 }, (_, i) => `Document ${i + 1}`)+ const description = ['Delete documents', 'Finance', ...titles.map(title => '- ' + title)].join('\n')+ assert.deepEqual(parse(description), { head: 'Delete documents\nFinance', items: titles })+})++test('legacy multiline titles remain readable through the scrollable fallback', () => {+ const description = 'Delete documents\nFinance\n- First\ncontinued title\n- Last document'+ assert.deepEqual(parse(description), { head: description, items: [] })+ assert.match(source, /class="prompt-desc">\{\{ descriptionParts\.head \}\}/)+ const fallback = styles.match(/\.prompt-desc \{([\s\S]*?)\n\}/)?.[1]+ assert.ok(fallback)+ assert.match(fallback, /white-space:\s*pre-line/)+ assert.match(fallback, /overflow-y:\s*auto/)+ assert.doesNotMatch(fallback, /line-clamp|overflow:\s*hidden/)+})diff --git a/frontend/src/views/chat/components/ToolApprovalCard.vue b/frontend/src/views/chat/components/ToolApprovalCard.vueindex 7218e5dbe..3e433f744 100644--- a/frontend/src/views/chat/components/ToolApprovalCard.vue+++ b/frontend/src/views/chat/components/ToolApprovalCard.vue@@ -1,7 +1,10 @@<template><div v-if="interactive" class="prompt-panel" @click.stop><div class="prompt-question">{{ $t('agentStream.toolApproval.dockQuestion', { target: targetLabel }) }}</div>- <div v-if="description" class="prompt-desc">{{ description }}</div>+ <div v-if="descriptionParts.head" class="prompt-desc">{{ descriptionParts.head }}</div>+ <ul v-if="descriptionParts.items.length" class="prompt-desc-items">+ <li v-for="(item, i) in descriptionParts.items" :key="i">{{ item }}</li>+ </ul><div v-if="hasArgs" class="prompt-args"><button type="button" class="prompt-args-toggle" :aria-expanded="argsExpanded" @click="toggleArgs">@@ -143,6 +146,20 @@ const awaitingInDock = computed(() => open.value && props.variant !== 'dock' &&const hasArgs = computed(() => argsText.value.trim().length > 0)+// A batch operation ends its description with one "- " line per item it acts+// on; those render as a list so every item stays visible.+const descriptionParts = computed(() => {+ const lines = (props.description || '').split('\n')+ const start = lines.findIndex((line) => line.startsWith('- '))+ if (start < 0 || !lines.slice(start).every((line) => line.startsWith('- '))) {+ return { head: (props.description || '').trim(), items: [] as string[] }+ }+ return {+ head: lines.slice(0, start).join('\n').trim(),+ items: lines.slice(start).map((line) => line.slice(2)),+ }+})+const isJsonValid = computed(() => {if (!argsText.value.trim()) return truetry {diff --git a/frontend/src/views/chat/components/agent-interaction-card.less b/frontend/src/views/chat/components/agent-interaction-card.lessindex 08e6a0434..3a8ea7f8c 100644--- a/frontend/src/views/chat/components/agent-interaction-card.less+++ b/frontend/src/views/chat/components/agent-interaction-card.less@@ -276,11 +276,21 @@font-size: var(--agent-step-summary-size, 13px);line-height: 1.55;color: var(--td-text-color-secondary);+ white-space: pre-line;+ word-break: break-word;+ max-height: calc(1.55em * 8);+ overflow-y: auto;+}++.prompt-desc-items {+ margin: -4px 0 0;+ padding-left: 18px;+ max-height: calc(1.55em * 8);+ overflow-y: auto;+ font-size: var(--agent-step-summary-size, 13px);+ line-height: 1.55;+ color: var(--td-text-color-secondary);word-break: break-word;- display: -webkit-box;- -webkit-line-clamp: 3;- -webkit-box-orient: vertical;- overflow: hidden;}.prompt-options {diff --git a/internal/agent/operations/catalog.go b/internal/agent/operations/catalog.goindex 393ccc866..8c1ae2853 100644--- a/internal/agent/operations/catalog.go+++ b/internal/agent/operations/catalog.go@@ -157,8 +157,25 @@ type Target struct {Operation string// Label is the result field shown to the user (e.g. "title").Label string+ // Items, for a batch mutation, also resolves every item it acts on.+ Items *ItemTarget}+// ItemTarget runs a read once per item of a list parameter, so the approval+// names each item rather than showing IDs.+type ItemTarget struct {+ // Param is the mutation's list parameter; at most MaxApprovalItems long.+ Param string+ Operation string+ // As is the target parameter that receives each item.+ As string+ Label string+}++// MaxApprovalItems bounds a batch whose items the approval resolves, so the+// user sees every item they approve.+const MaxApprovalItems = 20+// Param returns the parameter declared under name.func (op Operation) Param(name string) (Param, bool) {for _, p := range op.Params {@@ -423,9 +440,30 @@ func (c *Catalog) validateTarget(op Operation) error {if op.Target == nil {return nil}- target, ok := c.Get(op.Target.Operation)+ if err := c.validateRead(op, op.Target.Operation, op.Target.Label, ""); err != nil {+ return err+ }+ items := op.Target.Items+ if items == nil {+ return nil+ }+ list, ok := op.Param(items.Param)+ if !ok || list.Type != TypeStringList || !list.Required {+ return fmt.Errorf("target items %q must be a required string list", items.Param)+ }+ if list.MaxItems <= 0 || list.MaxItems > MaxApprovalItems {+ return fmt.Errorf("target items %q must be capped at %d or fewer", items.Param, MaxApprovalItems)+ }+ return c.validateRead(op, items.Operation, items.Label, items.As)+}++// validateRead checks a target read of op: a single-object read whose+// parameters op supplies (item, if set, is filled per item instead) and+// whose result has label.+func (c *Catalog) validateRead(op Operation, id, label, item string) error {+ target, ok := c.Get(id)if !ok {- return fmt.Errorf("target %q is not in the catalog", op.Target.Operation)+ return fmt.Errorf("target %q is not in the catalog", id)}if target.Risk != RiskRead {return fmt.Errorf("target %q must be a read operation", target.ID)@@ -433,7 +471,19 @@ func (c *Catalog) validateTarget(op Operation) error {if target.Result.List {return fmt.Errorf("target %q must return a single object", target.ID)}+ if item != "" {+ p, ok := target.Param(item)+ if !ok || p.Type != TypeString || !p.Required {+ return fmt.Errorf("target %q has no required string param %q for each item", target.ID, item)+ }+ if _, clash := op.Param(item); clash {+ return fmt.Errorf("target item param %q is also a param of %q", item, op.ID)+ }+ }for _, p := range target.Params {+ if p.Name == item {+ continue+ }own, ok := op.Param(p.Name)if !ok || own.Type != p.Type {return fmt.Errorf("target param %q is not declared with the same type", p.Name)@@ -442,16 +492,12 @@ func (c *Catalog) validateTarget(op Operation) error {return fmt.Errorf("target param %q is required by the target", p.Name)}}- labelled := falsefor _, f := range target.Result.Fields {- if f.outputKey() == op.Target.Label {- labelled = true+ if f.outputKey() == label {+ return nil}}- if !labelled {- return fmt.Errorf("target label %q is not a result field of %q", op.Target.Label, target.ID)- }- return nil+ return fmt.Errorf("target label %q is not a result field of %q", label, target.ID)}// parseRoute checks that route is a clean absolute path in an allowed areadiff --git a/internal/agent/operations/catalog_test.go b/internal/agent/operations/catalog_test.goindex 5e368fedb..ef2caf31f 100644--- a/internal/agent/operations/catalog_test.go+++ b/internal/agent/operations/catalog_test.go@@ -98,6 +98,54 @@ func TestNewCatalogChecksTargets(t *testing.T) {assert.Error(t, err, "target needs a param the mutation does not declare")}+func TestNewCatalogChecksItemTargets(t *testing.T) {+ kb := Param{Name: "knowledge_base_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}+ doc := Param{Name: "knowledge_id", In: InPath, Key: "id", Type: TypeString, Required: true, Description: "d"}+ ids := Param{+ Name: "knowledge_ids", In: InBody, Key: "ids", Type: TypeStringList, Required: true,+ Description: "d", MaxItems: MaxApprovalItems,+ }+ getKB := readOp("knowledge_base.get", "/api/v1/knowledge-bases/:id", kb)+ getDoc := readOp("knowledge.get", "/api/v1/knowledge/:id", doc)+ batch := func(mut func(*Operation)) Operation {+ kbBody := kb+ kbBody.In, kbBody.Key = InBody, "kb_id"+ op := Operation{+ ID: "knowledge.batch_delete", Summary: "s", Risk: RiskDestructive, Method: http.MethodPost,+ Route: "/api/v1/knowledge/batch-delete", Params: []Param{kbBody, ids},+ Target: &Target{Operation: "knowledge_base.get", Label: "title", Items: &ItemTarget{+ Param: "knowledge_ids", Operation: "knowledge.get", As: "knowledge_id", Label: "title",+ }},+ }+ if mut != nil {+ mut(&op)+ }+ return op+ }+ _, err := NewCatalog(getKB, getDoc, batch(nil))+ require.NoError(t, err)++ cases := map[string]func(*Operation){+ "uncapped list": func(op *Operation) { op.Params[1].MaxItems = 0 },+ "list longer than an approval shows": func(op *Operation) {+ op.Params[1].MaxItems = MaxApprovalItems + 1+ },+ "items param is not a list": func(op *Operation) { op.Target.Items.Param = "knowledge_base_id" },+ "item param the target lacks": func(op *Operation) { op.Target.Items.As = "chunk_id" },+ "item param shadows a param": func(op *Operation) {+ op.Params = append(op.Params, Param{Name: "knowledge_id", In: InBody, Type: TypeString, Description: "d"})+ },+ "item label not projected": func(op *Operation) { op.Target.Items.Label = "name" },+ "item target is a mutation": func(op *Operation) { op.Target.Items.Operation = "knowledge.batch_delete" },+ }+ for name, mut := range cases {+ t.Run(name, func(t *testing.T) {+ _, err := NewCatalog(getKB, getDoc, batch(mut))+ assert.Error(t, err)+ })+ }+}+func raw(v any) json.RawMessage {b, _ := json.Marshal(v)return bdiff --git a/internal/agent/operations/spec.go b/internal/agent/operations/spec.goindex 71cceb4be..c2b614f64 100644--- a/internal/agent/operations/spec.go+++ b/internal/agent/operations/spec.go@@ -28,7 +28,8 @@ const (// parameter or field its value may be a string: the model-facing name.extAgent = "x-agent"// extAgentMaximum caps an integer parameter below what the API allows,- // to keep results within what the model context can use.+ // to keep results within what the model context can use, or the length+ // of a string list.extAgentMaximum = "x-agent-maximum"// extAgentMaxBytes raises the string-parameter byte cap up to// maxAgentStringBytes. The default stays maxStringParamBytes.@@ -41,6 +42,15 @@ const (extAgentKeys = "x-agent-keys")+// agentItems is ItemTarget as written in x-agent:+// {"param":"knowledge_ids","target":"knowledge.get","as":"knowledge_id","label":"title"}.+type agentItems struct {+ Param string `json:"param"`+ Target string `json:"target"`+ As string `json:"as"`+ Label string `json:"label"`+}+// agentOperation is the value of x-agent on an operation.type agentOperation struct {ID string `json:"id"`@@ -48,6 +58,8 @@ type agentOperation struct {// Target and Label declare the approval target of a mutation.Target string `json:"target"`Label string `json:"label"`+ // Items also resolves each item of a batch for the approval.+ Items *agentItems `json:"items,omitempty"`// Root overrides the projected part of the response. By default it is// "data" when the body has that envelope and the body itself otherwise.Root *string `json:"root"`@@ -178,6 +190,15 @@ func (doc *specDocument) compile(method, path string, sop specOperation) (Operat}op.Target = &Target{Operation: meta.Target, Label: meta.Label}}+ if items := meta.Items; items != nil {+ if op.Target == nil {+ return Operation{}, fmt.Errorf("%s: items needs a target", extAgent)+ }+ if items.Param == "" || items.Target == "" || items.As == "" || items.Label == "" {+ return Operation{}, fmt.Errorf("%s: items needs param, target, as and label", extAgent)+ }+ op.Target.Items = &ItemTarget{Param: items.Param, Operation: items.Target, As: items.As, Label: items.Label}+ }for _, sp := range sop.Parameters {params, err := doc.params(sp)@@ -336,15 +357,30 @@ func (doc *specDocument) typeParam(p *Param, shape *specSchema, agentMax, agentMreturn fmt.Errorf("unsupported type %q", shape.Type)}if p.Type == TypeString || p.Type == TypeStringList {- if agentMax != "" {- return fmt.Errorf("%s applies to integers only", extAgentMaximum)+ if err := boundString(p, agentMaxBytes); err != nil {+ return err}- return boundString(p, agentMaxBytes)- }- if agentMaxBytes != "" {+ } else if agentMaxBytes != "" {return fmt.Errorf("%s applies to strings only", extAgentMaxBytes)}- return boundInteger(p, shape.Minimum, shape.Maximum, agentMax)+ switch p.Type {+ case TypeInteger:+ return boundInteger(p, shape.Minimum, shape.Maximum, agentMax)+ case TypeStringList:+ if agentMax == "" {+ return nil+ }+ limit, err := strconv.Atoi(agentMax)+ if err != nil || limit < 1 || limit > defaultMaxListItems {+ return fmt.Errorf("%s %q must be between 1 and %d items", extAgentMaximum, agentMax, defaultMaxListItems)+ }+ p.MaxItems = limit+ return nil+ }+ if agentMax != "" {+ return fmt.Errorf("%s applies to integers and lists only", extAgentMaximum)+ }+ return nil}func boundString(p *Param, agentMaxBytes string) error {diff --git a/internal/agent/operations/spec_test.go b/internal/agent/operations/spec_test.goindex 5797cf057..a5804f127 100644--- a/internal/agent/operations/spec_test.go+++ b/internal/agent/operations/spec_test.go@@ -188,6 +188,14 @@ func TestFromSpecRejectsBadAnnotations(t *testing.T) {"catch-all before the last segment": {`{"id": "doc.list", "risk": "read"}`, `{"id": "doc.list", "risk": "read", "catch_all": "id"}`,},+ "items without a target": {+ `{"id": "doc.get", "risk": "read"}`,+ `{"id": "doc.get", "risk": "read", "items": {"param": "a", "target": "b", "as": "c", "label": "d"}}`,+ },+ "items missing a key": {+ `"target": "doc.get", "label": "title"`,+ `"target": "doc.get", "label": "title", "items": {"param": "knowledge_ids", "target": "doc.get"}`,+ },"catch-all naming no segment": {`{"id": "doc.get", "risk": "read"}`, `{"id": "doc.get", "risk": "read", "catch_all": "slug"}`,},@@ -267,6 +275,9 @@ func TestBuiltinMatchesHandlerAnnotations(t *testing.T) {meta := agentOperation{ID: op.ID, Risk: op.Risk}if op.Target != nil {meta.Target, meta.Label = op.Target.Operation, op.Target.Label+ if it := op.Target.Items; it != nil {+ meta.Items = &agentItems{Param: it.Param, Target: it.Operation, As: it.As, Label: it.Label}+ }}if i := strings.LastIndex(op.Route, "/*"); i >= 0 {meta.CatchAll = op.Route[i+2:]@@ -385,3 +396,26 @@ func TestBuiltinListAndDocumentLimits(t *testing.T) {}assert.Equal(t, Field{From: "content", As: "content", MaxRunes: 8000}, contentField)}++func TestTypeParamCombinesListAndStringBounds(t *testing.T) {+ doc := &specDocument{}+ shape := &specSchema{Type: "array", Items: &specSchema{Type: "string"}}+ var p Param+ require.NoError(t, doc.typeParam(&p, shape, "2", "5"))+ op := Operation{Method: http.MethodPost, Params: []Param{p}}+ op.Params[0].Name = "titles"+ op.Params[0].In = InBody+ _, err := op.Build(map[string]json.RawMessage{"titles": raw([]string{"one", "two"})})+ require.NoError(t, err)+ _, err = op.Build(map[string]json.RawMessage{"titles": raw([]string{"one", "two", "three"})})+ require.Error(t, err, "the item count remains bounded")+ _, err = op.Build(map[string]json.RawMessage{"titles": raw([]string{"too long"})})+ require.Error(t, err, "each string remains bounded")++ for _, kind := range []string{"integer", "boolean"} {+ assert.Error(t, doc.typeParam(&Param{}, &specSchema{Type: kind}, "", "5"))+ }+ for _, kind := range []string{"string", "boolean"} {+ assert.Error(t, doc.typeParam(&Param{}, &specSchema{Type: kind}, "2", ""))+ }+}diff --git a/internal/agent/tools/operations.go b/internal/agent/tools/operations.goindex f2cf3e8f1..bd2a13dc9 100644--- a/internal/agent/tools/operations.go+++ b/internal/agent/tools/operations.go@@ -419,11 +419,62 @@ func (t *RunOperationTool) describeTarget(input runOperationInput,identity operations.Identity,) (string, *types.ToolResult) {- target, ok := t.rt.Catalog.Get(op.Target.Operation)+ items := op.Target.Items+ var ids []string+ if items != nil {+ if raw, ok := input.Params[items.Param]; ok {+ if err := json.Unmarshal(raw, &ids); err != nil {+ return "", operationFailure(fmt.Sprintf("invalid params for %s: %s must be an array of strings",+ op.ID, items.Param))+ }+ }+ if len(ids) > operations.MaxApprovalItems {+ return "", operationFailure(fmt.Sprintf("invalid params for %s: %s accepts at most %d items",+ op.ID, items.Param, operations.MaxApprovalItems))+ }+ }+ label, blocked := t.readLabel(ctx, op, op.Target.Operation, op.Target.Label, input.Params, identity)+ if blocked != nil || items == nil {+ return label, blocked+ }+ lines := []string{label}+ for _, id := range ids {+ encoded, err := json.Marshal(id)+ if err != nil {+ return "", operationFailure(err.Error())+ }+ params := make(map[string]json.RawMessage, len(input.Params)+1)+ for k, v := range input.Params {+ params[k] = v+ }+ params[items.As] = encoded+ itemLabel, blocked := t.readLabel(ctx, op, items.Operation, items.Label, params, identity)+ if blocked != nil {+ return "", blocked+ }+ if itemLabel == "" {+ itemLabel = id+ }+ // Titles are user content, not description delimiters. Keep each+ // item on one line so the approval card cannot hide later items.+ lines = append(lines, "- "+strings.Join(strings.Fields(itemLabel), " "))+ }+ return strings.TrimSpace(strings.Join(lines, "\n")), nil+}++// readLabel runs one target read of op and returns the label field.+func (t *RunOperationTool) readLabel(+ ctx context.Context,+ op operations.Operation,+ targetID, label string,+ params map[string]json.RawMessage,+ identity operations.Identity,+) (string, *types.ToolResult) {+ target, ok := t.rt.Catalog.Get(targetID)if !ok {return "", operationFailure(fmt.Sprintf("%s is misconfigured", op.ID))}- call, err := target.Build(operations.SelectParams(target, input.Params))+ call, err := target.Build(operations.SelectParams(target, params))if err != nil {return "", operationFailure(fmt.Sprintf("invalid params for %s: %v", op.ID, err))}@@ -439,7 +490,7 @@ func (t *RunOperationTool) describeTarget(if err != nil {return "", operationFailure(fmt.Sprintf("%s returned an unexpected response", target.ID))}- return projected.Label(op.Target.Label), nil+ return projected.Label(label), nil}func approvalDescription(op operations.Operation, label, detail string) string {@@ -512,8 +563,12 @@ func mutationDetail(if s, ok := rawString(params, "content"); ok && s != "" {lines = append(lines, fmt.Sprintf("Content (%d characters): %s", len([]rune(s)), excerpt(s)))}- if ids, ok := rawStringList(params, "knowledge_ids"); ok && len(ids) > 0 {- lines = append(lines, "Documents: "+documentTitles(ctx, t, ids, identity))+ // Item targets already resolve every document and place its title in the+ // trailing approval list. Do not fetch or append those titles again.+ if op.Target == nil || op.Target.Items == nil {+ if ids, ok := rawStringList(params, "knowledge_ids"); ok && len(ids) > 0 {+ lines = append(lines, "Documents: "+documentTitles(ctx, t, ids, identity))+ }}return strings.Join(lines, "\n")}diff --git a/internal/agent/tools/operations_test.go b/internal/agent/tools/operations_test.goindex 7c119d635..7c7935041 100644--- a/internal/agent/tools/operations_test.go+++ b/internal/agent/tools/operations_test.go@@ -181,6 +181,71 @@ func TestRunOperationApprovedMutation(t *testing.T) {assert.Equal(t, []string{"p1"}, gate.executed)}+func TestRunOperationBatchApprovalNamesEveryItem(t *testing.T) {+ responses := map[string]*operations.Response{+ "GET /api/v1/knowledge-bases/kb1": {+ Status: http.StatusOK, Body: []byte(`{"success":true,"data":{"id":"kb1","name":"Finance"}}`),+ },+ "GET /api/v1/knowledge/k1": {Status: http.StatusOK, Body: []byte(docBody)},+ "GET /api/v1/knowledge/k2": {+ Status: http.StatusOK, Body: []byte(`{"success":true,"data":{"id":"k2","title":"Q4 plan.docx"}}`),+ },+ "POST /api/v1/knowledge/batch-delete": {+ Status: http.StatusOK, Body: []byte(`{"success":true,"data":{"task_id":"t1","deleted_count":2}}`),+ },+ }+ d := &fakeDispatcher{responses: responses}+ gate := &fakeApprover{decision: approval.Decision{Approved: true, PendingID: "p1"}}+ params := map[string]any{"knowledge_base_id": "kb1", "knowledge_ids": []string{"k1", "k2"}}++ res, _ := newRunTool(d, gate).Execute(interactiveCtx(), runArgs("knowledge.batch_delete", params))+ require.True(t, res.Success, res.Error)+ require.Len(t, gate.requests, 1)+ assert.Equal(t, "批量删除知识\nFinance\n- Q3 report.pdf\n- Q4 plan.docx", gate.requests[0].Description)+ assert.Contains(t, res.Output, `"deleted_count":2`)++ d = &fakeDispatcher{responses: responses}+ gate = &fakeApprover{decision: approval.Decision{Approved: true, PendingID: "p1"}}+ params["knowledge_ids"] = []string{"k1", "k-other"}+ res, _ = newRunTool(d, gate).Execute(interactiveCtx(), runArgs("knowledge.batch_delete", params))+ assert.False(t, res.Success)+ assert.Contains(t, res.Error, "Knowledge not found")+ assert.Empty(t, gate.requests, "one item the user cannot see blocks the whole batch")++ ids := make([]string, operations.MaxApprovalItems+1)+ for i := range ids {+ ids[i] = "k1"+ }+ params["knowledge_ids"] = ids+ d = &fakeDispatcher{responses: responses}+ res, _ = newRunTool(d, gate).Execute(interactiveCtx(), runArgs("knowledge.batch_delete", params))+ assert.False(t, res.Success)+ assert.Contains(t, res.Error, "at most 20")+ assert.Empty(t, d.calls)+}++func TestRunOperationBatchApprovalKeepsMultilineTitlesOnOneLine(t *testing.T) {+ for _, separator := range []string{"\n", "\r\n", "\r", "\u2028", "\u2029"} {+ t.Run(separator, func(t *testing.T) {+ body, err := json.Marshal(map[string]any{"data": map[string]any{"title": "First" + separator + "document"}})+ require.NoError(t, err)+ d := &fakeDispatcher{responses: map[string]*operations.Response{+ "GET /api/v1/knowledge-bases/kb1": {Status: http.StatusOK, Body: []byte(`{"data":{"name":"Docs"}}`)},+ "GET /api/v1/knowledge/k1": {Status: http.StatusOK, Body: body},+ "GET /api/v1/knowledge/k2": {Status: http.StatusOK, Body: []byte(`{"data":{"title":"Second"}}`)},+ }}+ gate := &fakeApprover{decision: approval.Decision{Approved: false}}+ _, err = newRunTool(d, gate).Execute(interactiveCtx(), runArgs("knowledge.batch_delete", map[string]any{+ "knowledge_base_id": "kb1", "knowledge_ids": []string{"k1", "k2"},+ }))+ require.NoError(t, err)+ require.Len(t, gate.requests, 1)+ assert.Equal(t, "批量删除知识\nDocs\n- First document\n- Second", gate.requests[0].Description)+ assert.Len(t, d.calls, 3, "declining never dispatches the delete")+ })+ }+}+func TestRunOperationDeclinedOrEditedToAnotherOperation(t *testing.T) {responses := map[string]*operations.Response{"GET /api/v1/knowledge/k1": {Status: http.StatusOK, Body: []byte(docBody)},@@ -290,7 +355,7 @@ func TestRunOperationApprovalNamesTheChange(t *testing.T) {func TestFindOperationsDescribesMatches(t *testing.T) {tool := NewFindOperationsTool(operations.Builtin())- res, err := tool.Execute(context.Background(), json.RawMessage(`{"query":"delete"}`))+ res, err := tool.Execute(context.Background(), json.RawMessage(`{"query":"knowledge.delete"}`))require.NoError(t, err)require.True(t, res.Success)var out struct {diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex 4af192e84..b3de7271e 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -1857,8 +1857,10 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) {// BatchDeleteKnowledgeRequest is the body schema for POST /knowledge/batch-delete.type BatchDeleteKnowledgeRequest struct {- KBID string `json:"kb_id" binding:"required"`- IDs []string `json:"ids" binding:"required"`+ // Knowledge base the documents belong to.+ KBID string `json:"kb_id" binding:"required" extensions:"x-agent=knowledge_base_id"`+ // Documents to delete.+ IDs []string `json:"ids" binding:"required" extensions:"x-agent=knowledge_ids,x-agent-maximum=20"`}// BatchDeleteKnowledge godoc@@ -1873,6 +1875,8 @@ type BatchDeleteKnowledgeRequest struct {// @Failure 403 {object} errors.AppError "权限不足"// @Security Bearer// @Security ApiKeyAuth+// @x-agent {"id":"knowledge.batch_delete","risk":"destructive","target":"knowledge_base.get","label":"name","items":{"param":"knowledge_ids","target":"knowledge.get","as":"knowledge_id","label":"title"}}+// @x-agent-hint "Removes up to 20 documents of one knowledge base with their chunks, embeddings and graph data. Cannot be undone; the confirmation lists every document."// @Router /knowledge/batch-delete [post]func (h *KnowledgeHandler) BatchDeleteKnowledge(c *gin.Context) {ctx := c.Request.Context()@@ -2957,18 +2961,22 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {// MoveKnowledgeRequest defines the request for moving knowledge itemstype MoveKnowledgeRequest struct {- KnowledgeIDs []string `json:"knowledge_ids" binding:"required,min=1"`- SourceKBID string `json:"source_kb_id" binding:"required"`- TargetKBID string `json:"target_kb_id" binding:"required"`- Mode string `json:"mode" binding:"required,oneof=reuse_vectors reparse"`+ // Documents to move.+ KnowledgeIDs []string `json:"knowledge_ids" binding:"required,min=1" extensions:"x-agent,x-agent-maximum=20"`+ // Knowledge base the documents are in now.+ SourceKBID string `json:"source_kb_id" binding:"required" extensions:"x-agent=source_knowledge_base_id"`+ // Knowledge base to move them to.+ TargetKBID string `json:"target_kb_id" binding:"required" extensions:"x-agent=knowledge_base_id"`+ // reuse_vectors keeps the embeddings; reparse processes the documents again.+ Mode string `json:"mode" binding:"required,oneof=reuse_vectors reparse" enums:"reuse_vectors,reparse" extensions:"x-agent"`}// MoveKnowledgeResponse defines the response for move knowledgetype MoveKnowledgeResponse struct {- TaskID string `json:"task_id"`+ TaskID string `json:"task_id" extensions:"x-agent"`SourceKBID string `json:"source_kb_id"`TargetKBID string `json:"target_kb_id"`- KnowledgeCount int `json:"knowledge_count"`+ KnowledgeCount int `json:"knowledge_count" extensions:"x-agent"`Message string `json:"message"`}@@ -2981,10 +2989,12 @@ type MoveKnowledgeResponse struct {// @Accept json// @Produce json// @Param request body handler.MoveKnowledgeRequest true "{source_kb_id, target_kb_id, knowledge_ids}"-// @Success 200 {object} handler.MoveKnowledgeResponse "任务信息"+// @Success 200 {object} handler.DataResponse{data=handler.MoveKnowledgeResponse} "任务信息"// @Failure 400 {object} errors.AppError "请求参数错误"// @Security Bearer// @Security ApiKeyAuth+// @x-agent {"id":"knowledge.move","risk":"write","target":"knowledge_base.get","label":"name","items":{"param":"knowledge_ids","target":"knowledge.get","as":"knowledge_id","label":"title"}}+// @x-agent-hint "Moves up to 20 documents to another knowledge base of the same workspace; knowledge_base_id is the destination, from knowledge_base.list_move_targets. Runs in the background; follow with knowledge.get_move_progress."// @Router /knowledge/move [post]func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {ctx := c.Request.Context()@@ -3178,11 +3188,12 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {// @Description 按任务 ID 查询移动进度// @Tags 知识// @Produce json-// @Param task_id path string true "移动任务 ID"-// @Success 200 {object} types.KnowledgeMoveProgress "进度信息"+// @Param task_id path string true "移动任务 ID" extensions(x-agent)+// @Success 200 {object} handler.DataResponse{data=types.KnowledgeMoveProgress} "进度信息"// @Failure 404 {object} errors.AppError "任务不存在"// @Security Bearer// @Security ApiKeyAuth+// @x-agent {"id":"knowledge.get_move_progress","risk":"read"}// @Router /knowledge/move/progress/{task_id} [get]func (h *KnowledgeHandler) GetKnowledgeMoveProgress(c *gin.Context) {ctx := c.Request.Context()diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.goindex 842944758..9d5eb0a34 100644--- a/internal/handler/knowledgebase.go+++ b/internal/handler/knowledgebase.go@@ -1353,7 +1353,7 @@ func validateKnowledgeBasePromptInstructions(kb *types.KnowledgeBase) error {// @Description 返回与源知识库 Type 一致、EmbeddingModelID 一致、非临时且不是自身的目标知识库列表// @Tags 知识库// @Produce json-// @Param id path string true "源知识库 ID"+// @Param id path string true "源知识库 ID" extensions(x-agent=knowledge_base_id)// @Success 200 {object} handler.DataResponse{data=[]types.KnowledgeBase} "可移动目标列表"// @Failure 400 {object} errors.AppError "请求参数错误"// @Failure 401 {object} errors.AppError "未认证"@@ -1361,6 +1361,8 @@ func validateKnowledgeBasePromptInstructions(kb *types.KnowledgeBase) error {// @Failure 404 {object} errors.AppError "知识库不存在"// @Security Bearer// @Security ApiKeyAuth+// @x-agent {"id":"knowledge_base.list_move_targets","risk":"read"}+// @x-agent-hint "Knowledge bases the documents of this one can be moved to: same type and embedding model."// @Router /knowledge-bases/{id}/move-targets [get]func (h *KnowledgeBaseHandler) ListMoveTargets(c *gin.Context) {ctx := c.Request.Context()diff --git a/internal/handler/swagger_bodies.go b/internal/handler/swagger_bodies.goindex 3aec6361d..1476ea51d 100644--- a/internal/handler/swagger_bodies.go+++ b/internal/handler/swagger_bodies.go@@ -254,7 +254,7 @@ type FolderMoveData struct {// task_id is omitted when the knowledge base was already empty.type SubmittedTaskData struct {TaskID string `json:"task_id,omitempty"`- DeletedCount int `json:"deleted_count,omitempty"`+ DeletedCount int `json:"deleted_count,omitempty" extensions:"x-agent"`ReparseCount int `json:"reparse_count,omitempty" extensions:"x-agent"`}diff --git a/internal/modelcontext/tool_policy.go b/internal/modelcontext/tool_policy.goindex a331974ea..3e0112ade 100644--- a/internal/modelcontext/tool_policy.go+++ b/internal/modelcontext/tool_policy.go@@ -45,7 +45,8 @@ var sourceKeySpaces = map[string]sourceKeySpace{"source_refs": spaceDocumentRef,"knowledge_base": spaceKnowledgeBase, "knowledge_base_id": spaceKnowledgeBase,"knowledge_base_ids": spaceKnowledgeBase, "kb_id": spaceKnowledgeBase, "kb_ids": spaceKnowledgeBase,- "url": spaceWeb, "urls": spaceWeb,+ "source_knowledge_base_id": spaceKnowledgeBase,+ "url": spaceWeb, "urls": spaceWeb,"id": spaceAnySource,}@@ -169,7 +170,9 @@ var toolHandlePolicies = map[string]toolHandlePolicy{// come back as handles. Catalog metadata itself carries no identifiers."find_operations": {},"run_operation": {- sourceIDKeys: map[string]struct{}{"knowledge_base_id": {}, "knowledge_id": {}, "knowledge_ids": {}},+ sourceIDKeys: map[string]struct{}{+ "knowledge_base_id": {}, "source_knowledge_base_id": {}, "knowledge_id": {}, "knowledge_ids": {},+ },decodedIssueIDKeys: map[string]struct{}{"issue_id": {}},encodedIssueIDKeys: map[string]struct{}{"issue_id": {}},encodeKnownIssueIDs: true,diff --git a/internal/types/task.go b/internal/types/task.goindex c77f8621f..063ded39e 100644--- a/internal/types/task.go+++ b/internal/types/task.go@@ -478,15 +478,15 @@ type KnowledgeMoveProgress struct {TaskID string `json:"task_id"`SourceKBID string `json:"source_kb_id"`TargetKBID string `json:"target_kb_id"`- Status KBCloneTaskStatus `json:"status"`- Progress int `json:"progress"` // 0-100- Total int `json:"total"` // 总知识数- Processed int `json:"processed"` // 已处理数- Failed int `json:"failed"` // 失败数- Message string `json:"message"` // 状态消息- Error string `json:"error"` // 错误信息- CreatedAt int64 `json:"created_at"` // 任务创建时间- UpdatedAt int64 `json:"updated_at"` // 最后更新时间+ Status KBCloneTaskStatus `json:"status" extensions:"x-agent"`+ Progress int `json:"progress" extensions:"x-agent"` // 0-100+ Total int `json:"total" extensions:"x-agent"` // 总知识数+ Processed int `json:"processed" extensions:"x-agent"` // 已处理数+ Failed int `json:"failed" extensions:"x-agent"` // 失败数+ Message string `json:"message" extensions:"x-agent"` // 状态消息+ Error string `json:"error" extensions:"x-agent"` // 错误信息+ CreatedAt int64 `json:"created_at"` // 任务创建时间+ UpdatedAt int64 `json:"updated_at"` // 最后更新时间}// ManualProcessPayload represents the manual knowledge processing task payload.