feat(commands): Session management [Phase 1/3] cross-channel command registry

This commit is contained in:
mingmxren 2026-03-03 16:08:00 +08:00
parent de2ccb5da4
commit 554aa40d09
22 changed files with 1081 additions and 34 deletions

View file

@ -338,6 +338,12 @@ Talk to your picoclaw through Telegram, Discord, WhatsApp, DingTalk, LINE, or We
picoclaw gateway
```
**4. Telegram command menu (auto-registered at startup)**
PicoClaw now keeps command definitions in one shared registry. On startup, Telegram will automatically register supported bot commands (for example `/start`, `/help`, `/show`, `/list`) so command menu and runtime behavior stay in sync.
If command registration fails (network/API transient errors), the channel still starts and PicoClaw retries registration in the background.
</details>
<details>

View file

@ -307,6 +307,12 @@ PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方
| **OneBot** | ⭐⭐ 中等 | 兼容 NapCat/Go-CQHTTP社区生态丰富 | [查看文档](docs/channels/onebot/README.zh.md) |
| **MaixCam** | ⭐ 简单 | 专为 AI 摄像头设计的硬件集成通道 | [查看文档](docs/channels/maixcam/README.zh.md) |
### Telegram 命令注册(启动时自动同步)
PicoClaw 现在使用统一的命令定义来源。启动时会自动将 Telegram 支持的命令(例如 `/start``/help``/show``/list`)注册到 Bot 命令菜单,确保菜单展示与实际行为一致。
如果注册因网络或 API 短暂异常失败,不会阻塞 channel 启动;系统会在后台自动重试。
## <img src="assets/clawdchat-icon.png" width="24" height="24" alt="ClawdChat"> 加入 Agent 社交网络
只需通过 CLI 或任何集成的聊天应用发送一条消息,即可将 PicoClaw 连接到 Agent 社交网络。

View file

@ -0,0 +1,105 @@
# Session Management + Command Stack Architecture Change (#959/#960/#961)
## Scope
This document separates architecture changes into two concerns:
- Commands path: channel adapters, agent command entry, and command package execution model.
- Session path: scope-aware indexing, active-pointer lifecycle, and persistence model.
## 1) Commands Architecture Change
### Before (upstream main)
```mermaid
flowchart LR
U["User Input"] --> TG["Telegram Adapter"]
U --> OTH["Other Channel Adapters"]
TG --> TGLOCAL["telegram_commands.go\nlocal /help /show /list"]
OTH --> AGCMD["AgentLoop.handleCommand\npartial command set"]
TG --> AGCMD
AGCMD --> AGSTATE["AgentLoop mutable state"]
class TG,TGLOCAL p_before;
class OTH,AGCMD,AGSTATE p_before;
classDef p_before fill:#F5F5F5,stroke:#8C8C8C,stroke-width:1.5px,color:#1F1F1F;
```
### After (stacked PRs)
```mermaid
flowchart LR
U2["User Input"] --> CH["Channel Adapters"]
CH --> AGENTRY["AgentLoop command entry"]
AGENTRY --> EX["commands.Executor\nhandled/passthrough"]
EX --> REG["commands.Registry\ncanonical definitions"]
EX --> HANDLERS["Builtin handlers\n/show /list /session"]
CH --> TGREG["Telegram Start()\nasync command registration"]
TGREG --> REG
class CH,TGREG,REG p959;
class EX,AGENTRY,HANDLERS p961;
classDef p959 fill:#E6F4FF,stroke:#1677FF,stroke-width:2px,color:#0B2A4A;
classDef p961 fill:#F6FFED,stroke:#52C41A,stroke-width:2px,color:#17380A;
```
### Command Impact
- Command definitions are globally visible and shared by all channels.
- Channel-specific support filtering is removed from `pkg/commands`; execution is now command-name driven.
- `/show channel` and `/list channels` remain user-visible features handled by builtin handlers.
- Telegram command menu sync still exists, but it now consumes the same canonical definitions.
## 2) Session Architecture Change
### Before (upstream main)
```mermaid
flowchart LR
ROUTE0["Routing result / inbound session key"] --> SM0["SessionManager\nflat map by sessionKey"]
SM0 --> FILES0["One JSON file per session"]
SM0 --> ACTIVE0["Active session implicit\ncaller-managed"]
class ROUTE0,SM0,FILES0,ACTIVE0 p_before;
classDef p_before fill:#F5F5F5,stroke:#8C8C8C,stroke-width:1.5px,color:#1F1F1F;
```
### After (stacked PRs)
```mermaid
flowchart LR
ROUTE1["Resolved scopeKey\n(dm/group/route)"] --> RT960["commands.Runtime\nScopeKey + SessionOps"]
RT960 --> SM1["SessionManager\nscope-aware core"]
SM1 --> IDX["index.json\nscopes.active + ordered list\npending deletes"]
SM1 --> SFILES["Session JSON payloads"]
SM1 --> OPS["ResolveActive / StartNew\nList / Resume / Prune"]
OPS --> AGHANDLER["Agent command handlers\n/new /session ..."]
class RT960,SM1,IDX,SFILES,OPS p960;
class AGHANDLER p961;
classDef p960 fill:#FFF7E6,stroke:#FA8C16,stroke-width:2px,color:#4A2A0B;
classDef p961 fill:#F6FFED,stroke:#52C41A,stroke-width:2px,color:#17380A;
```
### Session Impact
- Session lifecycle is explicitly scope-aware instead of relying on a flat key convention.
- Active session pointer and ordered history are persisted in index metadata, enabling deterministic `list/resume` behavior.
- New-session rotation and prune are first-class operations with rollback/deferred-delete safeguards.
- Agent command runtime now consumes session operations through a narrow interface, reducing coupling.
## PR Layer Mapping
- #959: shared command registry model, channel integration points, and Telegram async registration baseline.
- #960: scope-aware `SessionManager`, persistent scope index, and lifecycle operations.
- #961: centralized command execution via runtime-backed executor and agent integration.

View file

@ -2,6 +2,8 @@ package channels
import "context"
import "github.com/sipeed/picoclaw/pkg/commands"
// TypingCapable — channels that can show a typing/thinking indicator.
// StartTyping begins the indicator and returns a stop function.
// The stop function MUST be idempotent and safe to call multiple times.
@ -39,3 +41,17 @@ type PlaceholderRecorder interface {
RecordTypingStop(channel, chatID string, stop func())
RecordReactionUndo(channel, chatID string, undo func())
}
// CommandRegistrarCapable is implemented by channels that can register
// command menus with their upstream platform (e.g. Telegram BotCommand).
// Channels that do not support platform-level command menus can ignore it.
type CommandRegistrarCapable interface {
RegisterCommands(ctx context.Context, defs []commands.Definition) error
}
// CommandParserCapable is implemented by channels that expose a command
// dispatch entrypoint backed by shared command definitions/dispatcher.
// It is optional and intended for cross-channel command handling features.
type CommandParserCapable interface {
DispatchCommand(ctx context.Context, req commands.Request) commands.Result
}

View file

@ -0,0 +1,26 @@
package channels
import (
"context"
"testing"
"github.com/sipeed/picoclaw/pkg/commands"
)
type mockRegistrar struct{}
func (mockRegistrar) RegisterCommands(context.Context, []commands.Definition) error { return nil }
type mockParser struct{}
func (mockParser) DispatchCommand(context.Context, commands.Request) commands.Result {
return commands.Result{Matched: false}
}
func TestCommandRegistrarCapable_Compiles(t *testing.T) {
var _ CommandRegistrarCapable = mockRegistrar{}
}
func TestCommandParserCapable_Compiles(t *testing.T) {
var _ CommandParserCapable = mockParser{}
}

View file

@ -0,0 +1,79 @@
package telegram
import (
"context"
"time"
"github.com/mymmrac/telego"
"github.com/sipeed/picoclaw/pkg/commands"
"github.com/sipeed/picoclaw/pkg/logger"
)
var commandRegistrationBackoff = []time.Duration{
5 * time.Second,
15 * time.Second,
60 * time.Second,
5 * time.Minute,
10 * time.Minute,
}
// RegisterCommands registers bot commands on Telegram platform.
func (c *TelegramChannel) RegisterCommands(ctx context.Context, defs []commands.Definition) error {
botCommands := make([]telego.BotCommand, 0, len(defs))
for _, def := range defs {
if def.Name == "" || def.Description == "" {
continue
}
botCommands = append(botCommands, telego.BotCommand{
Command: def.Name,
Description: def.Description,
})
}
return c.bot.SetMyCommands(ctx, &telego.SetMyCommandsParams{
Commands: botCommands,
})
}
func (c *TelegramChannel) startCommandRegistration(ctx context.Context, defs []commands.Definition) {
if len(defs) == 0 {
return
}
register := c.registerFunc
if register == nil {
register = c.RegisterCommands
}
regCtx, cancel := context.WithCancel(ctx)
c.commandRegCancel = cancel
// Registration runs asynchronously so Telegram message intake is never blocked
// by temporary upstream API failures. Retry stops on success or channel shutdown.
go func() {
attempt := 0
for {
err := register(regCtx, defs)
if err == nil {
logger.InfoCF("telegram", "Telegram commands registered", map[string]any{
"count": len(defs),
})
return
}
delay := commandRegistrationBackoff[min(attempt, len(commandRegistrationBackoff)-1)]
logger.WarnCF("telegram", "Telegram command registration failed; will retry", map[string]any{
"error": err.Error(),
"retry_after": delay.String(),
})
attempt++
select {
case <-regCtx.Done():
return
case <-time.After(delay):
}
}
}()
}

View file

@ -0,0 +1,96 @@
package telegram
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/sipeed/picoclaw/pkg/commands"
)
func TestStartCommandRegistration_DoesNotBlock(t *testing.T) {
ch := &TelegramChannel{}
started := make(chan struct{}, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch.registerFunc = func(context.Context, []commands.Definition) error {
started <- struct{}{}
return errors.New("temporary failure")
}
ch.startCommandRegistration(ctx, []commands.Definition{{Name: "help"}})
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("registration did not start asynchronously")
}
}
func TestStartCommandRegistration_RetriesUntilSuccessThenStops(t *testing.T) {
ch := &TelegramChannel{}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
origBackoff := commandRegistrationBackoff
commandRegistrationBackoff = []time.Duration{5 * time.Millisecond}
defer func() { commandRegistrationBackoff = origBackoff }()
var attempts atomic.Int32
ch.registerFunc = func(context.Context, []commands.Definition) error {
n := attempts.Add(1)
if n < 3 {
return errors.New("temporary failure")
}
return nil
}
ch.startCommandRegistration(ctx, []commands.Definition{{Name: "help", Description: "Help"}})
deadline := time.Now().Add(250 * time.Millisecond)
for time.Now().Before(deadline) {
if attempts.Load() >= 3 {
break
}
time.Sleep(5 * time.Millisecond)
}
if attempts.Load() < 3 {
t.Fatalf("expected at least 3 attempts, got %d", attempts.Load())
}
stable := attempts.Load()
time.Sleep(30 * time.Millisecond)
if attempts.Load() != stable {
t.Fatalf("expected retries to stop after success, got %d -> %d", stable, attempts.Load())
}
}
func TestStartCommandRegistration_StopsAfterCancel(t *testing.T) {
ch := &TelegramChannel{}
ctx, cancel := context.WithCancel(context.Background())
origBackoff := commandRegistrationBackoff
commandRegistrationBackoff = []time.Duration{5 * time.Millisecond}
defer func() { commandRegistrationBackoff = origBackoff }()
defer cancel()
var attempts atomic.Int32
ch.registerFunc = func(context.Context, []commands.Definition) error {
attempts.Add(1)
return errors.New("always fail")
}
ch.startCommandRegistration(ctx, []commands.Definition{{Name: "help", Description: "Help"}})
time.Sleep(20 * time.Millisecond)
cancel()
time.Sleep(20 * time.Millisecond) // allow in-flight attempt to settle
stable := attempts.Load()
time.Sleep(30 * time.Millisecond)
if attempts.Load() != stable {
t.Fatalf("expected retries to quiesce after cancel, got %d -> %d", stable, attempts.Load())
}
}

View file

@ -18,6 +18,7 @@ import (
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/commands"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/identity"
"github.com/sipeed/picoclaw/pkg/logger"
@ -40,13 +41,17 @@ var (
type TelegramChannel struct {
*channels.BaseChannel
bot *telego.Bot
bh *th.BotHandler
commands TelegramCommander
config *config.Config
chatIDs map[string]int64
ctx context.Context
cancel context.CancelFunc
bot *telego.Bot
bh *th.BotHandler
commands TelegramCommander
dispatcher commands.Dispatching
config *config.Config
chatIDs map[string]int64
ctx context.Context
cancel context.CancelFunc
registerFunc func(context.Context, []commands.Definition) error
commandRegCancel context.CancelFunc
}
func NewTelegramChannel(cfg *config.Config, bus *bus.MessageBus) (*TelegramChannel, error) {
@ -90,6 +95,7 @@ func NewTelegramChannel(cfg *config.Config, bus *bus.MessageBus) (*TelegramChann
return &TelegramChannel{
BaseChannel: base,
commands: NewTelegramCommands(bot, cfg),
dispatcher: commands.NewDispatcher(commands.NewRegistry(commands.BuiltinDefinitions(cfg))),
bot: bot,
config: cfg,
chatIDs: make(map[string]int64),
@ -123,21 +129,9 @@ func (c *TelegramChannel) Start(ctx context.Context) error {
c.bh = bh
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.commands.Start(ctx, message)
}, th.CommandEqual("start"))
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.commands.Help(ctx, message)
}, th.CommandEqual("help"))
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.commands.Show(ctx, message)
}, th.CommandEqual("show"))
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
return c.commands.List(ctx, message)
}, th.CommandEqual("list"))
bh.HandleMessage(func(ctx *th.Context, message telego.Message) error {
if c.dispatchCommand(ctx, message) {
return nil
}
return c.handleMessage(ctx, &message)
}, th.AnyMessage())
@ -146,6 +140,8 @@ func (c *TelegramChannel) Start(ctx context.Context) error {
"username": c.bot.Username(),
})
c.startCommandRegistration(c.ctx, commands.NewRegistry(commands.BuiltinDefinitions(c.config)).Definitions())
go func() {
if err = bh.Start(); err != nil {
logger.ErrorCF("telegram", "Bot handler failed", map[string]any{
@ -170,6 +166,9 @@ func (c *TelegramChannel) Stop(ctx context.Context) error {
if c.cancel != nil {
c.cancel()
}
if c.commandRegCancel != nil {
c.commandRegCancel()
}
return nil
}

View file

@ -7,6 +7,7 @@ import (
"github.com/mymmrac/telego"
"github.com/sipeed/picoclaw/pkg/commands"
"github.com/sipeed/picoclaw/pkg/config"
)
@ -38,11 +39,8 @@ func commandArgs(text string) string {
}
func (c *cmd) Help(ctx context.Context, message telego.Message) error {
msg := `/start - Start the bot
/help - Show this help message
/show [model|channel] - Show current configuration
/list [models|channels] - List available options
`
defs := commands.NewRegistry(commands.BuiltinDefinitions(c.config)).Definitions()
msg := commands.FormatHelpMessage(defs)
_, err := c.bot.SendMessage(ctx, &telego.SendMessageParams{
ChatID: telego.ChatID{ID: message.Chat.ID},
Text: msg,

View file

@ -0,0 +1,58 @@
package telegram
import (
"context"
"strconv"
"github.com/mymmrac/telego"
"github.com/sipeed/picoclaw/pkg/commands"
"github.com/sipeed/picoclaw/pkg/logger"
)
func (c *TelegramChannel) DispatchCommand(ctx context.Context, req commands.Request) commands.Result {
if c.dispatcher == nil {
return commands.Result{Matched: false}
}
return c.dispatcher.Dispatch(ctx, req)
}
// dispatchCommand adapts Telegram updates to the shared dispatcher contract.
// This keeps command semantics identical across channels while preserving
// Telegram-specific reply mechanics (reply_to message id).
func (c *TelegramChannel) dispatchCommand(ctx context.Context, message telego.Message) bool {
senderID := ""
if message.From != nil {
senderID = strconv.FormatInt(message.From.ID, 10)
}
res := c.DispatchCommand(ctx, commands.Request{
Channel: "telegram",
ChatID: strconv.FormatInt(message.Chat.ID, 10),
SenderID: senderID,
Text: message.Text,
MessageID: strconv.Itoa(message.MessageID),
Reply: func(text string) error {
_, err := c.bot.SendMessage(ctx, &telego.SendMessageParams{
ChatID: telego.ChatID{ID: message.Chat.ID},
Text: text,
ReplyParameters: &telego.ReplyParameters{
MessageID: message.MessageID,
},
})
return err
},
})
if !res.Matched {
return false
}
if res.Err != nil {
logger.ErrorCF("telegram", "Command execution failed", map[string]any{
"command": res.Command,
"error": res.Err.Error(),
})
}
return true
}

View file

@ -0,0 +1,32 @@
package telegram
import (
"context"
"testing"
"github.com/mymmrac/telego"
"github.com/sipeed/picoclaw/pkg/commands"
)
func TestDispatchCommand_UsesDispatcher(t *testing.T) {
ch := &TelegramChannel{}
called := false
ch.dispatcher = commands.DispatchFunc(func(context.Context, commands.Request) commands.Result {
called = true
return commands.Result{Matched: true, Command: "noop"}
})
msg := telego.Message{
Text: "/help",
MessageID: 7,
Chat: telego.Chat{
ID: 123,
},
}
handled := ch.dispatchCommand(context.Background(), msg)
if !handled || !called {
t.Fatalf("handled=%v called=%v", handled, called)
}
}

View file

@ -11,6 +11,7 @@ import (
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/commands"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/identity"
"github.com/sipeed/picoclaw/pkg/logger"
@ -19,13 +20,14 @@ import (
type WhatsAppChannel struct {
*channels.BaseChannel
conn *websocket.Conn
config config.WhatsAppConfig
url string
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
connected bool
conn *websocket.Conn
config config.WhatsAppConfig
url string
dispatcher commands.Dispatching
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
connected bool
}
func NewWhatsAppChannel(cfg config.WhatsAppConfig, bus *bus.MessageBus) (*WhatsAppChannel, error) {
@ -42,6 +44,7 @@ func NewWhatsAppChannel(cfg config.WhatsAppConfig, bus *bus.MessageBus) (*WhatsA
BaseChannel: base,
config: cfg,
url: cfg.BridgeURL,
dispatcher: commands.NewDispatcher(commands.NewRegistry(commands.BuiltinDefinitions(nil))),
connected: false,
}, nil
}
@ -248,5 +251,39 @@ func (c *WhatsAppChannel) handleIncomingMessage(msg map[string]any) {
return
}
if c.tryHandleCommand(c.ctx, content, chatID, senderID, messageID) {
return
}
c.HandleMessage(c.ctx, peer, messageID, senderID, chatID, content, mediaPaths, metadata, sender)
}
func (c *WhatsAppChannel) tryHandleCommand(
ctx context.Context,
text, chatID, senderID, messageID string,
) bool {
res := c.DispatchCommand(ctx, commands.Request{
Channel: "whatsapp",
ChatID: chatID,
SenderID: senderID,
Text: text,
MessageID: messageID,
Reply: func(text string) error {
return c.Send(ctx, bus.OutboundMessage{ChatID: chatID, Content: text})
},
})
if res.Err != nil {
logger.WarnCF("whatsapp", "Command execution failed", map[string]any{
"command": res.Command,
"error": res.Err.Error(),
})
}
return res.Matched
}
func (c *WhatsAppChannel) DispatchCommand(ctx context.Context, req commands.Request) commands.Result {
if c.dispatcher == nil {
return commands.Result{Matched: false}
}
return c.dispatcher.Dispatch(ctx, req)
}

View file

@ -0,0 +1,34 @@
package whatsapp
import (
"context"
"testing"
"github.com/sipeed/picoclaw/pkg/commands"
)
func TestTryHandleCommand_UsesDispatcher(t *testing.T) {
ch := &WhatsAppChannel{}
called := false
ch.dispatcher = commands.DispatchFunc(func(context.Context, commands.Request) commands.Result {
called = true
return commands.Result{Matched: true, Handled: true}
})
handled := ch.tryHandleCommand(context.Background(), "/help", "chat1", "user1", "mid1")
if !handled || !called {
t.Fatalf("handled=%v called=%v", handled, called)
}
}
func TestTryHandleCommand_MatchedWithoutHandler_DoesNotFallThrough(t *testing.T) {
ch := &WhatsAppChannel{}
ch.dispatcher = commands.DispatchFunc(func(context.Context, commands.Request) commands.Result {
return commands.Result{Matched: true, Handled: false, Command: "unknown"}
})
handled := ch.tryHandleCommand(context.Background(), "/unknown", "chat1", "user1", "mid1")
if !handled {
t.Fatal("expected matched command to be treated as handled")
}
}

View file

@ -0,0 +1,36 @@
//go:build whatsapp_native
package whatsapp
import (
"context"
"testing"
"github.com/sipeed/picoclaw/pkg/commands"
)
func TestTryHandleCommand_UsesDispatcher(t *testing.T) {
ch := &WhatsAppNativeChannel{}
called := false
ch.dispatcher = commands.DispatchFunc(func(context.Context, commands.Request) commands.Result {
called = true
return commands.Result{Matched: true, Handled: true}
})
handled := ch.tryHandleCommand(context.Background(), "/help", "chat1", "user1", "mid1")
if !handled || !called {
t.Fatalf("handled=%v called=%v", handled, called)
}
}
func TestTryHandleCommand_MatchedWithoutHandler_DoesNotFallThrough(t *testing.T) {
ch := &WhatsAppNativeChannel{}
ch.dispatcher = commands.DispatchFunc(func(context.Context, commands.Request) commands.Result {
return commands.Result{Matched: true, Handled: false, Command: "unknown"}
})
handled := ch.tryHandleCommand(context.Background(), "/unknown", "chat1", "user1", "mid1")
if !handled {
t.Fatal("expected matched command to be treated as handled")
}
}

View file

@ -30,6 +30,7 @@ import (
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/commands"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/identity"
"github.com/sipeed/picoclaw/pkg/logger"
@ -55,6 +56,7 @@ type WhatsAppNativeChannel struct {
mu sync.Mutex
runCtx context.Context
runCancel context.CancelFunc
dispatcher commands.Dispatching
reconnectMu sync.Mutex
reconnecting bool
stopping atomic.Bool // set once Stop begins; prevents new wg.Add calls
@ -76,6 +78,7 @@ func NewWhatsAppNativeChannel(
BaseChannel: base,
config: cfg,
storePath: storePath,
dispatcher: commands.NewDispatcher(commands.NewRegistry(commands.BuiltinDefinitions(nil))),
}
return c, nil
}
@ -387,6 +390,9 @@ func (c *WhatsAppNativeChannel) handleIncoming(evt *events.Message) {
if !c.IsAllowedSender(sender) {
return
}
if c.tryHandleCommand(c.runCtx, content, chatID, senderID, messageID) {
return
}
logger.DebugCF(
"whatsapp",
@ -396,6 +402,36 @@ func (c *WhatsAppNativeChannel) handleIncoming(evt *events.Message) {
c.HandleMessage(c.runCtx, peer, messageID, senderID, chatID, content, mediaPaths, metadata, sender)
}
func (c *WhatsAppNativeChannel) tryHandleCommand(
ctx context.Context,
text, chatID, senderID, messageID string,
) bool {
res := c.DispatchCommand(ctx, commands.Request{
Channel: "whatsapp_native",
ChatID: chatID,
SenderID: senderID,
Text: text,
MessageID: messageID,
Reply: func(text string) error {
return c.Send(ctx, bus.OutboundMessage{ChatID: chatID, Content: text})
},
})
if res.Err != nil {
logger.WarnCF("whatsapp", "Command execution failed", map[string]any{
"command": res.Command,
"error": res.Err.Error(),
})
}
return res.Matched
}
func (c *WhatsAppNativeChannel) DispatchCommand(ctx context.Context, req commands.Request) commands.Result {
if c.dispatcher == nil {
return commands.Result{Matched: false}
}
return c.dispatcher.Dispatch(ctx, req)
}
func (c *WhatsAppNativeChannel) Send(ctx context.Context, msg bus.OutboundMessage) error {
if !c.IsRunning() {
return channels.ErrNotRunning

163
pkg/commands/builtin.go Normal file
View file

@ -0,0 +1,163 @@
package commands
import (
"context"
"fmt"
"strings"
"github.com/sipeed/picoclaw/pkg/config"
)
func BuiltinDefinitions(cfg *config.Config) []Definition {
return []Definition{
{
Name: "start",
Description: "Start the bot",
Usage: "/start",
Handler: replyText("Hello! I am PicoClaw 🦞"),
},
{
Name: "help",
Description: "Show this help message",
Usage: "/help",
Handler: func(_ context.Context, req Request) error {
if req.Reply == nil {
return nil
}
defs := NewRegistry(BuiltinDefinitions(cfg)).Definitions()
return req.Reply(FormatHelpMessage(defs))
},
},
{
Name: "show",
Description: "Show current configuration",
Usage: "/show [model|channel]",
Handler: func(_ context.Context, req Request) error {
if req.Reply == nil {
return nil
}
if cfg == nil {
return req.Reply("Command unavailable in current context.")
}
args := commandArgs(req.Text)
if args == "" {
return req.Reply("Usage: /show [model|channel]")
}
switch args {
case "model":
return req.Reply(fmt.Sprintf(
"Current Model: %s (Provider: %s)",
cfg.Agents.Defaults.GetModelName(),
cfg.Agents.Defaults.Provider,
))
case "channel":
return req.Reply(fmt.Sprintf("Current Channel: %s", req.Channel))
default:
return req.Reply(fmt.Sprintf("Unknown parameter: %s. Try 'model' or 'channel'.", args))
}
},
},
{
Name: "list",
Description: "List available options",
Usage: "/list [models|channels]",
Handler: func(_ context.Context, req Request) error {
if req.Reply == nil {
return nil
}
if cfg == nil {
return req.Reply("Command unavailable in current context.")
}
args := commandArgs(req.Text)
if args == "" {
return req.Reply("Usage: /list [models|channels]")
}
switch args {
case "models":
provider := cfg.Agents.Defaults.Provider
if provider == "" {
provider = "configured default"
}
return req.Reply(fmt.Sprintf(
"Configured Model: %s\nProvider: %s\n\nTo change models, update config.json",
cfg.Agents.Defaults.GetModelName(),
provider,
))
case "channels":
enabled := enabledChannels(cfg)
return req.Reply(fmt.Sprintf("Enabled Channels:\n- %s", strings.Join(enabled, "\n- ")))
default:
return req.Reply(fmt.Sprintf("Unknown parameter: %s. Try 'models' or 'channels'.", args))
}
},
},
}
}
func FormatHelpMessage(defs []Definition) string {
if len(defs) == 0 {
return "No commands available."
}
lines := make([]string, 0, len(defs))
for _, def := range defs {
usage := def.Usage
if usage == "" {
usage = "/" + def.Name
}
desc := def.Description
if desc == "" {
desc = "No description"
}
lines = append(lines, fmt.Sprintf("%s - %s", usage, desc))
}
return strings.Join(lines, "\n")
}
func commandArgs(text string) string {
parts := strings.SplitN(text, " ", 2)
if len(parts) < 2 {
return ""
}
return strings.TrimSpace(parts[1])
}
func replyText(text string) Handler {
return func(_ context.Context, req Request) error {
if req.Reply == nil {
return nil
}
return req.Reply(text)
}
}
func enabledChannels(cfg *config.Config) []string {
enabled := make([]string, 0, 8)
if cfg.Channels.Telegram.Enabled {
enabled = append(enabled, "telegram")
}
if cfg.Channels.WhatsApp.Enabled {
enabled = append(enabled, "whatsapp")
}
if cfg.Channels.Feishu.Enabled {
enabled = append(enabled, "feishu")
}
if cfg.Channels.Discord.Enabled {
enabled = append(enabled, "discord")
}
if cfg.Channels.Slack.Enabled {
enabled = append(enabled, "slack")
}
if cfg.Channels.DingTalk.Enabled {
enabled = append(enabled, "dingtalk")
}
if cfg.Channels.LINE.Enabled {
enabled = append(enabled, "line")
}
if cfg.Channels.OneBot.Enabled {
enabled = append(enabled, "onebot")
}
return enabled
}

View file

@ -0,0 +1,101 @@
package commands
import (
"context"
"strings"
"testing"
"github.com/sipeed/picoclaw/pkg/config"
)
func findDefinitionByName(t *testing.T, defs []Definition, name string) Definition {
t.Helper()
for _, def := range defs {
if def.Name == name {
return def
}
}
t.Fatalf("missing /%s definition", name)
return Definition{}
}
func TestBuiltinHelpHandler_ReturnsFormattedMessage(t *testing.T) {
defs := BuiltinDefinitions(nil)
helpDef := findDefinitionByName(t, defs, "help")
if helpDef.Handler == nil {
t.Fatalf("/help handler should not be nil")
}
var reply string
err := helpDef.Handler(context.Background(), Request{
Text: "/help",
Reply: func(text string) error {
reply = text
return nil
},
})
if err != nil {
t.Fatalf("/help handler error: %v", err)
}
if !strings.Contains(reply, "/show [model|channel] - Show current configuration") {
t.Fatalf("/help reply missing /show usage, got %q", reply)
}
if !strings.Contains(reply, "/list [models|channels] - List available options") {
t.Fatalf("/help reply missing /list usage, got %q", reply)
}
}
func TestBuiltinShowChannel_PreservesUserVisibleBehavior(t *testing.T) {
defs := BuiltinDefinitions(&config.Config{})
showDef := findDefinitionByName(t, defs, "show")
if showDef.Handler == nil {
t.Fatalf("/show handler should not be nil")
}
cases := []string{"telegram", "whatsapp"}
for _, channel := range cases {
var reply string
err := showDef.Handler(context.Background(), Request{
Channel: channel,
Text: "/show channel",
Reply: func(text string) error {
reply = text
return nil
},
})
if err != nil {
t.Fatalf("/show channel handler error on %s: %v", channel, err)
}
want := "Current Channel: " + channel
if reply != want {
t.Fatalf("/show channel reply=%q, want=%q", reply, want)
}
}
}
func TestBuiltinListChannels_UsesConfigEnabledChannels(t *testing.T) {
cfg := &config.Config{}
cfg.Channels.Telegram.Enabled = true
cfg.Channels.Slack.Enabled = true
defs := BuiltinDefinitions(cfg)
listDef := findDefinitionByName(t, defs, "list")
if listDef.Handler == nil {
t.Fatalf("/list handler should not be nil")
}
var reply string
err := listDef.Handler(context.Background(), Request{
Text: "/list channels",
Reply: func(text string) error {
reply = text
return nil
},
})
if err != nil {
t.Fatalf("/list channels handler error: %v", err)
}
if !strings.Contains(reply, "telegram") || !strings.Contains(reply, "slack") {
t.Fatalf("/list channels reply=%q, want telegram and slack", reply)
}
}

View file

@ -0,0 +1,16 @@
package commands
// Definition is the single-source metadata and behavior contract for a slash command.
//
// Design notes (phase 1):
// - Every channel reads command shape from this type instead of keeping local copies.
// - Visibility is global: all definitions are considered available to all channels.
// - Platform menu registration (for example Telegram BotCommand) also derives from this
// same definition so UI labels and runtime behavior stay aligned.
type Definition struct {
Name string
Description string
Usage string
Aliases []string
Handler Handler
}

101
pkg/commands/dispatcher.go Normal file
View file

@ -0,0 +1,101 @@
package commands
import (
"context"
"strings"
)
type Handler func(ctx context.Context, req Request) error
type Request struct {
Channel string
ChatID string
SenderID string
Text string
MessageID string
Reply func(text string) error
}
type Result struct {
Matched bool
Handled bool
Command string
Err error
}
type Dispatcher struct {
reg *Registry
}
type Dispatching interface {
Dispatch(ctx context.Context, req Request) Result
}
type DispatchFunc func(ctx context.Context, req Request) Result
func (f DispatchFunc) Dispatch(ctx context.Context, req Request) Result {
return f(ctx, req)
}
// NewDispatcher binds the unified parser/executor flow to one command registry.
func NewDispatcher(reg *Registry) *Dispatcher {
return &Dispatcher{reg: reg}
}
// Dispatch parses slash commands and executes handlers from the shared registry.
// Unmatched messages intentionally return Matched=false so callers can fall back
// to normal agent message handling.
func (d *Dispatcher) Dispatch(ctx context.Context, req Request) Result {
cmdName, ok := parseCommandName(req.Text)
if !ok {
return Result{Matched: false}
}
for _, def := range d.reg.Definitions() {
if def.Name != cmdName && !contains(def.Aliases, cmdName) {
continue
}
if def.Handler == nil {
return Result{Matched: true, Handled: false, Command: def.Name}
}
err := def.Handler(ctx, req)
return Result{Matched: true, Handled: true, Command: def.Name, Err: err}
}
return Result{Matched: false}
}
func firstToken(input string) string {
parts := strings.Fields(strings.TrimSpace(input))
if len(parts) == 0 {
return ""
}
return parts[0]
}
// parseCommandName accepts both "/name" and "/name@bot", then normalizes to "name".
func parseCommandName(input string) (string, bool) {
token := firstToken(input)
if token == "" || !strings.HasPrefix(token, "/") {
return "", false
}
name := strings.TrimPrefix(token, "/")
if i := strings.Index(name, "@"); i >= 0 {
name = name[:i]
}
name = strings.TrimSpace(name)
if name == "" {
return "", false
}
return name, true
}
func contains(items []string, target string) bool {
for _, item := range items {
if item == target {
return true
}
}
return false
}

View file

@ -0,0 +1,61 @@
package commands
import (
"context"
"testing"
)
func TestDispatcher_MatchSlashCommand(t *testing.T) {
called := false
defs := []Definition{
{
Name: "help",
Handler: func(context.Context, Request) error {
called = true
return nil
},
},
}
d := NewDispatcher(NewRegistry(defs))
res := d.Dispatch(context.Background(), Request{
Channel: "telegram",
Text: "/help",
})
if !res.Matched || !called || res.Err != nil {
t.Fatalf("dispatch result = %+v, called=%v", res, called)
}
}
func TestDispatcher_DoesNotMatchWithoutSlash(t *testing.T) {
d := NewDispatcher(NewRegistry([]Definition{{Name: "help"}}))
res := d.Dispatch(context.Background(), Request{
Channel: "telegram",
Text: "help",
})
if res.Matched {
t.Fatalf("expected unmatched for plain text, got %+v", res)
}
}
func TestDispatcher_MatchTelegramMentionSyntax(t *testing.T) {
called := false
d := NewDispatcher(NewRegistry([]Definition{
{
Name: "help",
Handler: func(context.Context, Request) error {
called = true
return nil
},
},
}))
res := d.Dispatch(context.Background(), Request{
Channel: "telegram",
Text: "/help@my_bot",
})
if !res.Matched || !res.Handled || !called || res.Err != nil {
t.Fatalf("dispatch result = %+v, called=%v", res, called)
}
}

19
pkg/commands/registry.go Normal file
View file

@ -0,0 +1,19 @@
package commands
type Registry struct {
defs []Definition
}
// NewRegistry stores the canonical command set used by both dispatch and
// optional platform registration adapters.
func NewRegistry(defs []Definition) *Registry {
return &Registry{defs: defs}
}
// Definitions returns all registered command definitions.
// Command availability is global and no longer channel-scoped.
func (r *Registry) Definitions() []Definition {
out := make([]Definition, len(r.defs))
copy(out, r.defs)
return out
}

View file

@ -0,0 +1,22 @@
package commands
import "testing"
func TestRegistry_Definitions_ReturnsCopy(t *testing.T) {
defs := []Definition{
{Name: "help", Description: "Show help"},
{Name: "admin", Description: "Admin command"},
}
r := NewRegistry(defs)
got := r.Definitions()
if len(got) != 2 {
t.Fatalf("definitions len = %d, want 2", len(got))
}
got[0].Name = "mutated"
again := r.Definitions()
if again[0].Name != "help" {
t.Fatalf("registry should not be mutated by caller, got first name %q", again[0].Name)
}
}