feat: Introduce Wiki Fixer agent and related functionalities

- Added a new built-in agent, "Wiki Fixer," designed to repair and optimize Wiki pages based on linter issues, with multilingual support for enhanced accessibility.
- Implemented a corresponding system prompt detailing the agent's role, mission, and workflow for effective issue resolution.
- Introduced new API functions for listing and updating wiki issues, allowing for better management of content conflicts and errors.
- Enhanced the frontend with new UI elements to display pending issues and facilitate auto-fixing, improving user interaction with the Wiki content.

These changes significantly enhance the agent's capabilities for maintaining the accuracy and quality of Wiki pages, fostering a more reliable knowledge base.
This commit is contained in:
wizardchen
2026-04-10 17:56:17 +08:00
parent 3e47376539
commit bd096454e1
29 changed files with 1724 additions and 50 deletions
+11 -4
View File
@@ -369,9 +369,17 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
}
if len(llmContext) > 0 {
// Redact KB tool results from previous turns to prevent the LLM
// from reusing stale retrieval data when the KB has been modified.
sanitized := redactHistoryKBResults(llmContext)
var sanitized []chat.Message
if e.config.RetainRetrievalHistory {
sanitized = llmContext
logger.Infof(context.Background(), "Retaining full retrieval history in context (RetainRetrievalHistory=true)")
} else {
// Redact KB tool results from previous turns to prevent the LLM
// from reusing stale retrieval data when the KB has been modified.
sanitized = redactHistoryKBResults(llmContext)
logger.Infof(context.Background(), "Added %d history messages to context (KB tool results redacted)", len(llmContext))
}
for _, msg := range sanitized {
if msg.Role == "system" {
continue
@@ -380,7 +388,6 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
messages = append(messages, msg)
}
}
logger.Infof(context.Background(), "Added %d history messages to context (KB tool results redacted)", len(llmContext))
}
// Build user message with runtime context safety tag
+12
View File
@@ -24,9 +24,15 @@ const (
ToolReadSkill = "read_skill"
// Wiki-related tools (only available when wiki KBs are in scope)
ToolWikiReadPage = "wiki_read_page"
ToolWikiWritePage = "wiki_write_page"
ToolWikiReplaceText = "wiki_replace_text"
ToolWikiRenamePage = "wiki_rename_page"
ToolWikiDeletePage = "wiki_delete_page"
ToolWikiSearch = "wiki_search"
ToolWikiReadSourceDoc = "wiki_read_source_doc"
ToolWikiFlagIssue = "wiki_flag_issue"
ToolWikiReadIssue = "wiki_read_issue"
ToolWikiUpdateIssue = "wiki_update_issue"
)
// AvailableTool defines a simple tool metadata used by settings APIs.
@@ -57,6 +63,12 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadSourceDoc, Label: "精读源文档", Description: "使用知识点深入阅读特定原始文档"},
{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页面问题状态"},
}
}
+115
View File
@@ -0,0 +1,115 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type wikiDeletePageTool struct {
BaseTool
wikiPageService interfaces.WikiPageService
kbIDs []string
}
// NewWikiDeletePageTool creates a new wiki_delete_page tool
func NewWikiDeletePageTool(wikiPageService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiDeletePageTool{
BaseTool: NewBaseTool(
ToolWikiDeletePage,
"Delete a Wiki page. Automatically cleans up incoming links on other pages to prevent dead links.",
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "The slug of the Wiki page to delete"
}
},
"required": ["slug"]
}`),
),
wikiPageService: wikiPageService,
kbIDs: kbIDs,
}
}
func (t *wikiDeletePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to parse arguments: " + err.Error()}, nil
}
if len(t.kbIDs) == 0 {
return &types.ToolResult{Success: false, Error: "No knowledge bases available for editing"}, nil
}
kbID := t.kbIDs[0]
if params.Slug == "" {
return &types.ToolResult{Success: false, Error: "slug is required"}, nil
}
// Fetch page to get its incoming links before deleting
existingPage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, params.Slug)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to fetch page to delete: " + err.Error()}, nil
}
inLinks := make([]string, len(existingPage.InLinks))
copy(inLinks, existingPage.InLinks)
err = t.wikiPageService.DeletePage(ctx, kbID, params.Slug)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to delete page: " + err.Error()}, nil
}
// Clean up incoming links to prevent dead links
updatedCount := 0
var updatedSlugs []string
for _, sourceSlug := range inLinks {
sourcePage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, sourceSlug)
if err == nil {
changed := false
// Replace [[deleted-slug]] with readable name
parts := strings.Split(params.Slug, "/")
readableName := parts[len(parts)-1]
readableName = strings.ReplaceAll(readableName, "-", " ")
link1 := "[[" + params.Slug + "]]"
if strings.Contains(sourcePage.Content, link1) {
sourcePage.Content = strings.ReplaceAll(sourcePage.Content, link1, readableName)
changed = true
}
// Replace [[deleted-slug|Text]] with just Text
re := regexp.MustCompile(`\[\[` + regexp.QuoteMeta(params.Slug) + `\|([^\]]+)\]\]`)
if re.MatchString(sourcePage.Content) {
sourcePage.Content = re.ReplaceAllString(sourcePage.Content, "$1")
changed = true
}
if changed {
_, updateErr := t.wikiPageService.UpdatePage(ctx, sourcePage)
if updateErr == nil {
updatedCount++
updatedSlugs = append(updatedSlugs, sourceSlug)
}
}
}
}
outputMsg := fmt.Sprintf("Successfully deleted page %s and cleaned up %d incoming links.", params.Slug, updatedCount)
if updatedCount > 0 {
outputMsg += fmt.Sprintf(" Affected pages: %s", strings.Join(updatedSlugs, ", "))
}
return &types.ToolResult{Success: true, Output: outputMsg}, nil
}
+92
View File
@@ -0,0 +1,92 @@
package tools
import (
"context"
"encoding/json"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type wikiReadIssueTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiReadIssueTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiReadIssueTool{
BaseTool: NewBaseTool(
ToolWikiReadIssue,
"Read the details of a specific wiki page issue or list pending issues for a wiki page.",
json.RawMessage(`{
"type": "object",
"properties": {
"issue_id": {
"type": "string",
"description": "Optional: The ID of a specific issue to read."
},
"slug": {
"type": "string",
"description": "Optional: The slug of the wiki page to list pending issues for."
}
},
"description": "Provide either issue_id or slug to read issue(s)."
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiReadIssueTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
IssueID string `json:"issue_id"`
Slug string `json:"slug"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil
}
issueID := strings.TrimSpace(params.IssueID)
slug := strings.TrimSpace(params.Slug)
if issueID == "" && slug == "" {
return &types.ToolResult{Success: false, Error: "Either issue_id or slug is required"}, nil
}
if len(t.kbIDs) == 0 {
return &types.ToolResult{Success: false, Error: "No knowledge bases available"}, nil
}
kbID := t.kbIDs[0]
if issueID != "" {
// Just reuse ListIssues since there's no GetIssueByID yet
issues, err := t.wikiService.ListIssues(ctx, kbID, "", "")
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to list issues: " + err.Error()}, nil
}
for _, issue := range issues {
if issue.ID == issueID {
out, _ := json.MarshalIndent(issue, "", " ")
return &types.ToolResult{Success: true, Output: string(out)}, nil
}
}
return &types.ToolResult{Success: false, Error: "Issue not found"}, nil
}
issues, err := t.wikiService.ListIssues(ctx, kbID, slug, "pending")
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to list issues: " + err.Error()}, nil
}
if len(issues) == 0 {
return &types.ToolResult{Success: true, Output: "No pending issues found for slug: " + slug}, nil
}
out, _ := json.MarshalIndent(issues, "", " ")
return &types.ToolResult{Success: true, Output: string(out)}, nil
}
+143
View File
@@ -0,0 +1,143 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type wikiRenamePageTool struct {
BaseTool
wikiPageService interfaces.WikiPageService
kbIDs []string
}
// NewWikiRenamePageTool creates a new wiki_rename_page tool
func NewWikiRenamePageTool(wikiPageService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiRenamePageTool{
BaseTool: NewBaseTool(
ToolWikiRenamePage,
"Rename a Wiki page's slug. Automatically cascades the new slug to all pages that linked to the old one.",
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "The current slug of the Wiki page"
},
"new_slug": {
"type": "string",
"description": "The new slug for the page"
}
},
"required": ["slug", "new_slug"]
}`),
),
wikiPageService: wikiPageService,
kbIDs: kbIDs,
}
}
func (t *wikiRenamePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
NewSlug string `json:"new_slug"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to parse arguments: " + err.Error()}, nil
}
if len(t.kbIDs) == 0 {
return &types.ToolResult{Success: false, Error: "No knowledge bases available for editing"}, nil
}
kbID := t.kbIDs[0]
if params.NewSlug == "" {
return &types.ToolResult{Success: false, Error: "new_slug is required"}, nil
}
if params.NewSlug == params.Slug {
return &types.ToolResult{Success: false, Error: "new_slug must be different from old slug"}, nil
}
// Get existing page
existingPage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, params.Slug)
if err != nil {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("Page %s not found. Cannot rename a non-existent page.", params.Slug)}, nil
}
inLinks := make([]string, len(existingPage.InLinks))
copy(inLinks, existingPage.InLinks)
// Create new page with new slug but same content
newPage := &types.WikiPage{
KnowledgeBaseID: kbID,
Slug: params.NewSlug,
Title: existingPage.Title,
Summary: existingPage.Summary,
Content: existingPage.Content,
PageType: existingPage.PageType,
Aliases: existingPage.Aliases,
}
_, err = t.wikiPageService.CreatePage(ctx, newPage)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to create renamed page: " + err.Error()}, nil
}
// Update incoming links in other pages
updatedCount := 0
var updatedSlugs []string
for _, sourceSlug := range inLinks {
sourcePage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, sourceSlug)
if err == nil {
changed := false
// Replace [[old-slug]] with [[new-slug]]
link1 := "[[" + params.Slug + "]]"
newLink1 := "[[" + params.NewSlug + "]]"
if strings.Contains(sourcePage.Content, link1) {
sourcePage.Content = strings.ReplaceAll(sourcePage.Content, link1, newLink1)
changed = true
}
// Replace [[old-slug|text]] with [[new-slug|text]]
link2 := "[[" + params.Slug + "|"
newLink2 := "[[" + params.NewSlug + "|"
if strings.Contains(sourcePage.Content, link2) {
sourcePage.Content = strings.ReplaceAll(sourcePage.Content, link2, newLink2)
changed = true
}
if changed {
_, updateErr := t.wikiPageService.UpdatePage(ctx, sourcePage)
if updateErr == nil {
updatedCount++
updatedSlugs = append(updatedSlugs, sourceSlug)
}
}
}
}
// Delete old page
err = t.wikiPageService.DeletePage(ctx, kbID, params.Slug)
if err != nil {
return &types.ToolResult{Success: false, Error: "Successfully created new page and updated links, but failed to delete old page: " + err.Error()}, nil
}
// Inject cross-links so other pages know about this new slug
t.wikiPageService.InjectCrossLinks(ctx, kbID, []string{params.NewSlug})
// Rebuild the index page to reflect the new/updated summary
_ = t.wikiPageService.RebuildIndexPage(ctx, kbID)
outputMsg := fmt.Sprintf("Successfully renamed page %s to %s and updated %d incoming links.", params.Slug, params.NewSlug, updatedCount)
if updatedCount > 0 {
outputMsg += fmt.Sprintf(" Affected pages: %s", strings.Join(updatedSlugs, ", "))
}
return &types.ToolResult{Success: true, Output: outputMsg}, nil
}
+97
View File
@@ -0,0 +1,97 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type wikiReplaceTextTool struct {
BaseTool
wikiPageService interfaces.WikiPageService
kbIDs []string
}
// NewWikiReplaceTextTool creates a new wiki_replace_text tool
func NewWikiReplaceTextTool(wikiPageService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiReplaceTextTool{
BaseTool: NewBaseTool(
ToolWikiReplaceText,
"Replace specific exact text in a Wiki page. Ideal for minor corrections.",
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "The slug of the Wiki page"
},
"old_text": {
"type": "string",
"description": "The exact text to find and replace"
},
"new_text": {
"type": "string",
"description": "The new text to insert"
},
"source_refs": {
"type": "array",
"items": {"type": "string"},
"description": "An optional list of source knowledge IDs that justify this change. If provided, these will COMPLETELY REPLACE the existing source_refs of the page."
}
},
"required": ["slug", "old_text", "new_text"]
}`),
),
wikiPageService: wikiPageService,
kbIDs: kbIDs,
}
}
func (t *wikiReplaceTextTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
OldText string `json:"old_text"`
NewText string `json:"new_text"`
SourceRefs []string `json:"source_refs"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to parse arguments: " + err.Error()}, nil
}
if len(t.kbIDs) == 0 {
return &types.ToolResult{Success: false, Error: "No knowledge bases available for editing"}, nil
}
kbID := t.kbIDs[0]
if params.OldText == "" {
return &types.ToolResult{Success: false, Error: "old_text is required"}, nil
}
// Get the existing page
existingPage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, params.Slug)
if err != nil {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("Failed to fetch page %s: %v", params.Slug, err)}, nil
}
if !strings.Contains(existingPage.Content, params.OldText) {
return &types.ToolResult{Success: false, Error: "old_text not found in the current page content. Ensure you copy it exactly as it appears."}, nil
}
existingPage.Content = strings.Replace(existingPage.Content, params.OldText, params.NewText, 1)
if len(params.SourceRefs) > 0 {
existingPage.SourceRefs = params.SourceRefs
}
_, err = t.wikiPageService.UpdatePage(ctx, existingPage)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to update page: " + err.Error()}, nil
}
return &types.ToolResult{Success: true, Output: fmt.Sprintf("Successfully replaced text on page %s.", params.Slug)}, nil
}
+4
View File
@@ -145,6 +145,9 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
<sources>
%s
</sources>
<summary>
%s
</summary>
<content>
%s
</content>
@@ -153,6 +156,7 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
strings.Join(outLinksDesc, ", "),
strings.Join(inLinksDesc, ", "),
strings.Join(sourcesDesc, "\n"),
page.Summary,
page.Content,
)
outputs = append(outputs, output)
+74
View File
@@ -0,0 +1,74 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type wikiUpdateIssueTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiUpdateIssueTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiUpdateIssueTool{
BaseTool: NewBaseTool(
ToolWikiUpdateIssue,
"Update the status of a specific wiki page issue (e.g., set it to 'resolved' or 'ignored').",
json.RawMessage(`{
"type": "object",
"properties": {
"issue_id": {
"type": "string",
"description": "The ID of the issue to update."
},
"status": {
"type": "string",
"enum": ["resolved", "ignored", "pending"],
"description": "The new status for the issue."
}
},
"required": ["issue_id", "status"]
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiUpdateIssueTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
IssueID string `json:"issue_id"`
Status string `json:"status"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil
}
if params.IssueID == "" {
return &types.ToolResult{Success: false, Error: "issue_id is required"}, nil
}
if params.Status == "" {
return &types.ToolResult{Success: false, Error: "status is required"}, nil
}
if len(t.kbIDs) == 0 {
return &types.ToolResult{Success: false, Error: "No knowledge bases available"}, nil
}
// Update issue status
err := t.wikiService.UpdateIssueStatus(ctx, params.IssueID, params.Status)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to update issue status: " + err.Error()}, nil
}
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("Successfully updated issue %s to status '%s'", params.IssueID, params.Status),
}, nil
}
+145
View File
@@ -0,0 +1,145 @@
package tools
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type wikiWritePageTool struct {
BaseTool
wikiPageService interfaces.WikiPageService
kbIDs []string
}
// NewWikiWritePageTool creates a new wiki_write_page tool
func NewWikiWritePageTool(wikiPageService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiWritePageTool{
BaseTool: NewBaseTool(
ToolWikiWritePage,
"Create a new Wiki page or completely overwrite an existing one. Automatically handles outbound links.",
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "The slug of the Wiki page (e.g. 'entity/hunyuan-damoxing')"
},
"title": {
"type": "string",
"description": "The title of the page"
},
"summary": {
"type": "string",
"description": "A one-sentence summary for the index listing"
},
"content": {
"type": "string",
"description": "The FULL, complete Markdown content of the page. Do NOT use placeholders."
},
"page_type": {
"type": "string",
"description": "The page type, e.g., 'summary', 'entity', 'concept', 'synthesis', 'comparison'"
},
"aliases": {
"type": "array",
"items": {"type": "string"},
"description": "A list of aliases for the page (optional)"
},
"source_refs": {
"type": "array",
"items": {"type": "string"},
"description": "A list of source knowledge IDs that contributed to this page. If provided, these will COMPLETELY REPLACE the existing source_refs of the page."
}
},
"required": ["slug", "title", "summary", "content", "page_type"]
}`),
),
wikiPageService: wikiPageService,
kbIDs: kbIDs,
}
}
func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
Title string `json:"title"`
Summary string `json:"summary"`
Content string `json:"content"`
PageType string `json:"page_type"`
Aliases []string `json:"aliases"`
SourceRefs []string `json:"source_refs"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to parse arguments: " + err.Error()}, nil
}
if len(t.kbIDs) == 0 {
return &types.ToolResult{Success: false, Error: "No knowledge bases available for editing"}, nil
}
kbID := t.kbIDs[0]
if params.Title == "" || params.PageType == "" || params.Content == "" || params.Summary == "" {
return &types.ToolResult{Success: false, Error: "title, summary, content, and page_type are required for write action"}, nil
}
// Try to get the existing page
existingPage, err := t.wikiPageService.GetPageBySlug(ctx, kbID, params.Slug)
if err != nil && !errors.Is(err, repository.ErrWikiPageNotFound) {
return &types.ToolResult{Success: false, Error: "Failed to check existing page: " + err.Error()}, nil
}
var action string
if existingPage != nil {
// Update
existingPage.Title = params.Title
existingPage.Summary = params.Summary
existingPage.Content = params.Content
existingPage.PageType = params.PageType
existingPage.Aliases = params.Aliases
if len(params.SourceRefs) > 0 {
existingPage.SourceRefs = params.SourceRefs
}
_, err = t.wikiPageService.UpdatePage(ctx, existingPage)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to update page: " + err.Error()}, nil
}
action = "updated"
} else {
// Create
newPage := &types.WikiPage{
KnowledgeBaseID: kbID,
Slug: params.Slug,
Title: params.Title,
Summary: params.Summary,
Content: params.Content,
PageType: params.PageType,
Aliases: params.Aliases,
SourceRefs: params.SourceRefs,
}
_, err = t.wikiPageService.CreatePage(ctx, newPage)
if err != nil {
return &types.ToolResult{Success: false, Error: "Failed to create page: " + err.Error()}, nil
}
action = "created"
}
// Inject cross-links so other pages know about this new/updated entity
t.wikiPageService.InjectCrossLinks(ctx, kbID, []string{params.Slug})
// Rebuild the index page to reflect the new/updated summary
_ = t.wikiPageService.RebuildIndexPage(ctx, kbID)
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("Successfully %s page %s.", action, params.Slug),
}, nil
}
@@ -456,6 +456,18 @@ func (s *agentService) registerTools(
toolToRegister = tools.NewWikiReadSourceDocTool(s.knowledgeService, s.chunkService)
case tools.ToolWikiFlagIssue:
toolToRegister = tools.NewWikiFlagIssueTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiReadIssue:
toolToRegister = tools.NewWikiReadIssueTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiUpdateIssue:
toolToRegister = tools.NewWikiUpdateIssueTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiWritePage:
toolToRegister = tools.NewWikiWritePageTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiReplaceText:
toolToRegister = tools.NewWikiReplaceTextTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiRenamePage:
toolToRegister = tools.NewWikiRenamePageTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiDeletePage:
toolToRegister = tools.NewWikiDeletePageTool(s.wikiPageService, wikiKBIDs)
default:
logger.Warnf(ctx, "Unknown tool: %s", toolName)
@@ -91,13 +91,20 @@ func (s *sessionService) AgentQA(
return fmt.Errorf("failed to get chat model: %w", err)
}
// Get rerank model from custom agent config (only required when knowledge bases are configured)
// Get rerank model from custom agent config (only required when knowledge_search is allowed)
var rerankModel rerank.Reranker
hasKnowledge := len(agentConfig.KnowledgeBases) > 0 || len(agentConfig.KnowledgeIDs) > 0
if hasKnowledge {
hasKnowledgeSearchTool := false
for _, tool := range agentConfig.AllowedTools {
if tool == tools.ToolKnowledgeSearch {
hasKnowledgeSearchTool = true
break
}
}
if hasKnowledgeSearchTool {
rerankModelID := req.CustomAgent.Config.RerankModelID
if rerankModelID == "" {
logger.Warnf(ctx, "No rerank model configured for custom agent %s, but knowledge bases are specified", req.CustomAgent.ID)
logger.Warnf(ctx, "No rerank model configured for custom agent %s, but knowledge_search tool is enabled", req.CustomAgent.ID)
return errors.New("rerank model (rerank_model_id) is not configured in custom agent settings")
}
@@ -107,7 +114,7 @@ func (s *sessionService) AgentQA(
return fmt.Errorf("failed to get rerank model: %w", err)
}
} else {
logger.Infof(ctx, "No knowledge bases configured, skipping rerank model initialization")
logger.Infof(ctx, "knowledge_search tool not enabled, skipping rerank model initialization")
}
// Get or create contextManager for this session
@@ -225,6 +232,7 @@ func (s *sessionService) buildAgentConfig(
// Falls back to global configuration if no specific timeout is set for the agent.
if agentConfig.LLMCallTimeout == 0 && s.cfg.Agent != nil && s.cfg.Agent.LLMCallTimeout > 0 {
agentConfig.LLMCallTimeout = s.cfg.Agent.LLMCallTimeout
RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory,
}
// Configure skills based on CustomAgentConfig
+167
View File
@@ -288,6 +288,7 @@ func (s *wikiPageService) GetStats(ctx context.Context, kbID string) (*types.Wik
}
var pendingTasks int64
var pendingIssues int64
var isActive bool
if s.redisClient != nil {
pendingTasks, _ = s.redisClient.LLen(ctx, "wiki:pending:"+kbID).Result()
@@ -295,6 +296,9 @@ func (s *wikiPageService) GetStats(ctx context.Context, kbID string) (*types.Wik
isActive = activeFlag > 0
}
issues, _ := s.ListIssues(ctx, kbID, "", "pending")
pendingIssues = int64(len(issues))
return &types.WikiStats{
TotalPages: total,
PagesByType: counts,
@@ -302,6 +306,7 @@ func (s *wikiPageService) GetStats(ctx context.Context, kbID string) (*types.Wik
OrphanCount: orphans,
RecentUpdates: recentPages,
PendingTasks: pendingTasks,
PendingIssues: pendingIssues,
IsActive: isActive,
}, nil
}
@@ -498,3 +503,165 @@ func (s *wikiPageService) ListIssues(ctx context.Context, kbID string, slug stri
func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, issueID string, status string) error {
return s.repo.UpdateIssueStatus(ctx, issueID, status)
}
// InjectCrossLinks scans affected pages and injects [[wiki-links]] for mentions
// of other wiki page titles in the content. Pure text replacement, no LLM call.
func (s *wikiPageService) InjectCrossLinks(ctx context.Context, kbID string, affectedSlugs []string) {
// Build a title→slug lookup from ALL pages in this KB
allPages, err := s.ListAllPages(ctx, kbID)
if err != nil || len(allPages) < 2 {
return
}
type pageRef struct {
slug string
matchText string
}
var allRefs []pageRef
for _, p := range allPages {
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
continue
}
if p.Title != "" {
allRefs = append(allRefs, pageRef{slug: p.Slug, matchText: p.Title})
}
for _, alias := range p.Aliases {
if alias != "" {
allRefs = append(allRefs, pageRef{slug: p.Slug, matchText: alias})
}
}
}
if len(allRefs) == 0 {
return
}
// Sort by title length descending
for i := 0; i < len(allRefs); i++ {
for j := i + 1; j < len(allRefs); j++ {
if len([]rune(allRefs[j].matchText)) > len([]rune(allRefs[i].matchText)) {
allRefs[i], allRefs[j] = allRefs[j], allRefs[i]
}
}
}
affectedSet := make(map[string]bool, len(affectedSlugs))
for _, slug := range affectedSlugs {
affectedSet[slug] = true
}
var updated int
for _, p := range allPages {
if !affectedSet[p.Slug] {
continue
}
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
continue
}
content := p.Content
changed := false
for _, ref := range allRefs {
if ref.slug == p.Slug {
continue
}
if strings.Contains(content, "[["+ref.slug+"|") || strings.Contains(content, "[["+ref.slug+"]]") {
continue
}
if strings.Contains(content, ref.matchText) {
content = replaceFirstOutsideLinks(content, ref.matchText, "[["+ref.slug+"|"+ref.matchText+"]]")
changed = true
}
}
if changed {
p.Content = content
if _, err := s.UpdatePage(ctx, p); err != nil {
logger.Warnf(ctx, "wiki: cross-link injection failed for %s: %v", p.Slug, err)
} else {
updated++
}
}
}
if updated > 0 {
logger.Infof(ctx, "wiki: injected cross-links in %d pages", updated)
}
}
// RebuildIndexPage regenerates the index page directory.
func (s *wikiPageService) RebuildIndexPage(ctx context.Context, kbID string) error {
indexPage, err := s.GetIndex(ctx, kbID)
if err != nil {
return err
}
allPages, err := s.ListAllPages(ctx, kbID)
if err != nil {
return err
}
typeOrder := []string{
types.WikiPageTypeSummary, types.WikiPageTypeEntity, types.WikiPageTypeConcept,
types.WikiPageTypeSynthesis, types.WikiPageTypeComparison,
}
typeLabels := map[string]string{
types.WikiPageTypeSummary: "Summary", types.WikiPageTypeEntity: "Entity",
types.WikiPageTypeConcept: "Concept", types.WikiPageTypeSynthesis: "Synthesis",
types.WikiPageTypeComparison: "Comparison",
}
grouped := make(map[string][]*types.WikiPage)
totalPages := 0
for _, p := range allPages {
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
continue
}
if p.Status == types.WikiPageStatusArchived {
continue
}
grouped[p.PageType] = append(grouped[p.PageType], p)
totalPages++
}
var dir strings.Builder
for _, pt := range typeOrder {
pages := grouped[pt]
if len(pages) == 0 {
continue
}
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", typeLabels[pt], len(pages))
for _, p := range pages {
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
}
}
for pt, pages := range grouped {
inOrder := false
for _, o := range typeOrder {
if o == pt {
inOrder = true
break
}
}
if inOrder || len(pages) == 0 {
continue
}
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", pt, len(pages))
for _, p := range pages {
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
}
}
if totalPages == 0 {
dir.WriteString("\n*No wiki pages yet. Upload documents to get started.*\n")
}
intro := indexPage.Summary
if intro == "" {
intro = "# Wiki Index\n\nThis wiki contains knowledge extracted from uploaded documents.\n"
indexPage.Summary = intro
}
indexPage.Content = intro + "\n" + dir.String()
_, err = s.UpdatePage(ctx, indexPage)
return err
}
+3
View File
@@ -37,6 +37,9 @@ type AgentConfig struct {
// Whether to retrieve knowledge base only when explicitly mentioned with @ (default: false)
RetrieveKBOnlyWhenMentioned bool `json:"retrieve_kb_only_when_mentioned"`
// Whether to retain retrieval history (like wiki_read_page results) across turns (default: false)
RetainRetrievalHistory bool `json:"retain_retrieval_history"`
// Skills configuration (Progressive Disclosure pattern)
SkillsEnabled bool `json:"skills_enabled"` // Whether skills are enabled (default: false)
SkillDirs []string `json:"skill_dirs"` // Directories to search for skills
+9
View File
@@ -22,6 +22,10 @@ const (
BuiltinKnowledgeGraphExpertID = "builtin-knowledge-graph-expert"
// BuiltinDocumentAssistantID is the ID for the built-in document assistant agent
BuiltinDocumentAssistantID = "builtin-document-assistant"
// BuiltinWikiResearcherID is the ID for the built-in wiki researcher agent
BuiltinWikiResearcherID = "builtin-wiki-researcher"
// BuiltinWikiFixerID is the ID for the built-in wiki fixer agent
BuiltinWikiFixerID = "builtin-wiki-fixer"
)
// AgentMode constants for agent running mode
@@ -115,6 +119,9 @@ type CustomAgentConfig struct {
// When false, knowledge base retrieval happens according to KBSelectionMode
RetrieveKBOnlyWhenMentioned bool `yaml:"retrieve_kb_only_when_mentioned" json:"retrieve_kb_only_when_mentioned"`
// Whether to retain retrieval history across turns
RetainRetrievalHistory bool `yaml:"retain_retrieval_history" json:"retain_retrieval_history"`
// ===== Image Upload / Multimodal Settings =====
// Whether image upload is enabled for this agent (default: false)
ImageUploadEnabled bool `yaml:"image_upload_enabled" json:"image_upload_enabled"`
@@ -288,6 +295,8 @@ var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{}
var builtinAgentIDsOrdered = []string{
BuiltinQuickAnswerID,
BuiltinSmartReasoningID,
BuiltinWikiResearcherID,
BuiltinWikiFixerID,
BuiltinDeepResearcherID,
BuiltinDataAnalystID,
BuiltinKnowledgeGraphExpertID,
+7
View File
@@ -52,6 +52,13 @@ type WikiPageService interface {
// RebuildLinks re-parses all pages and rebuilds bidirectional link references.
RebuildLinks(ctx context.Context, kbID string) error
// InjectCrossLinks scans specified pages and injects [[wiki-links]] for mentions
// of other wiki page titles/aliases in the content.
InjectCrossLinks(ctx context.Context, kbID string, affectedSlugs []string)
// RebuildIndexPage regenerates the index page.
RebuildIndexPage(ctx context.Context, kbID string) error
// ListAllPages retrieves all wiki pages in a knowledge base without pagination.
// Used for index rebuild, graph generation, cross-link injection, etc.
ListAllPages(ctx context.Context, kbID string) ([]*types.WikiPage, error)
+1
View File
@@ -169,6 +169,7 @@ type WikiStats struct {
OrphanCount int64 `json:"orphan_count"` // pages with no inbound links
RecentUpdates []*WikiPage `json:"recent_updates"` // last N updated pages
PendingTasks int64 `json:"pending_tasks"` // number of documents waiting to be ingested
PendingIssues int64 `json:"pending_issues"` // number of pending wiki issues
IsActive bool `json:"is_active"` // whether wiki ingestion is currently running
}