feat(im): add slash-command system with /help, /info, /search, /stop, /clear

Introduce a pluggable command framework for IM channels. Includes
Command interface, CommandRegistry for registration and dispatch,
and five built-in commands: /help (list commands), /info (inspect
knowledge bases), /search (search knowledge), /stop (cancel running
QA), and /clear (reset conversation context).
This commit is contained in:
nullkey
2026-03-19 03:27:39 +08:00
committed by lyingbug
parent 838a49601c
commit f05f9b0e11
7 changed files with 498 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
package im
import "context"
// ClearCommand implements /clear.
// It soft-deletes the current ChannelSession and clears the LLM context so
// the next message starts a completely fresh conversation.
type ClearCommand struct{}
func newClearCommand() *ClearCommand { return &ClearCommand{} }
func (c *ClearCommand) Name() string { return "clear" }
func (c *ClearCommand) Description() string {
return "清空对话记忆,下次消息将开始全新会话"
}
func (c *ClearCommand) Execute(_ context.Context, _ *CommandContext, _ []string) (*CommandResult, error) {
return &CommandResult{
Content: "✅ 对话已清空,下次消息将开始全新会话。",
Action: ActionClear,
}, nil
}
+50
View File
@@ -0,0 +1,50 @@
package im
import (
"context"
"fmt"
"sort"
"strings"
)
// HelpCommand implements /help [command].
type HelpCommand struct {
registry *CommandRegistry
}
func newHelpCommand(registry *CommandRegistry) *HelpCommand {
return &HelpCommand{registry: registry}
}
func (c *HelpCommand) Name() string { return "help" }
func (c *HelpCommand) Description() string {
return "显示可用指令列表,或查看某个指令的详细用法"
}
func (c *HelpCommand) Execute(_ context.Context, _ *CommandContext, args []string) (*CommandResult, error) {
// /help <command> — show detailed usage for a specific command
if len(args) > 0 {
name := strings.ToLower(args[0])
cmd, _, ok := c.registry.Parse("/" + name)
if !ok {
return &CommandResult{
Content: fmt.Sprintf("未知指令 `%s`,发送 `/help` 查看所有可用指令。", args[0]),
}, nil
}
return &CommandResult{
Content: fmt.Sprintf("**/%s** — %s", cmd.Name(), cmd.Description()),
}, nil
}
// /help — list all commands sorted by name
cmds := c.registry.All()
sort.Slice(cmds, func(i, j int) bool { return cmds[i].Name() < cmds[j].Name() })
var sb strings.Builder
sb.WriteString("**可用指令**\n\n")
for _, cmd := range cmds {
sb.WriteString(fmt.Sprintf("· `/%s` — %s\n", cmd.Name(), cmd.Description()))
}
sb.WriteString("\n发送 `/help <指令名>` 查看详细用法")
return &CommandResult{Content: sb.String()}, nil
}
+132
View File
@@ -0,0 +1,132 @@
package im
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// InfoCommand implements /info.
// It shows the bound agent's profile and capabilities so IM users can
// understand what the bot can do without leaving the chat.
type InfoCommand struct {
kbService interfaces.KnowledgeBaseService
}
func newInfoCommand(kbService interfaces.KnowledgeBaseService) *InfoCommand {
return &InfoCommand{kbService: kbService}
}
func (c *InfoCommand) Name() string { return "info" }
func (c *InfoCommand) Description() string { return "查看当前智能体的信息与能力" }
func (c *InfoCommand) Execute(ctx context.Context, cmdCtx *CommandContext, _ []string) (*CommandResult, error) {
var sb strings.Builder
// Note: Feishu card markdown only renders **bold** when it occupies the
// entire inline segment. "**label:**value" on the same line will show
// raw asterisks. Always keep bold text self-contained on its own line.
// ── Header ──
name := cmdCtx.AgentName
if name == "" {
name = "未命名智能体"
}
sb.WriteString(fmt.Sprintf("🤖 **%s**\n", name))
if cmdCtx.CustomAgent != nil && cmdCtx.CustomAgent.Description != "" {
sb.WriteString(fmt.Sprintf("> %s\n", cmdCtx.CustomAgent.Description))
}
if cmdCtx.CustomAgent == nil {
sb.WriteString("\n未绑定智能体,发送 `/help` 查看可用指令。")
return &CommandResult{Content: sb.String()}, nil
}
cfg := cmdCtx.CustomAgent.Config
// ── Mode ──
if cmdCtx.CustomAgent.IsAgentMode() {
sb.WriteString("\n🧠 **Agent模式**\n")
sb.WriteString("支持多步思考、工具调用(ReAct)\n")
} else {
sb.WriteString("\n🧠 **Agent模式**\n")
sb.WriteString("基于知识库检索直接回答(RAG)\n")
}
// ── Knowledge bases ──
// KBSelectionMode: "all" uses every KB under the tenant (IDs list is empty),
// "selected" uses the explicit KnowledgeBases list, "none"/empty means disabled.
sb.WriteString("\n📚 **知识库**\n")
if cfg.KBSelectionMode == "all" {
kbs, err := c.kbService.ListKnowledgeBasesByTenantID(ctx, cmdCtx.TenantID)
if err == nil && len(kbs) > 0 {
for _, kb := range kbs {
sb.WriteString(fmt.Sprintf(" · %s\n", kb.Name))
}
sb.WriteString(fmt.Sprintf(" 共 %d 个(全部启用)\n", len(kbs)))
} else {
sb.WriteString(" 全部启用\n")
}
} else if len(cfg.KnowledgeBases) > 0 {
kbs, err := c.kbService.ListKnowledgeBasesByTenantID(ctx, cmdCtx.TenantID)
if err == nil {
nameMap := make(map[string]string, len(kbs))
for _, kb := range kbs {
nameMap[kb.ID] = kb.Name
}
for _, id := range cfg.KnowledgeBases {
label := id
if n, ok := nameMap[id]; ok {
label = n
}
sb.WriteString(fmt.Sprintf(" · %s\n", label))
}
} else {
sb.WriteString(fmt.Sprintf(" 已选择 %d 个\n", len(cfg.KnowledgeBases)))
}
} else {
sb.WriteString(" 未配置\n")
}
// ── Skills ──
sb.WriteString("\n⚡ **Skills**\n")
if cfg.SkillsSelectionMode == "all" {
sb.WriteString(" 全部启用\n")
} else if cfg.SkillsSelectionMode == "selected" && len(cfg.SelectedSkills) > 0 {
for _, s := range cfg.SelectedSkills {
sb.WriteString(fmt.Sprintf(" · %s\n", s))
}
} else {
sb.WriteString(" 未配置\n")
}
// ── MCP ──
sb.WriteString("\n🔌 **MCP 服务**\n")
if cfg.MCPSelectionMode == "all" {
sb.WriteString(" 全部接入\n")
} else if cfg.MCPSelectionMode == "selected" && len(cfg.MCPServices) > 0 {
sb.WriteString(fmt.Sprintf(" 已接入 %d 个服务\n", len(cfg.MCPServices)))
} else {
sb.WriteString(" 未配置\n")
}
// ── Web search ──
sb.WriteString("\n🌐 **网络搜索**\n")
if cfg.WebSearchEnabled {
sb.WriteString(" 已启用\n")
} else {
sb.WriteString(" 未启用\n")
}
// ── Footer ──
outputLabel := "流式输出"
if cmdCtx.ChannelOutputMode == "full" {
outputLabel = "完整输出"
}
sb.WriteString(fmt.Sprintf("\n⚙️ **输出模式**\n %s\n", outputLabel))
sb.WriteString("\n---\n发送 `/help` 查看所有可用指令")
return &CommandResult{Content: sb.String()}, nil
}
+115
View File
@@ -0,0 +1,115 @@
package im
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const (
searchMaxResults = 5
searchContentMaxLen = 200 // runes shown per result
)
// SearchCommand implements /search <query>.
//
// It runs a hybrid search (vector + keywords) against the user's selected
// knowledge bases—or the bot-level defaults when no override is active—and
// returns the raw matching passages without AI summarisation. This is useful
// when the user needs to inspect source text directly.
type SearchCommand struct {
sessionService interfaces.SessionService
kbService interfaces.KnowledgeBaseService
}
func newSearchCommand(sessionService interfaces.SessionService, kbService interfaces.KnowledgeBaseService) *SearchCommand {
return &SearchCommand{sessionService: sessionService, kbService: kbService}
}
func (c *SearchCommand) Name() string { return "search" }
func (c *SearchCommand) Description() string {
return "直接检索知识库原文(不经 AI 总结),例如:/search 退款政策"
}
func (c *SearchCommand) Execute(ctx context.Context, cmdCtx *CommandContext, args []string) (*CommandResult, error) {
if len(args) == 0 {
return &CommandResult{
Content: "请输入搜索内容,例如:`/search 退款政策`",
}, nil
}
query := strings.Join(args, " ")
// Resolve which KBs to search, mirroring the logic in the QA pipeline's
// resolveKnowledgeBasesFromAgent so that /search covers the same scope.
var kbIDs []string
if cmdCtx.CustomAgent != nil {
switch cmdCtx.CustomAgent.Config.KBSelectionMode {
case "all":
allKBs, err := c.kbService.ListKnowledgeBases(ctx)
if err == nil {
for _, kb := range allKBs {
kbIDs = append(kbIDs, kb.ID)
}
}
case "none":
// No knowledge bases configured — will return empty results.
case "selected":
kbIDs = cmdCtx.CustomAgent.Config.KnowledgeBases
default:
// Backward compatibility: fall back to configured list.
kbIDs = cmdCtx.CustomAgent.Config.KnowledgeBases
}
}
results, err := c.sessionService.SearchKnowledge(ctx, kbIDs, nil, query)
if err != nil {
return nil, fmt.Errorf("search knowledge: %w", err)
}
if len(results) == 0 {
return &CommandResult{
Content: fmt.Sprintf("未在知识库中找到与「%s」相关的内容。", query),
}, nil
}
// Cap the number of results shown in IM (wall of text is unhelpful).
shown := results
if len(shown) > searchMaxResults {
shown = shown[:searchMaxResults]
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("🔍 **搜索「%s」** — 找到 %d 条结果\n\n", query, len(results)))
for i, r := range shown {
// Trim content to a readable length.
content := []rune(r.Content)
suffix := ""
if len(content) > searchContentMaxLen {
content = content[:searchContentMaxLen]
suffix = "…"
}
// Source label: prefer title, fall back to filename.
source := r.KnowledgeTitle
if source == "" {
source = r.KnowledgeFilename
}
sb.WriteString(fmt.Sprintf("**[%d]** %s\n> %s%s\n", i+1, source, string(content), suffix))
if r.Score > 0 {
sb.WriteString(fmt.Sprintf("匹配度:%.0f%%\n", r.Score*100))
}
sb.WriteString("\n")
}
if len(results) > searchMaxResults {
sb.WriteString(fmt.Sprintf("_(仅显示前 %d 条,共 %d 条)_", searchMaxResults, len(results)))
}
return &CommandResult{Content: sb.String()}, nil
}
+21
View File
@@ -0,0 +1,21 @@
package im
import "context"
// StopCommand implements /stop.
// It cancels the in-flight QA request for the current user+chat, allowing the
// user to abort a long-running ReAct reasoning chain without waiting for it to
// complete. If no request is in progress the command simply acknowledges.
type StopCommand struct{}
func newStopCommand() *StopCommand { return &StopCommand{} }
func (c *StopCommand) Name() string { return "stop" }
func (c *StopCommand) Description() string { return "中止当前正在进行的回答" }
func (c *StopCommand) Execute(_ context.Context, _ *CommandContext, _ []string) (*CommandResult, error) {
return &CommandResult{
Content: "✅ 已请求中止当前回答。",
Action: ActionStop,
}, nil
}
+66
View File
@@ -0,0 +1,66 @@
package im
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// CommandAction represents a service-level side effect that a command requests.
// Using an enum keeps commands free of service/DB dependencies—they declare intent,
// the Service executes it.
type CommandAction int
const (
// ActionNone means no side effect beyond sending the reply.
ActionNone CommandAction = iota
// ActionClear soft-deletes the current ChannelSession and clears the LLM
// context so the next message creates a completely fresh conversation.
ActionClear
// ActionStop cancels the in-flight QA request for this user+chat.
ActionStop
)
// CommandResult is the output produced by a Command.Execute call.
type CommandResult struct {
// Content is the Markdown reply sent back to the user.
Content string
// Action requests a service-level side effect (reset, clear, …).
Action CommandAction
}
// CommandContext carries all runtime data a command needs during execution.
// Services are NOT here; inject them into command structs at construction time.
type CommandContext struct {
// Incoming is the raw IM message that triggered the command.
Incoming *IncomingMessage
// Session is the IM channel session for this user×chat combination.
Session *ChannelSession
// TenantID is the tenant that owns this bot deployment.
TenantID uint64
// AgentName is the display name of the bound agent (empty if none).
AgentName string
// CustomAgent is the bound agent configuration. Commands that need to
// inspect agent-level settings (e.g. /search reading KBSelectionMode)
// can access it directly. May be nil when no agent is bound.
CustomAgent *types.CustomAgent
// ChannelOutputMode is the channel-level output mode configured by the admin
// ("stream" or "full").
ChannelOutputMode string
}
// Command is the interface every IM slash-command must implement.
//
// Design rules:
// - Dependencies (DB, services) are injected at construction time.
// - Validation errors (bad args, entity not found) are returned as a
// CommandResult with a helpful message, NOT as an error.
// - error is reserved for infrastructure failures (DB errors, network, …).
type Command interface {
// Name is the primary token used after "/" (e.g. "kb", "mode").
Name() string
// Description is the one-line summary shown in /help output.
Description() string
// Execute runs the command and returns a reply to send to the user.
Execute(ctx context.Context, cmdCtx *CommandContext, args []string) (*CommandResult, error)
}
+92
View File
@@ -0,0 +1,92 @@
package im
import "strings"
// CommandRegistry maps slash-command names to their handlers.
type CommandRegistry struct {
commands map[string]Command
}
// NewCommandRegistry returns an empty registry.
func NewCommandRegistry() *CommandRegistry {
return &CommandRegistry{commands: make(map[string]Command)}
}
// Register adds cmd to the registry under its Name(). Panics on duplicate names
// to surface misconfiguration at startup rather than silently ignoring it.
func (r *CommandRegistry) Register(cmd Command) {
key := strings.ToLower(cmd.Name())
if _, exists := r.commands[key]; exists {
panic("im: duplicate command registration: " + key)
}
r.commands[key] = cmd
}
// Parse checks whether content is a slash-command and, if so, returns the
// matching Command and the remaining tokens as args.
//
// It returns (nil, nil, false) when:
// - content does not start with "/"
// - the first token after "/" has no registered handler
//
// Note: unrecognised slash-words are deliberately NOT matched here so that
// the caller can decide whether to treat them as unknown commands (show help)
// or pass them through to the QA pipeline (e.g. "/api/v2/users" paths).
// Use LooksLikeCommand to distinguish the two cases.
func (r *CommandRegistry) Parse(content string) (Command, []string, bool) {
content = strings.TrimSpace(content)
if !strings.HasPrefix(content, "/") {
return nil, nil, false
}
parts := strings.Fields(content[1:])
if len(parts) == 0 {
return nil, nil, false
}
name := strings.ToLower(parts[0])
cmd, ok := r.commands[name]
if !ok {
return nil, nil, false
}
return cmd, parts[1:], true
}
// IsRegistered returns true when content starts with a registered command name.
// It is cheaper than Parse because it does not allocate a result.
func (r *CommandRegistry) IsRegistered(content string) bool {
content = strings.TrimSpace(content)
if !strings.HasPrefix(content, "/") {
return false
}
parts := strings.Fields(content[1:])
if len(parts) == 0 {
return false
}
_, ok := r.commands[strings.ToLower(parts[0])]
return ok
}
// All returns every registered command.
func (r *CommandRegistry) All() []Command {
cmds := make([]Command, 0, len(r.commands))
for _, cmd := range r.commands {
cmds = append(cmds, cmd)
}
return cmds
}
// LooksLikeCommand returns true when content appears to be a command attempt—
// it starts with "/" and the first token contains no further "/" separators.
//
// This distinguishes "/help" (command attempt) from "/api/v2/users" (URL path
// that should fall through to the QA pipeline).
func LooksLikeCommand(content string) bool {
content = strings.TrimSpace(content)
if !strings.HasPrefix(content, "/") {
return false
}
parts := strings.Fields(content[1:])
if len(parts) == 0 {
return false
}
return !strings.Contains(parts[0], "/")
}