refactor: remove Pico and MaixCAM channels

Remove pico, pico_client and maixcam adapters, configuration and migration support.
Drop Pico-specific agent publishing while preserving shared IM streaming and MQTT.
Clean up channel examples and localized documentation; move shared tests to Telegram.
Validated with full Go tests, vet, lint, docs checks and a Linux amd64 build.
This commit is contained in:
loveuer committed 2026-11-11 19:02:03 +08:00
1 parent 6159157e47
commit 996dfefffe
74 files changed
+243 -5862

No files matched your search

+1 -4
View File
@@ -103,7 +103,7 @@ type processOptions struct {
DefaultResponse string // Response when LLM returns empty
EnableSummary bool // Whether to trigger summarization
SendResponse bool // Whether to send response via bus
AllowInterimPicoPublish bool // Whether pico tool-call interim text can be published when SendResponse is false
AllowStreaming bool // Whether streaming output is allowed when SendResponse is false
SuppressToolFeedback bool // Whether to suppress inline tool feedback messages
NoHistory bool // If true, don't load session history (for heartbeat)
SkipInitialSteeringPoll bool // If true, skip the steering poll at loop start (used by Continue)
@@ -126,11 +126,8 @@ const (
pendingTurnPrefix = "pending-"
providerReloadGracePeriod = 30 * time.Second
metadataKeyMessageKind = "message_kind"
metadataKeyToolCalls = "tool_calls"
metadataKeyOutboundKind = "outbound_kind"
messageKindThought = "thought"
messageKindToolFeedback = "tool_feedback"
messageKindToolCalls = "tool_calls"
outboundKindFinal = "final"
outboundKindCommandReply = "command_reply"
metadataKeyAccountID = "account_id"
+6 -6
View File
@@ -186,12 +186,12 @@ func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage)
UserMessage: msg.Content,
Media: append([]string(nil), msg.Media...),
},
SenderID: msg.SenderID,
SenderDisplayName: msg.Sender.DisplayName,
DefaultResponse: defaultResponse,
EnableSummary: true,
SendResponse: false,
AllowInterimPicoPublish: true,
SenderID: msg.SenderID,
SenderDisplayName: msg.Sender.DisplayName,
DefaultResponse: defaultResponse,
EnableSummary: true,
SendResponse: false,
AllowStreaming: true,
}
var err error
opts, err = resolveTurnProfileOptions(al.GetConfig(), opts)
-152
View File
@@ -4,16 +4,12 @@ package agent
import (
"context"
"encoding/json"
"errors"
"strings"
"time"
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/logger"
"github.com/sipeed/picoclaw/pkg/providers"
"github.com/sipeed/picoclaw/pkg/tools"
"github.com/sipeed/picoclaw/pkg/utils"
)
func (al *AgentLoop) maybePublishError(ctx context.Context, channel, chatID, sessionKey string, err error) bool {
@@ -101,154 +97,6 @@ func (al *AgentLoop) targetReasoningChannelID(channelName string) (chatID string
return ""
}
func (al *AgentLoop) publishPicoReasoning(
ctx context.Context,
reasoningContent, chatID, sessionKey, modelName string,
) {
if reasoningContent == "" || chatID == "" {
return
}
if ctx.Err() != nil {
return
}
pubCtx, pubCancel := context.WithTimeout(ctx, 5*time.Second)
defer pubCancel()
raw := map[string]string{metadataKeyMessageKind: messageKindThought}
if trimmedModelName := strings.TrimSpace(modelName); trimmedModelName != "" {
raw["model_name"] = trimmedModelName
}
if err := al.bus.PublishOutbound(pubCtx, bus.OutboundMessage{
Context: bus.InboundContext{
Channel: "pico",
ChatID: chatID,
Raw: raw,
},
SessionKey: sessionKey,
Content: reasoningContent,
}); err != nil {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) ||
errors.Is(err, bus.ErrBusClosed) {
logger.DebugCF("agent", "Pico reasoning publish skipped (timeout/cancel)", map[string]any{
"channel": "pico",
"error": err.Error(),
})
} else {
logger.WarnCF("agent", "Failed to publish pico reasoning (best-effort)", map[string]any{
"channel": "pico",
"error": err.Error(),
})
}
}
}
func (al *AgentLoop) publishPicoToolCallInterim(
ctx context.Context,
ts *turnState,
modelName string,
reasoningContent string,
content string,
toolCalls []providers.ToolCall,
) {
if ts == nil || ts.chatID == "" || al == nil || al.bus == nil {
return
}
if strings.TrimSpace(reasoningContent) != "" {
pubCtx, pubCancel := context.WithTimeout(ctx, 3*time.Second)
err := al.bus.PublishOutbound(
pubCtx,
outboundMessageForTurnWithOptions(
ts,
reasoningContent,
outboundTurnMessageOptions{
kind: messageKindThought,
modelName: modelName,
},
),
)
pubCancel()
if err != nil && !errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, context.Canceled) &&
!errors.Is(err, bus.ErrBusClosed) {
logger.WarnCF("agent", "Failed to publish pico reasoning", map[string]any{
"channel": ts.channel,
"chat_id": ts.chatID,
"error": err.Error(),
})
}
}
if !ts.opts.AllowInterimPicoPublish {
return
}
visibleToolCalls := utils.BuildVisibleToolCalls(
toolCalls,
al.cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength(),
)
duplicateToolCallContent := len(visibleToolCalls) > 0 &&
utils.ToolCallExplanationDuplicatesContent(content, toolCalls)
if strings.TrimSpace(content) != "" && !duplicateToolCallContent {
pubCtx, pubCancel := context.WithTimeout(ctx, 3*time.Second)
err := al.bus.PublishOutbound(
pubCtx,
outboundMessageForTurnWithOptions(ts, content, outboundTurnMessageOptions{
modelName: modelName,
}),
)
pubCancel()
if err != nil && !errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, context.Canceled) &&
!errors.Is(err, bus.ErrBusClosed) {
logger.WarnCF("agent", "Failed to publish pico interim assistant content", map[string]any{
"channel": ts.channel,
"chat_id": ts.chatID,
"error": err.Error(),
})
}
}
if len(visibleToolCalls) == 0 {
return
}
rawToolCalls, err := json.Marshal(visibleToolCalls)
if err != nil {
logger.WarnCF("agent", "Failed to serialize pico tool calls", map[string]any{
"channel": ts.channel,
"chat_id": ts.chatID,
"error": err.Error(),
})
return
}
msg := outboundMessageForTurnWithOptions(ts, "", outboundTurnMessageOptions{
kind: messageKindToolCalls,
modelName: modelName,
raw: map[string]string{
metadataKeyToolCalls: string(rawToolCalls),
},
})
pubCtx, pubCancel := context.WithTimeout(ctx, 3*time.Second)
err = al.bus.PublishOutbound(pubCtx, msg)
pubCancel()
if err != nil && !errors.Is(err, context.DeadlineExceeded) &&
!errors.Is(err, context.Canceled) &&
!errors.Is(err, bus.ErrBusClosed) {
logger.WarnCF("agent", "Failed to publish pico tool calls", map[string]any{
"channel": ts.channel,
"chat_id": ts.chatID,
"error": err.Error(),
})
}
}
func (al *AgentLoop) handleReasoning(
ctx context.Context,
reasoningContent, channelName, channelID string,
+23 -391
View File
@@ -453,7 +453,7 @@ func TestPublishResponseIfNeeded_MarksFinalOutbound(t *testing.T) {
defer cleanup()
_ = provider
al.PublishResponseIfNeeded(context.Background(), "pico", "pico:session-1", "session-1", "final reply")
al.PublishResponseIfNeeded(context.Background(), "telegram", "telegram:session-1", "session-1", "final reply")
select {
case outbound := <-msgBus.OutboundChan():
@@ -471,32 +471,6 @@ func TestPublishResponseIfNeeded_MarksFinalOutbound(t *testing.T) {
}
}
func TestPublishPicoReasoningIncludesSessionKey(t *testing.T) {
al, _, msgBus, provider, cleanup := newTestAgentLoop(t)
defer cleanup()
_ = provider
al.publishPicoReasoning(context.Background(), "reasoning", "pico-chat", "session-1", "")
select {
case outbound := <-msgBus.OutboundChan():
if outbound.Channel != "pico" || outbound.ChatID != "pico-chat" {
t.Fatalf("unexpected outbound target: %+v", outbound)
}
if outbound.Content != "reasoning" {
t.Fatalf("outbound content = %q, want reasoning", outbound.Content)
}
if outbound.SessionKey != "session-1" {
t.Fatalf("outbound session key = %q, want session-1", outbound.SessionKey)
}
if outbound.Context.Raw[metadataKeyMessageKind] != messageKindThought {
t.Fatalf("message kind = %q, want %q", outbound.Context.Raw[metadataKeyMessageKind], messageKindThought)
}
case <-time.After(time.Second):
t.Fatal("expected pico reasoning outbound")
}
}
func TestProcessMessage_IncludesCurrentSenderInDynamicContext(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "agent-test-*")
if err != nil {
@@ -566,7 +540,7 @@ func TestProcessMessage_DoesNotPassImplicitThinkingOffToCapableProvider(t *testi
al := NewAgentLoop(cfg, bus.NewMessageBus(), provider)
response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
ChatID: "chat-1",
Content: "hello",
}))
@@ -602,7 +576,7 @@ func TestProcessMessage_PassesExplicitThinkingOffToCapableProvider(t *testing.T)
al := NewAgentLoop(cfg, bus.NewMessageBus(), provider)
response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
ChatID: "chat-1",
Content: "hello",
}))
@@ -638,7 +612,7 @@ func TestProcessMessage_PassesExplicitThinkingOffToProviderWithoutThinkingCapabi
al := NewAgentLoop(cfg, bus.NewMessageBus(), provider)
response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
ChatID: "chat-1",
Content: "hello",
}))
@@ -675,7 +649,7 @@ func TestProcessMessage_PassesDeepSeekThinkingLevelToThinkingCapableProvider(t *
al := NewAgentLoop(cfg, bus.NewMessageBus(), provider)
response, err := al.processMessage(context.Background(), testInboundMessage(bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
ChatID: "chat-1",
Content: "hello",
}))
@@ -714,8 +688,8 @@ func TestProcessMessage_SuppressesReasoningWhenThinkingOff(t *testing.T) {
context.Background(),
al.GetRegistry().GetDefaultAgent(),
processOptions{
SessionKey: "agent:main:pico:chat-1",
Channel: "pico",
SessionKey: "agent:main:telegram:chat-1",
Channel: "telegram",
ChatID: "chat-1",
UserMessage: "hello",
SendResponse: false,
@@ -767,9 +741,9 @@ func TestProcessMessage_BeforeLLMModelRewriteReevaluatesThinkingOff(t *testing.T
}
response, err := al.processMessage(context.Background(), bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
SenderID: "user1",
ChatID: "pico:test-session",
ChatID: "telegram:test-session",
Content: "hello",
})
if err != nil {
@@ -814,14 +788,21 @@ func TestProcessMessage_BeforeLLMModelRewriteDoesNotLeakThinkingOff(t *testing.T
msgBus := bus.NewMessageBus()
provider := &reasoningOptionRecordingProvider{}
al := NewAgentLoop(cfg, msgBus, provider)
chManager, err := channels.NewManager(&config.Config{}, msgBus, nil)
if err != nil {
t.Fatalf("Failed to create channel manager: %v", err)
}
chManager.RegisterChannel("telegram", &fakeChannel{id: "reason-chat"})
al.SetChannelManager(chManager)
if err := al.MountHook(NamedHook("rewrite-model", modelRewriteHook{model: "plain-model"})); err != nil {
t.Fatalf("MountHook failed: %v", err)
}
response, err := al.processMessage(context.Background(), bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
SenderID: "user1",
ChatID: "pico:test-session",
ChatID: "telegram:test-session",
Content: "hello",
})
if err != nil {
@@ -2835,77 +2816,6 @@ func TestToolFeedbackArgsPreview_UsesJSONAndTruncates(t *testing.T) {
}
}
type picoInterleavedContentProvider struct {
calls int
}
func (m *picoInterleavedContentProvider) Chat(
ctx context.Context,
messages []providers.Message,
tools []providers.ToolDefinition,
model string,
opts map[string]any,
) (*providers.LLMResponse, error) {
m.calls++
if m.calls == 1 {
return &providers.LLMResponse{
Content: "intermediate model text",
ToolCalls: []providers.ToolCall{{
ID: "call_tool_limit_test",
Type: "function",
Name: "tool_limit_test_tool",
Arguments: map[string]any{"value": "x"},
}},
}, nil
}
return &providers.LLMResponse{
Content: "final model text",
ToolCalls: []providers.ToolCall{},
}, nil
}
func (m *picoInterleavedContentProvider) GetDefaultModel() string {
return "pico-interleaved-content-model"
}
type picoDistinctToolCallContentProvider struct {
calls int
}
func (m *picoDistinctToolCallContentProvider) Chat(
ctx context.Context,
messages []providers.Message,
tools []providers.ToolDefinition,
model string,
opts map[string]any,
) (*providers.LLMResponse, error) {
m.calls++
if m.calls == 1 {
return &providers.LLMResponse{
Content: "intermediate model text",
ToolCalls: []providers.ToolCall{{
ID: "call_tool_limit_test",
Type: "function",
Name: "tool_limit_test_tool",
Arguments: map[string]any{"value": "x"},
ExtraContent: &providers.ExtraContent{
ToolFeedbackExplanation: "Read the file before replying.",
},
}},
}, nil
}
return &providers.LLMResponse{
Content: "final model text",
ToolCalls: []providers.ToolCall{},
}, nil
}
func (m *picoDistinctToolCallContentProvider) GetDefaultModel() string {
return "pico-distinct-tool-call-content-model"
}
type toolLimitOnlyProvider struct{}
func (m *toolLimitOnlyProvider) Chat(
@@ -5623,7 +5533,7 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) {
"telegram": "rid-telegram",
"feishu": "rid-feishu",
"discord": "rid-discord",
"maixcam": "rid-maixcam",
"mqtt": "rid-mqtt",
"qq": "rid-qq",
"dingtalk": "rid-dingtalk",
"slack": "rid-slack",
@@ -5642,7 +5552,7 @@ func TestTargetReasoningChannelID_AllChannels(t *testing.T) {
{channel: "telegram", wantID: "rid-telegram"},
{channel: "feishu", wantID: "rid-feishu"},
{channel: "discord", wantID: "rid-discord"},
{channel: "maixcam", wantID: "rid-maixcam"},
{channel: "mqtt", wantID: "rid-mqtt"},
{channel: "qq", wantID: "rid-qq"},
{channel: "dingtalk", wantID: "rid-dingtalk"},
{channel: "slack", wantID: "rid-slack"},
@@ -5892,66 +5802,6 @@ func TestProcessMessage_PublishesReasoningContentToReasoningChannel(t *testing.T
}
}
func TestProcessMessage_PicoPublishesReasoningAsThoughtMessage(t *testing.T) {
tmpDir := t.TempDir()
cfg := &config.Config{
Agents: config.AgentsConfig{
Defaults: config.AgentDefaults{
Workspace: tmpDir,
ModelName: "test-model",
MaxTokens: 4096,
MaxToolIterations: 10,
},
},
}
msgBus := bus.NewMessageBus()
provider := &reasoningContentProvider{
response: "final answer",
reasoningContent: "thinking trace",
}
al := NewAgentLoop(cfg, msgBus, provider)
response, err := al.processMessage(context.Background(), bus.InboundMessage{
Channel: "pico",
SenderID: "user1",
ChatID: "pico:test-session",
Content: "hello",
})
if err != nil {
t.Fatalf("processMessage() error = %v", err)
}
if response != "final answer" {
t.Fatalf("processMessage() response = %q, want %q", response, "final answer")
}
var thoughtMsg *bus.OutboundMessage
deadline := time.After(3 * time.Second)
for thoughtMsg == nil {
select {
case outbound := <-msgBus.OutboundChan():
msg := outbound
if msg.Content == "thinking trace" {
thoughtMsg = &msg
}
case <-deadline:
t.Fatal("expected thought outbound message for pico")
}
}
if thoughtMsg.Channel != "pico" || thoughtMsg.ChatID != "pico:test-session" {
t.Fatalf("thought message route = %s/%s, want pico/pico:test-session", thoughtMsg.Channel, thoughtMsg.ChatID)
}
if thoughtMsg.Context.Raw[metadataKeyMessageKind] != messageKindThought {
t.Fatalf(
"thought metadata kind = %q, want %q",
thoughtMsg.Context.Raw[metadataKeyMessageKind],
messageKindThought,
)
}
}
func TestProcessHeartbeat_DoesNotPublishToolFeedback(t *testing.T) {
tmpDir := t.TempDir()
heartbeatFile := filepath.Join(tmpDir, "heartbeat-task.txt")
@@ -6107,9 +5957,9 @@ func TestProcessMessage_PersistsReasoningContentInSessionHistory(t *testing.T) {
al := NewAgentLoop(cfg, msgBus, provider)
response, err := al.processMessage(context.Background(), bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
SenderID: "user1",
ChatID: "pico:test-session",
ChatID: "telegram:test-session",
Content: "hello",
})
if err != nil {
@@ -6440,224 +6290,6 @@ func TestProcessMessage_MessageToolPublishesOutboundWithTurnMetadata(t *testing.
}
}
func TestRun_PicoPublishesAssistantContentDuringToolCallsWithoutFinalDuplicate(t *testing.T) {
tmpDir := t.TempDir()
cfg := &config.Config{
Agents: config.AgentsConfig{
Defaults: config.AgentDefaults{
Workspace: tmpDir,
ModelName: "test-model",
MaxTokens: 4096,
MaxToolIterations: 10,
},
},
}
msgBus := bus.NewMessageBus()
provider := &picoDistinctToolCallContentProvider{}
al := NewAgentLoop(cfg, msgBus, provider)
agent := al.GetRegistry().GetDefaultAgent()
if agent == nil {
t.Fatal("expected default agent")
}
agent.Tools.Register(&toolLimitTestTool{})
runCtx, runCancel := context.WithCancel(context.Background())
defer runCancel()
runDone := make(chan error, 1)
go func() {
runDone <- al.Run(runCtx)
}()
if err := msgBus.PublishInbound(context.Background(), bus.InboundMessage{
Channel: "pico",
SenderID: "user-1",
ChatID: "session-1",
Content: "run with tools",
}); err != nil {
t.Fatalf("PublishInbound() error = %v", err)
}
outputs := make([]bus.OutboundMessage, 0, 3)
deadline := time.After(2 * time.Second)
for len(outputs) < 3 {
select {
case outbound := <-msgBus.OutboundChan():
outputs = append(outputs, outbound)
case <-deadline:
t.Fatalf("timed out waiting for pico outputs, got %v", outputs)
}
}
if outputs[0].Content != "intermediate model text" {
t.Fatalf("first outbound content = %q, want %q", outputs[0].Content, "intermediate model text")
}
if outputs[1].Context.Raw[metadataKeyMessageKind] != messageKindToolCalls {
t.Fatalf("second outbound = %+v, want tool_calls message", outputs[1])
}
if !strings.Contains(outputs[1].Context.Raw[metadataKeyToolCalls], "tool_limit_test_tool") {
t.Fatalf("second outbound tool_calls = %q, want tool name", outputs[1].Context.Raw[metadataKeyToolCalls])
}
if outputs[2].Content != "final model text" {
t.Fatalf("third outbound content = %q, want %q", outputs[2].Content, "final model text")
}
runCancel()
select {
case err := <-runDone:
if err != nil {
t.Fatalf("Run() error = %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for Run() to exit")
}
select {
case outbound := <-msgBus.OutboundChan():
if outbound.Content == "final model text" {
t.Fatalf("unexpected duplicate final pico output: %+v", outbound)
}
case <-time.After(200 * time.Millisecond):
}
}
func TestRunAgentLoop_PicoSkipsInterimPublishWhenNotAllowed(t *testing.T) {
tmpDir := t.TempDir()
cfg := &config.Config{
Agents: config.AgentsConfig{
Defaults: config.AgentDefaults{
Workspace: tmpDir,
ModelName: "test-model",
MaxTokens: 4096,
MaxToolIterations: 10,
},
},
}
msgBus := bus.NewMessageBus()
provider := &picoInterleavedContentProvider{}
al := NewAgentLoop(cfg, msgBus, provider)
agent := al.GetRegistry().GetDefaultAgent()
if agent == nil {
t.Fatal("expected default agent")
}
agent.Tools.Register(&toolLimitTestTool{})
response, err := al.runAgentLoop(context.Background(), agent, processOptions{
SessionKey: "agent:main:pico:session-1",
Channel: "pico",
ChatID: "session-1",
UserMessage: "run with tools",
DefaultResponse: defaultResponse,
EnableSummary: false,
SendResponse: false,
AllowInterimPicoPublish: false,
SuppressToolFeedback: true,
})
if err != nil {
t.Fatalf("runAgentLoop() error = %v", err)
}
if response != "final model text" {
t.Fatalf("runAgentLoop() response = %q, want %q", response, "final model text")
}
select {
case outbound := <-msgBus.OutboundChan():
t.Fatalf("unexpected outbound message when interim publish disabled: %+v", outbound)
case <-time.After(200 * time.Millisecond):
}
}
func TestRun_PicoToolFeedbackSuppressesDuplicateInterimAssistantContent(t *testing.T) {
tmpDir := t.TempDir()
cfg := &config.Config{
Agents: config.AgentsConfig{
Defaults: config.AgentDefaults{
Workspace: tmpDir,
ModelName: "test-model",
MaxTokens: 4096,
MaxToolIterations: 10,
ToolFeedback: config.ToolFeedbackConfig{
Enabled: true,
},
},
},
}
msgBus := bus.NewMessageBus()
provider := &picoInterleavedContentProvider{}
al := NewAgentLoop(cfg, msgBus, provider)
agent := al.GetRegistry().GetDefaultAgent()
if agent == nil {
t.Fatal("expected default agent")
}
agent.Tools.Register(&toolLimitTestTool{})
runCtx, runCancel := context.WithCancel(context.Background())
defer runCancel()
runDone := make(chan error, 1)
go func() {
runDone <- al.Run(runCtx)
}()
if err := msgBus.PublishInbound(context.Background(), bus.InboundMessage{
Channel: "pico",
SenderID: "user-1",
ChatID: "session-1",
Content: "run with tools",
}); err != nil {
t.Fatalf("PublishInbound() error = %v", err)
}
outputs := make([]bus.OutboundMessage, 0, 3)
deadline := time.After(2 * time.Second)
for len(outputs) < 2 {
select {
case outbound := <-msgBus.OutboundChan():
outputs = append(outputs, outbound)
case <-deadline:
t.Fatalf("timed out waiting for pico outputs, got %v", outputs)
}
}
if outputs[0].Context.Raw[metadataKeyMessageKind] != messageKindToolCalls {
t.Fatalf("first outbound = %+v, want tool_calls message", outputs[0])
}
if outputs[0].Content != "" {
t.Fatalf("first outbound content = %q, want empty tool_calls content", outputs[0].Content)
}
if !strings.Contains(outputs[0].Context.Raw[metadataKeyToolCalls], "tool_limit_test_tool") {
t.Fatalf("first outbound tool_calls = %q, want tool name", outputs[0].Context.Raw[metadataKeyToolCalls])
}
if outputs[1].Content != "final model text" {
t.Fatalf("second outbound content = %q, want %q", outputs[1].Content, "final model text")
}
runCancel()
select {
case err := <-runDone:
if err != nil {
t.Fatalf("Run() error = %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for Run() to exit")
}
select {
case outbound := <-msgBus.OutboundChan():
t.Fatalf("unexpected extra pico output after tool feedback + final reply: %+v", outbound)
case <-time.After(200 * time.Millisecond):
}
}
func TestResolveMediaRefs_ImageInjectsPathTag(t *testing.T) {
store := media.NewFileMediaStore()
dir := t.TempDir()
@@ -7330,7 +6962,7 @@ func TestProcessMessage_NativeSearchHandlesHookClearingOptions(t *testing.T) {
}
response, err := al.processMessage(context.Background(), bus.InboundMessage{
Channel: "pico",
Channel: "telegram",
ChatID: "native-search-hook",
Content: "search",
})
+1 -1
View File
@@ -717,7 +717,7 @@ func TestBuildMessages_IncludesMediaOnlyCurrentMessage(t *testing.T) {
"",
"",
[]string{"data:image/png;base64,abc123"},
"pico",
"telegram",
"chat-1",
"",
"",
+2 -2
View File
@@ -197,7 +197,7 @@ toolLoop:
},
)
if shouldPublishToolFeedback(al.cfg, ts) && ts.channel != "pico" {
if shouldPublishToolFeedback(al.cfg, ts) {
toolFeedbackMaxLen := al.cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength()
toolFeedbackExplanation := toolFeedbackExplanationForToolCall(
exec.response,
@@ -489,7 +489,7 @@ toolLoop:
},
)
if shouldPublishToolFeedback(al.cfg, ts) && ts.channel != "pico" {
if shouldPublishToolFeedback(al.cfg, ts) {
toolFeedbackMaxLen := al.cfg.Agents.Defaults.GetToolFeedbackMaxArgsLength()
toolFeedbackExplanation := toolFeedbackExplanationForToolCall(
exec.response,
+2 -2
View File
@@ -78,10 +78,10 @@ func (p *Pipeline) Finalize(
contextUsage := computeContextUsage(ts.agent, ts.sessionKey)
streamErr := finalizeConfiguredStreamingLLM(turnCtx, ts, exec, finalContent, contextUsage)
// If streaming never became visible, keep the legacy Pico interim publish path
// If streaming never became visible, publish the fallback answer
// so the final answer is still delivered outside normal SendResponse.
if ((streamErr != nil && !isConfiguredStreamingVisibleError(streamErr)) || exec.streamingFallback) &&
!ts.opts.SendResponse && ts.opts.AllowInterimPicoPublish && finalContent != "" {
!ts.opts.SendResponse && ts.opts.AllowStreaming && finalContent != "" {
msg := outboundMessageForTurnWithOptions(ts, finalContent, outboundTurnMessageOptions{
modelName: exec.llmModelName,
})
+7 -38
View File
@@ -551,33 +551,12 @@ func (p *Pipeline) CallLLM(
exec.response.ReasoningDetails = nil
}
reasoningContent := responseReasoningContent(exec.response)
shouldPublishPicoToolCallInterim := ts.channel == "pico" && len(exec.response.ToolCalls) > 0
if shouldPublishPicoToolCallInterim {
// Pico tool-call turns publish their reasoning/content/tool summary as a
// structured sequence after the tool-call payload is normalized below.
} else if ts.channel == "pico" {
if exec.streamingPublisher != nil && exec.streamingPublisher.ReasoningPublished() {
if err := exec.streamingPublisher.FinalizeReasoning(turnCtx, reasoningContent); err != nil {
logger.WarnCF("agent", "Failed to finalize streamed pico reasoning", map[string]any{
"channel": ts.channel,
"chat_id": ts.chatID,
"error": err.Error(),
})
}
} else {
// Publish pico thoughts before the turn context is canceled at return time.
// The async variant can race with turn teardown and intermittently drop the
// thought message in CI even though the LLM produced reasoning content.
al.publishPicoReasoning(turnCtx, reasoningContent, ts.chatID, ts.sessionKey, exec.llmModelName)
}
} else {
go al.handleReasoning(
turnCtx,
reasoningContent,
ts.channel,
al.targetReasoningChannelID(ts.channel),
)
}
go al.handleReasoning(
turnCtx,
reasoningContent,
ts.channel,
al.targetReasoningChannelID(ts.channel),
)
al.emitEvent(
runtimeevents.KindAgentLLMResponse,
ts.eventMeta("runTurn", "turn.llm.response"),
@@ -607,7 +586,7 @@ func (p *Pipeline) CallLLM(
// No-tool-call path: steering check and direct response
if len(exec.response.ToolCalls) == 0 || exec.gracefulTerminal {
responseContent := exec.response.Content
if responseContent == "" && exec.response.ReasoningContent != "" && ts.channel != "pico" {
if responseContent == "" && exec.response.ReasoningContent != "" {
responseContent = exec.response.ReasoningContent
}
if steerMsgs := al.dequeueSteeringMessagesForScope(ts.sessionKey); len(steerMsgs) > 0 {
@@ -695,16 +674,6 @@ func (p *Pipeline) CallLLM(
ts.recordPersistedMessage(assistantMsg)
ts.ingestMessage(turnCtx, al, assistantMsg)
}
if shouldPublishPicoToolCallInterim {
al.publishPicoToolCallInterim(
turnCtx,
ts,
exec.llmModelName,
reasoningContent,
exec.response.Content,
assistantMsg.ToolCalls,
)
}
return ControlToolLoop, nil
}
+8 -28
View File
@@ -274,7 +274,7 @@ func (p *Pipeline) configuredStreamingEligible(ts *turnState, exec *turnExecutio
})
return false
}
if !ts.opts.SendResponse && !ts.opts.AllowInterimPicoPublish {
if !ts.opts.SendResponse && !ts.opts.AllowStreaming {
logger.DebugCF("agent", "configured streaming not used", map[string]any{
"agent_id": ts.agent.ID,
"channel": ts.channel,
@@ -370,14 +370,13 @@ func streamingConfigFromDecodedSettings(decoded any) (config.StreamingConfig, bo
}
type streamingChunkPublisher struct {
streamer bus.Streamer
channel string
chatID string
modelName string
published bool
reasoningPublished bool
err error
ts *turnState
streamer bus.Streamer
channel string
chatID string
modelName string
published bool
err error
ts *turnState
}
func (p *streamingChunkPublisher) Update(ctx context.Context, accumulated string) {
@@ -419,17 +418,12 @@ func (p *streamingChunkPublisher) UpdateReasoning(ctx context.Context, accumulat
})
return
}
p.reasoningPublished = true
}
func (p *streamingChunkPublisher) Published() bool {
return p != nil && p.published
}
func (p *streamingChunkPublisher) ReasoningPublished() bool {
return p != nil && p.reasoningPublished
}
func (p *streamingChunkPublisher) Err() error {
if p == nil {
return nil
@@ -465,20 +459,6 @@ func (p *streamingChunkPublisher) Finalize(ctx context.Context, content string,
return nil
}
func (p *streamingChunkPublisher) FinalizeReasoning(ctx context.Context, content string) error {
if p == nil || p.streamer == nil || !p.reasoningPublished || strings.TrimSpace(content) == "" {
return nil
}
reasoningStreamer, ok := p.streamer.(bus.ReasoningStreamer)
if !ok {
return nil
}
if err := reasoningStreamer.FinalizeReasoning(ctx, content); err != nil {
return fmt.Errorf("stream reasoning finalize: %w", err)
}
return nil
}
func (p *streamingChunkPublisher) ClearFinalizedStreamMarker() {
if p == nil || p.streamer == nil {
return
+43 -43
View File
@@ -288,7 +288,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
}{
{
name: "channel and model enabled streams",
channel: "pico",
channel: "telegram",
channelStreaming: true,
modelStreaming: true,
streamingProvider: true,
@@ -306,7 +306,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
},
{
name: "channel disabled uses chat",
channel: "pico",
channel: "telegram",
modelStreaming: true,
streamingProvider: true,
streamDelegate: true,
@@ -314,7 +314,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
},
{
name: "model disabled uses chat",
channel: "pico",
channel: "telegram",
channelStreaming: true,
streamingProvider: true,
streamDelegate: true,
@@ -322,7 +322,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
},
{
name: "provider without streaming uses chat",
channel: "pico",
channel: "telegram",
channelStreaming: true,
modelStreaming: true,
streamDelegate: true,
@@ -330,7 +330,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
},
{
name: "multi candidate fallback uses chat",
channel: "pico",
channel: "telegram",
channelStreaming: true,
modelStreaming: true,
fallbacks: []string{"fallback-model"},
@@ -340,7 +340,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
},
{
name: "missing streamer uses chat",
channel: "pico",
channel: "telegram",
channelStreaming: true,
modelStreaming: true,
streamingProvider: true,
@@ -348,7 +348,7 @@ func TestConfiguredStreamingEligibilityGates(t *testing.T) {
},
{
name: "omitted fields use chat",
channel: "pico",
channel: "telegram",
streamingProvider: true,
streamDelegate: true,
wantChatCalls: 1,
@@ -398,7 +398,7 @@ func TestConfiguredStreamingPreChunkFailureFallsBackToChat(t *testing.T) {
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "chat after stream failure" {
t.Fatalf("response = %q, want chat fallback response", got)
@@ -429,9 +429,9 @@ func TestConfiguredStreamingDisabledForInternalTurnWithoutUserVisibleOutput(t *t
chatResponse: &providers.LLMResponse{Content: "chat response"},
}
al := NewAgentLoop(cfg, msgBus, provider)
opts := configuredStreamingProcessOptions("pico")
opts := configuredStreamingProcessOptions("telegram")
opts.SendResponse = false
opts.AllowInterimPicoPublish = false
opts.AllowStreaming = false
got, err := al.runAgentLoop(context.Background(), al.GetRegistry().GetDefaultAgent(), opts)
if err != nil {
@@ -461,7 +461,7 @@ func TestConfiguredStreamingVisibleSendResponseFalseRetainsFinalizedStreamMarker
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "stream response" {
t.Fatalf("response = %q, want stream response", got)
@@ -471,7 +471,7 @@ func TestConfiguredStreamingVisibleSendResponseFalseRetainsFinalizedStreamMarker
}
}
func TestConfiguredStreamingStreamsPicoReasoningBeforeAnswerContent(t *testing.T) {
func TestConfiguredStreamingStreamsReasoningBeforeAnswerContent(t *testing.T) {
cfg := newConfiguredStreamingTestConfig(t, true, true, nil)
streamer := &recordingStreamer{}
msgBus := bus.NewMessageBus()
@@ -491,7 +491,7 @@ func TestConfiguredStreamingStreamsPicoReasoningBeforeAnswerContent(t *testing.T
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "answer" {
t.Fatalf("response = %q, want answer", got)
}
@@ -517,7 +517,7 @@ func TestConfiguredStreamingStreamsPicoReasoningBeforeAnswerContent(t *testing.T
}
}
func TestConfiguredStreamingSuppressesPicoReasoningWhenThinkingOff(t *testing.T) {
func TestConfiguredStreamingSuppressesReasoningWhenThinkingOff(t *testing.T) {
cfg := newConfiguredStreamingTestConfig(t, true, true, nil)
cfg.ModelList[0].ThinkingLevel = "off"
streamer := &recordingStreamer{}
@@ -537,7 +537,7 @@ func TestConfiguredStreamingSuppressesPicoReasoningWhenThinkingOff(t *testing.T)
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "answer" {
t.Fatalf("response = %q, want answer", got)
}
@@ -573,7 +573,7 @@ func TestConfiguredStreamingFinalFlushFailureAfterVisibleOutputReturnsErrorWitho
_, err := al.runAgentLoop(
context.Background(),
al.GetRegistry().GetDefaultAgent(),
configuredStreamingProcessOptions("pico"),
configuredStreamingProcessOptions("telegram"),
)
if err == nil {
t.Fatal("expected final flush failure after visible output to return an error")
@@ -600,7 +600,7 @@ func TestConfiguredStreamingFinalFlushFailureBeforeVisibleOutputPublishesFallbac
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "stream response" {
t.Fatalf("response = %q, want stream response", got)
@@ -632,7 +632,7 @@ func TestConfiguredStreamingFinalFlushFailureBeforeVisibleOutputKeepsNormalOutbo
}},
}
al := NewAgentLoop(cfg, msgBus, provider)
opts := configuredStreamingProcessOptions("pico")
opts := configuredStreamingProcessOptions("telegram")
opts.SendResponse = true
got, err := al.runAgentLoop(context.Background(), al.GetRegistry().GetDefaultAgent(), opts)
@@ -669,7 +669,7 @@ func TestConfiguredStreamingUpdateFailureThenStreamErrorFallsBackToChat(t *testi
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "chat fallback after invisible update" {
t.Fatalf("response = %q, want chat fallback", got)
@@ -704,7 +704,7 @@ func TestConfiguredStreamingUpdateFailureThenStreamSuccessFallsBackToChat(t *tes
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "chat fallback after invisible update" {
t.Fatalf("response = %q, want chat fallback", got)
@@ -742,7 +742,7 @@ func TestConfiguredStreamingLaterUpdateFailureThenStreamSuccessReturnsVisibleErr
_, err := al.runAgentLoop(
context.Background(),
al.GetRegistry().GetDefaultAgent(),
configuredStreamingProcessOptions("pico"),
configuredStreamingProcessOptions("telegram"),
)
if err == nil {
t.Fatal("expected post-visible update failure to return an error")
@@ -815,7 +815,7 @@ func TestConfiguredStreamingBeforeLLMModelRewriteReevaluatesModelStreaming(t *te
t.Fatalf("MountHook() error = %v", err)
}
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if provider.streamCalls != tt.wantStreamCalls {
t.Fatalf("ChatStream calls = %d, want %d", provider.streamCalls, tt.wantStreamCalls)
@@ -860,7 +860,7 @@ func TestConfiguredStreamingPostChunkFailureDoesNotFallBackToChat(t *testing.T)
_, err := al.runAgentLoop(
context.Background(),
al.GetRegistry().GetDefaultAgent(),
configuredStreamingProcessOptions("pico"),
configuredStreamingProcessOptions("telegram"),
)
if err == nil {
t.Fatal("expected post-chunk stream failure to return an error")
@@ -893,7 +893,7 @@ func TestConfiguredStreamingPostChunkEOFDoesNotRetryOrCancelVisibleOutput(t *tes
_, err := al.runAgentLoop(
context.Background(),
al.GetRegistry().GetDefaultAgent(),
configuredStreamingProcessOptions("pico"),
configuredStreamingProcessOptions("telegram"),
)
if err == nil {
t.Fatal("expected post-chunk EOF to return an error")
@@ -927,7 +927,7 @@ func TestConfiguredStreamingFinalizesAfterAfterLLMHookMutation(t *testing.T) {
t.Fatalf("MountHook() error = %v", err)
}
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "hooked final response" {
t.Fatalf("response = %q, want hook-modified response", got)
@@ -968,7 +968,7 @@ func TestConfiguredStreamingAfterLLMAbortCancelsPublishedStream(t *testing.T) {
_, _ = al.runAgentLoop(
context.Background(),
al.GetRegistry().GetDefaultAgent(),
configuredStreamingProcessOptions("pico"),
configuredStreamingProcessOptions("telegram"),
)
if streamer.canceled != 1 {
@@ -994,7 +994,7 @@ func TestConfiguredStreamingFinalizesWithDefaultResponseWhenContentEmpty(t *test
}
al := NewAgentLoop(cfg, msgBus, provider)
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != defaultResponse {
t.Fatalf("response = %q, want default response", got)
@@ -1032,7 +1032,7 @@ func TestConfiguredStreamingToolCallsUseCompleteStreamResponse(t *testing.T) {
agent := al.GetRegistry().GetDefaultAgent()
agent.Tools.Register(&toolLimitTestTool{})
got := runConfiguredStreamingTurn(t, al, "pico")
got := runConfiguredStreamingTurn(t, al, "telegram")
if got != "tool call handled" {
t.Fatalf("response = %q, want tool call handled", got)
@@ -1075,8 +1075,8 @@ func newConfiguredStreamingTestConfig(
},
},
Channels: config.ChannelsConfig{
"pico": newConfiguredStreamingPicoChannel(t, channelStreaming),
"wecom": newConfiguredStreamingWeComChannel(t, channelStreaming),
"telegram": newConfiguredStreamingTelegramChannel(t, channelStreaming),
"wecom": newConfiguredStreamingWeComChannel(t, channelStreaming),
},
ModelList: []*config.ModelConfig{{
ModelName: "test-model",
@@ -1120,22 +1120,22 @@ func newConfiguredStreamingWeComChannel(t *testing.T, enabled bool) *config.Chan
}
}
func newConfiguredStreamingPicoChannel(t *testing.T, enabled bool) *config.Channel {
func newConfiguredStreamingTelegramChannel(t *testing.T, enabled bool) *config.Channel {
t.Helper()
settings := config.PicoSettings{
settings := config.TelegramSettings{
Streaming: config.StreamingConfig{
Enabled: enabled,
ThrottleSeconds: 1,
MinGrowthChars: 40,
},
}
settings.SetToken("test-token")
settings.Token = *config.NewSecureString("test-token")
raw, err := json.Marshal(settings)
if err != nil {
t.Fatalf("Marshal settings error = %v", err)
}
return &config.Channel{
Type: config.ChannelPico,
Type: config.ChannelTelegram,
Enabled: true,
Settings: config.RawNode(raw),
}
@@ -1143,15 +1143,15 @@ func newConfiguredStreamingPicoChannel(t *testing.T, enabled bool) *config.Chann
func configuredStreamingProcessOptions(channel string) processOptions {
return processOptions{
SessionKey: "agent:main:" + channel + ":session-1",
Channel: channel,
ChatID: "session-1",
UserMessage: "hello",
DefaultResponse: defaultResponse,
EnableSummary: false,
SendResponse: false,
AllowInterimPicoPublish: true,
NoHistory: true,
SessionKey: "agent:main:" + channel + ":session-1",
Channel: channel,
ChatID: "session-1",
UserMessage: "hello",
DefaultResponse: defaultResponse,
EnableSummary: false,
SendResponse: false,
AllowStreaming: true,
NoHistory: true,
}
}
+8 -8
View File
@@ -203,8 +203,8 @@ func TestTurnProfile_ProcessMessageUsesEnabledTurnProfile(t *testing.T) {
_, err := al.processMessage(context.Background(), bus.InboundMessage{
Context: bus.InboundContext{
Channel: "pico",
ChatID: "pico:sess-1",
Channel: "telegram",
ChatID: "telegram:sess-1",
ChatType: "direct",
SenderID: "pico-user",
},
@@ -251,8 +251,8 @@ func TestTurnProfile_BtwCommandUsesEnabledTurnProfile(t *testing.T) {
_, err := al.processMessage(context.Background(), bus.InboundMessage{
Context: bus.InboundContext{
Channel: "pico",
ChatID: "pico:btw",
Channel: "telegram",
ChatID: "telegram:btw",
ChatType: "direct",
SenderID: "pico-user",
},
@@ -313,8 +313,8 @@ func TestTurnProfile_BtwCommandDoesNotAddToolFallbackWhenSystemPromptOff(t *test
_, err := al.processMessage(context.Background(), bus.InboundMessage{
Context: bus.InboundContext{
Channel: "pico",
ChatID: "pico:btw-system-off",
Channel: "telegram",
ChatID: "telegram:btw-system-off",
ChatType: "direct",
SenderID: "pico-user",
},
@@ -361,8 +361,8 @@ func TestTurnProfile_BtwHookCannotReenableNativeSearchWhenToolsOff(t *testing.T)
_, err := al.processMessage(context.Background(), bus.InboundMessage{
Context: bus.InboundContext{
Channel: "pico",
ChatID: "pico:btw-native-search",
Channel: "telegram",
ChatID: "telegram:btw-native-search",
ChatType: "direct",
SenderID: "pico-user",
},
+2 -2
View File
@@ -148,7 +148,7 @@ func TestPublishInbound_BackfillsContextFromLegacyFields(t *testing.T) {
defer mb.Close()
msg := InboundMessage{
Channel: "pico",
Channel: "telegram",
ChatID: "session-1",
SenderID: "user-1",
MessageID: "msg-1",
@@ -160,7 +160,7 @@ func TestPublishInbound_BackfillsContextFromLegacyFields(t *testing.T) {
}
got := <-mb.InboundChan()
if got.Context.Channel != "pico" {
if got.Context.Channel != "telegram" {
t.Fatalf("expected context channel pico, got %q", got.Context.Channel)
}
if got.Context.ChatID != "session-1" {
+8 -12
View File
@@ -60,7 +60,7 @@ pkg/channels/
├── discord/
│ ├── init.go
│ └── discord.go
├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ maixcam/ pico/
├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
│ └── ...
pkg/bus/
@@ -767,9 +767,9 @@ if c.owner != nil && c.placeholderRecorder != nil {
```
**This means**:
- Channels implementing `TypingCapable` (Telegram, Discord, LINE, Pico) do not need to manually call `StartTyping` + `RecordTypingStop` in `handleMessage`
- Channels implementing `TypingCapable` (Telegram, Discord, LINE) do not need to manually call `StartTyping` + `RecordTypingStop` in `handleMessage`
- Channels implementing `ReactionCapable` (Slack, OneBot) do not need to manually call `AddReaction` + `RecordTypingStop` in `handleMessage`
- Channels implementing `PlaceholderCapable` (Telegram, Discord, Pico) do not need to manually send placeholder messages and call `RecordPlaceholder` in `handleMessage`
- Channels implementing `PlaceholderCapable` (Telegram, Discord) do not need to manually send placeholder messages and call `RecordPlaceholder` in `handleMessage`
- Channels only need to implement the corresponding interface; `HandleMessage` handles orchestration automatically
- Channels that don't implement these interfaces are unaffected (type assertions will fail and be skipped)
- `PlaceholderCapable`'s `SendPlaceholder` method internally decides whether to send based on the configured `PlaceholderConfig.Enabled`; returning `("", nil)` skips registration
@@ -1234,7 +1234,7 @@ Timeout configuration: ReadTimeout = 30s, WriteTimeout = 30s
5. **Typing/Reaction/Placeholder is handled by BaseChannel + Manager automatically**: A channel's `Send` method does not need to manage Typing stop, Reaction undo, or Placeholder editing. `BaseChannel.HandleMessage` auto-triggers `TypingCapable`, `ReactionCapable`, and `PlaceholderCapable` on the inbound side (via `owner` type assertions); Manager's `preSend` auto-stops Typing, undoes Reaction, and edits Placeholder on the outbound side. Channels only need to implement the corresponding interfaces.
6. **Factory registration belongs in init()**: Each sub-package must have an `init.go` file calling `channels.RegisterFactory`. Gateway must trigger registration via blank imports (`_ "pkg/channels/xxx"`).
5. **Factory registration belongs in init()**: Each sub-package must have an `init.go` file calling `channels.RegisterFactory`. Gateway must trigger registration via blank imports (`_ "pkg/channels/xxx"`).
### 5.2 Metadata Field Usage Conventions
@@ -1309,9 +1309,7 @@ make test # Full test suite
| `pkg/channels/qq/` | `"qq"` | — |
| `pkg/channels/whatsapp/` | `"whatsapp"` | — (Bridge mode) |
| `pkg/channels/whatsapp_native/` | `"whatsapp_native"` | — (Native whatsmeow mode) |
| `pkg/channels/maixcam/` | `"maixcam"` | — |
| `pkg/channels/mqtt/` | `"mqtt"` | — |
| `pkg/channels/pico/` | `"pico"` | TypingCapable, PlaceholderCapable, MessageEditor, WebhookHandler |
### A.3 Interface Quick Reference
@@ -1423,12 +1421,10 @@ agentLoop.Stop() // Stop Agent
3. **WeCom is now a single channel**: `"wecom"` is implemented as a WebSocket-based AI Bot channel with route persistence. Access control uses the shared channel allowlist mechanism. It no longer exposes the legacy webhook/app split.
4. **Pico Protocol**: `pkg/channels/pico/` implements a custom PicoClaw native protocol channel that receives messages via WebSocket webhook (`/pico/ws`).
4. **WhatsApp has two modes**: `"whatsapp"` (Bridge mode, communicates via external bridge URL) and `"whatsapp_native"` (native whatsmeow mode, connects directly to WhatsApp). Manager selects which to initialize based on `WhatsAppConfig.UseNative`.
5. **WhatsApp has two modes**: `"whatsapp"` (Bridge mode, communicates via external bridge URL) and `"whatsapp_native"` (native whatsmeow mode, connects directly to WhatsApp). Manager selects which to initialize based on `WhatsAppConfig.UseNative`.
5. **DingTalk uses Stream mode**: DingTalk uses the SDK's Stream/WebSocket mode (not HTTP webhook), so it does not implement `WebhookHandler`.
6. **DingTalk uses Stream mode**: DingTalk uses the SDK's Stream/WebSocket mode (not HTTP webhook), so it does not implement `WebhookHandler`.
6. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 5 channel configs (Telegram, Discord, Slack, LINE, OneBot), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram, Discord) can actually use placeholder message editing. The rest are reserved fields.
7. **PlaceholderConfig vs implementation**: `PlaceholderConfig` appears in 6 channel configs (Telegram, Discord, Slack, LINE, OneBot, Pico), but only channels that implement both `PlaceholderCapable` + `MessageEditor` (Telegram, Discord, Pico) can actually use placeholder message editing. The rest are reserved fields.
8. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (WhatsApp, Telegram, Feishu, Discord, MaixCam, QQ, DingTalk, Slack, LINE, OneBot, WeCom). Note: `PicoConfig` does not currently expose this field. `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method.
7. **ReasoningChannelID**: Most channel configs include a `reasoning_channel_id` field to route LLM reasoning/thinking output to a designated channel (WhatsApp, Telegram, Feishu, Discord, QQ, DingTalk, Slack, LINE, OneBot, WeCom). `BaseChannel` exposes this via the `WithReasoningChannelID` option and `ReasoningChannelID()` method.
+8 -12
View File
@@ -60,7 +60,7 @@ pkg/channels/
├── discord/
│ ├── init.go
│ └── discord.go
├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ maixcam/ pico/
├── slack/ line/ onebot/ dingtalk/ feishu/ wecom/ qq/ whatsapp/ whatsapp_native/ mqtt/
│ └── ...
pkg/bus/
@@ -766,9 +766,9 @@ if c.owner != nil && c.placeholderRecorder != nil {
```
**这意味着**:
- 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE、Pico)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop`
- 实现 `TypingCapable` 的 channel(Telegram、Discord、LINE)无需在 `handleMessage` 中手动调用 `StartTyping` + `RecordTypingStop`
- 实现 `ReactionCapable` 的 channel(Slack、OneBot)无需在 `handleMessage` 中手动调用 `AddReaction` + `RecordTypingStop`
- 实现 `PlaceholderCapable` 的 channel(Telegram、Discord、Pico)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder`
- 实现 `PlaceholderCapable` 的 channel(Telegram、Discord)无需在 `handleMessage` 中手动发送占位消息并调用 `RecordPlaceholder`
- Channel 只需实现对应接口,`HandleMessage` 会自动完成编排
- 不实现这些接口的 channel 不受影响(类型断言会失败,跳过)
- `PlaceholderCapable` 的 `SendPlaceholder` 方法内部根据配置的 `PlaceholderConfig.Enabled` 决定是否发送;返回 `("", nil)` 时跳过注册
@@ -1232,7 +1232,7 @@ Manager 创建单一 `http.Server`,自动发现和注册:
5. **Typing/Reaction/Placeholder 由 BaseChannel + Manager 自动处理**:Channel 的 `Send` 方法不需要管理 Typing 停止、Reaction 撤销或 Placeholder 编辑。`BaseChannel.HandleMessage` 在入站侧自动触发 `TypingCapable`、`ReactionCapable` 和 `PlaceholderCapable`(通过 `owner` 类型断言);Manager 的 `preSend` 在出站侧自动停止 Typing、撤销 Reaction、编辑 Placeholder。Channel 只需实现对应接口即可。
6. **工厂注册在 init() 中**:每个子包必须有 `init.go` 文件调用 `channels.RegisterFactory`。Gateway 必须通过 blank import(`_ "pkg/channels/xxx"`)触发注册。
5. **工厂注册在 init() 中**:每个子包必须有 `init.go` 文件调用 `channels.RegisterFactory`。Gateway 必须通过 blank import(`_ "pkg/channels/xxx"`)触发注册。
### 5.2 Metadata 字段使用约定
@@ -1307,9 +1307,7 @@ make test # 全量测试
| `pkg/channels/qq/` | `"qq"` | — |
| `pkg/channels/whatsapp/` | `"whatsapp"` | — (Bridge 模式) |
| `pkg/channels/whatsapp_native/` | `"whatsapp_native"` | — (原生 whatsmeow 模式) |
| `pkg/channels/maixcam/` | `"maixcam"` | — |
| `pkg/channels/mqtt/` | `"mqtt"` | — |
| `pkg/channels/pico/` | `"pico"` | TypingCapable, PlaceholderCapable, MessageEditor, WebhookHandler |
### A.3 接口速查表
@@ -1421,12 +1419,10 @@ agentLoop.Stop() // 停止 Agent
3. **WeCom 现在只有一个 channel**:`"wecom"` 采用 WebSocket AI Bot 实现,带路由持久化;访问控制走统一的 channel 白名单机制,不再保留旧的 webhook/app 双分支。
4. **Pico Protocol**:`pkg/channels/pico/` 实现了一个自定义的 PicoClaw 原生协议 channel,通过 WebSocket webhook (`/pico/ws`) 接收消息。
4. **WhatsApp 有两种模式**:`"whatsapp"`(Bridge 模式,通过外部 bridge URL 通信)和 `"whatsapp_native"`(原生 whatsmeow 模式,直接连接 WhatsApp)。Manager 根据 `WhatsAppConfig.UseNative` 决定初始化哪个。
5. **WhatsApp 有两种模式**:`"whatsapp"`(Bridge 模式,通过外部 bridge URL 通信)和 `"whatsapp_native"`(原生 whatsmeow 模式,直接连接 WhatsApp)。Manager 根据 `WhatsAppConfig.UseNative` 决定初始化哪个。
5. **DingTalk 使用 Stream 模式**:DingTalk 使用 SDK 的 Stream/WebSocket 模式(非 HTTP webhook),因此不实现 `WebhookHandler`。
6. **DingTalk 使用 Stream 模式**:DingTalk 使用 SDK 的 Stream/WebSocket 模式(非 HTTP webhook),因此不实现 `WebhookHandler`。
6. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 5 个 channel config 中(Telegram、Discord、Slack、LINE、OneBot),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。
7. **PlaceholderConfig 的配置与实现**:`PlaceholderConfig` 出现在 6 个 channel config 中(Telegram、Discord、Slack、LINE、OneBot、Pico),但只有实现了 `PlaceholderCapable` + `MessageEditor` 的 channel(Telegram、Discord、Pico)能真正使用占位消息编辑功能。其余 channel 的 `PlaceholderConfig` 为预留字段。
8. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、MaixCam、QQ、DingTalk、Slack、LINE、OneBot、WeCom)。注意:`PicoConfig` 目前不包含该字段。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。
7. **ReasoningChannelID**:大多数 channel config 都包含 `reasoning_channel_id` 字段,用于将 LLM 的思维链(reasoning/thinking)路由到指定 channel(WhatsApp、Telegram、Feishu、Discord、QQ、DingTalk、Slack、LINE、OneBot、WeCom)。`BaseChannel` 通过 `WithReasoningChannelID` 选项和 `ReasoningChannelID()` 方法暴露此配置。
-25
View File
@@ -1,25 +0,0 @@
package maixcam
import (
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/config"
)
func init() {
channels.RegisterFactory(
config.ChannelMaixCam,
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
bc := cfg.Channels[channelName]
decoded, err := bc.GetDecoded()
if err != nil {
return nil, err
}
c, ok := decoded.(*config.MaixCamSettings)
if !ok {
return nil, channels.ErrSendFailed
}
return NewMaixCamChannel(bc, c, b)
},
)
}
-291
View File
@@ -1,291 +0,0 @@
package maixcam
import (
"context"
"encoding/json"
"fmt"
"net"
"sync"
"time"
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/identity"
"github.com/sipeed/picoclaw/pkg/logger"
)
type MaixCamChannel struct {
*channels.BaseChannel
config *config.MaixCamSettings
listener net.Listener
ctx context.Context
cancel context.CancelFunc
clients map[net.Conn]bool
clientsMux sync.RWMutex
}
type MaixCamMessage struct {
Type string `json:"type"`
Tips string `json:"tips"`
Timestamp float64 `json:"timestamp"`
Data map[string]any `json:"data"`
}
func NewMaixCamChannel(
bc *config.Channel,
cfg *config.MaixCamSettings,
bus *bus.MessageBus,
) (*MaixCamChannel, error) {
base := channels.NewBaseChannel(
"maixcam",
cfg,
bus,
bc.AllowFrom,
channels.WithReasoningChannelID(bc.ReasoningChannelID),
)
return &MaixCamChannel{
BaseChannel: base,
config: cfg,
clients: make(map[net.Conn]bool),
}, nil
}
func (c *MaixCamChannel) Start(ctx context.Context) error {
logger.InfoC("maixcam", "Starting MaixCam channel server")
c.ctx, c.cancel = context.WithCancel(ctx)
addr := fmt.Sprintf("%s:%d", c.config.Host, c.config.Port)
listener, err := net.Listen("tcp", addr)
if err != nil {
c.cancel()
return fmt.Errorf("failed to listen on %s: %w", addr, err)
}
c.listener = listener
c.SetRunning(true)
logger.InfoCF("maixcam", "MaixCam server listening", map[string]any{
"host": c.config.Host,
"port": c.config.Port,
})
go c.acceptConnections()
return nil
}
func (c *MaixCamChannel) acceptConnections() {
logger.DebugC("maixcam", "Starting connection acceptor")
for {
select {
case <-c.ctx.Done():
logger.InfoC("maixcam", "Stopping connection acceptor")
return
default:
conn, err := c.listener.Accept()
if err != nil {
if c.IsRunning() {
logger.ErrorCF("maixcam", "Failed to accept connection", map[string]any{
"error": err.Error(),
})
}
return
}
logger.InfoCF("maixcam", "New connection from MaixCam device", map[string]any{
"remote_addr": conn.RemoteAddr().String(),
})
c.clientsMux.Lock()
c.clients[conn] = true
c.clientsMux.Unlock()
go c.handleConnection(conn)
}
}
}
func (c *MaixCamChannel) handleConnection(conn net.Conn) {
logger.DebugC("maixcam", "Handling MaixCam connection")
defer func() {
conn.Close()
c.clientsMux.Lock()
delete(c.clients, conn)
c.clientsMux.Unlock()
logger.DebugC("maixcam", "Connection closed")
}()
decoder := json.NewDecoder(conn)
for {
select {
case <-c.ctx.Done():
return
default:
var msg MaixCamMessage
if err := decoder.Decode(&msg); err != nil {
if err.Error() != "EOF" {
logger.ErrorCF("maixcam", "Failed to decode message", map[string]any{
"error": err.Error(),
})
}
return
}
c.processMessage(msg, conn)
}
}
}
func (c *MaixCamChannel) processMessage(msg MaixCamMessage, conn net.Conn) {
switch msg.Type {
case "person_detected":
c.handlePersonDetection(msg)
case "heartbeat":
logger.DebugC("maixcam", "Received heartbeat")
case "status":
c.handleStatusUpdate(msg)
default:
logger.WarnCF("maixcam", "Unknown message type", map[string]any{
"type": msg.Type,
})
}
}
func (c *MaixCamChannel) handlePersonDetection(msg MaixCamMessage) {
logger.InfoCF("maixcam", "", map[string]any{
"timestamp": msg.Timestamp,
"data": msg.Data,
})
senderID := "maixcam"
chatID := "default"
classInfo, ok := msg.Data["class_name"].(string)
if !ok {
classInfo = "person"
}
score, _ := msg.Data["score"].(float64)
x, _ := msg.Data["x"].(float64)
y, _ := msg.Data["y"].(float64)
w, _ := msg.Data["w"].(float64)
h, _ := msg.Data["h"].(float64)
content := fmt.Sprintf("📷 Person detected!\nClass: %s\nConfidence: %.2f%%\nPosition: (%.0f, %.0f)\nSize: %.0fx%.0f",
classInfo, score*100, x, y, w, h)
metadata := map[string]string{
"timestamp": fmt.Sprintf("%.0f", msg.Timestamp),
"class_id": fmt.Sprintf("%.0f", msg.Data["class_id"]),
"score": fmt.Sprintf("%.2f", score),
"x": fmt.Sprintf("%.0f", x),
"y": fmt.Sprintf("%.0f", y),
"w": fmt.Sprintf("%.0f", w),
"h": fmt.Sprintf("%.0f", h),
}
sender := bus.SenderInfo{
Platform: "maixcam",
PlatformID: "maixcam",
CanonicalID: identity.BuildCanonicalID("maixcam", "maixcam"),
}
if !c.IsAllowedSender(sender) {
return
}
inboundCtx := bus.InboundContext{
Channel: "maixcam",
ChatID: chatID,
ChatType: "channel",
SenderID: senderID,
Raw: metadata,
}
c.HandleInboundContext(c.ctx, chatID, content, nil, inboundCtx, sender)
}
func (c *MaixCamChannel) handleStatusUpdate(msg MaixCamMessage) {
logger.InfoCF("maixcam", "Status update from MaixCam", map[string]any{
"status": msg.Data,
})
}
func (c *MaixCamChannel) Stop(ctx context.Context) error {
logger.InfoC("maixcam", "Stopping MaixCam channel")
c.SetRunning(false)
// Cancel context first to signal goroutines to exit
if c.cancel != nil {
c.cancel()
}
if c.listener != nil {
c.listener.Close()
}
c.clientsMux.Lock()
defer c.clientsMux.Unlock()
for conn := range c.clients {
conn.Close()
}
c.clients = make(map[net.Conn]bool)
logger.InfoC("maixcam", "MaixCam channel stopped")
return nil
}
func (c *MaixCamChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
if !c.IsRunning() {
return nil, channels.ErrNotRunning
}
// Check ctx before entering write path
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
c.clientsMux.RLock()
defer c.clientsMux.RUnlock()
if len(c.clients) == 0 {
logger.WarnC("maixcam", "No MaixCam devices connected")
return nil, fmt.Errorf("no connected MaixCam devices")
}
response := map[string]any{
"type": "command",
"timestamp": float64(0),
"message": msg.Content,
"chat_id": msg.ChatID,
}
data, err := json.Marshal(response)
if err != nil {
return nil, fmt.Errorf("failed to marshal response: %w", err)
}
var sendErr error
for conn := range c.clients {
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if _, err := conn.Write(data); err != nil {
logger.ErrorCF("maixcam", "Failed to send to client", map[string]any{
"client": conn.RemoteAddr().String(),
"error": err.Error(),
})
sendErr = fmt.Errorf("maixcam send: %w", channels.ErrTemporary)
}
_ = conn.SetWriteDeadline(time.Time{})
}
return nil, sendErr
}
-6
View File
@@ -1060,16 +1060,12 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
return bc, settings.Homeserver != "" && settings.UserID != "" && settings.AccessToken.String() != ""
case *config.WeComSettings:
return bc, settings.BotID != "" && settings.Secret.String() != ""
case *config.PicoClientSettings:
return bc, settings.URL != ""
case *config.DingTalkSettings:
return bc, settings.ClientID != ""
case *config.SlackSettings:
return bc, settings.BotToken.String() != ""
case *config.WeixinSettings:
return bc, settings.Token.String() != ""
case *config.PicoSettings:
return bc, settings.Token.String() != ""
case *config.IRCSettings:
return bc, settings.Server != ""
case *config.LINESettings:
@@ -1082,8 +1078,6 @@ func (m *Manager) getChannelConfigAndEnabled(channelName string) (*config.Channe
return bc, settings.Token.String() != ""
case *config.FeishuSettings:
return bc, settings.AppSecret.String() != ""
case *config.MaixCamSettings:
return bc, true
case *config.TeamsWebhookSettings:
return bc, true
case *config.SlackWebhookSettings:
-4
View File
@@ -46,10 +46,6 @@ func hiddenValues(key string, value map[string]any, ch *config.Channel) {
return
}
switch key {
case "pico":
if settings, ok := v.(*config.PicoSettings); ok {
value["token"] = settings.Token.String()
}
case "telegram":
if settings, ok := v.(*config.TelegramSettings); ok {
value["token"] = settings.Token.String()
-343
View File
@@ -1,343 +0,0 @@
package pico
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/config"
"github.com/sipeed/picoclaw/pkg/identity"
"github.com/sipeed/picoclaw/pkg/logger"
)
// PicoClientChannel connects to a remote Pico Protocol WebSocket server.
type PicoClientChannel struct {
*channels.BaseChannel
config *config.PicoClientSettings
conn *picoConn
mu sync.Mutex
ctx context.Context
cancel context.CancelFunc
}
// NewPicoClientChannel creates a new Pico Protocol client channel.
func NewPicoClientChannel(
bc *config.Channel,
cfg *config.PicoClientSettings,
messageBus *bus.MessageBus,
) (*PicoClientChannel, error) {
if cfg.URL == "" {
return nil, fmt.Errorf("pico_client url is required")
}
base := channels.NewBaseChannel("pico_client", cfg, messageBus, bc.AllowFrom)
return &PicoClientChannel{
BaseChannel: base,
config: cfg,
}, nil
}
// Start dials the remote server and begins reading.
func (c *PicoClientChannel) Start(ctx context.Context) error {
logger.InfoC("pico_client", "Starting Pico Client channel")
c.ctx, c.cancel = context.WithCancel(ctx)
if err := c.dial(); err != nil {
c.cancel()
return fmt.Errorf("pico_client initial connect: %w", err)
}
c.SetRunning(true)
go c.reconnectLoop()
logger.InfoCF("pico_client", "Connected", map[string]any{"url": c.config.URL})
return nil
}
// Stop closes the connection.
func (c *PicoClientChannel) Stop(ctx context.Context) error {
logger.InfoC("pico_client", "Stopping Pico Client channel")
c.SetRunning(false)
if c.cancel != nil {
c.cancel()
}
c.mu.Lock()
if c.conn != nil {
c.conn.close()
}
c.mu.Unlock()
logger.InfoC("pico_client", "Pico Client channel stopped")
return nil
}
func (c *PicoClientChannel) dial() error {
header := http.Header{}
if c.config.Token.String() != "" {
header.Set("Authorization", "Bearer "+c.config.Token.String())
}
ws, resp, err := websocket.DefaultDialer.DialContext(c.ctx, c.config.URL, header)
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
if err != nil {
return err
}
connCtx, connCancel := context.WithCancel(c.ctx)
pc := &picoConn{
id: uuid.New().String(),
conn: ws,
sessionID: c.config.SessionID,
cancel: connCancel,
}
if pc.sessionID == "" {
pc.sessionID = uuid.New().String()
}
c.mu.Lock()
c.conn = pc
c.mu.Unlock()
go c.readLoop(connCtx, pc)
return nil
}
// reconnectLoop re-dials when the connection drops.
func (c *PicoClientChannel) reconnectLoop() {
for {
select {
case <-c.ctx.Done():
return
default:
}
c.mu.Lock()
pc := c.conn
c.mu.Unlock()
if pc == nil || pc.closed.Load() {
backoff := 5 * time.Second
logger.InfoC("pico_client", "Reconnecting...")
if err := c.dial(); err != nil {
logger.WarnCF("pico_client", "Reconnect failed", map[string]any{
"error": err.Error(),
})
select {
case <-c.ctx.Done():
return
case <-time.After(backoff):
}
continue
}
logger.InfoC("pico_client", "Reconnected")
}
select {
case <-c.ctx.Done():
return
case <-time.After(1 * time.Second):
}
}
}
func (c *PicoClientChannel) readLoop(connCtx context.Context, pc *picoConn) {
defer pc.close()
readTimeout := time.Duration(c.config.ReadTimeout) * time.Second
if readTimeout <= 0 {
readTimeout = 60 * time.Second
}
_ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout))
pc.conn.SetPongHandler(func(string) error {
return pc.conn.SetReadDeadline(time.Now().Add(readTimeout))
})
pingInterval := time.Duration(c.config.PingInterval) * time.Second
if pingInterval <= 0 {
pingInterval = 30 * time.Second
}
go c.pingLoop(connCtx, pc, pingInterval)
for {
select {
case <-connCtx.Done():
return
default:
}
_, raw, err := pc.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(
err,
websocket.CloseGoingAway,
websocket.CloseNormalClosure,
) {
logger.DebugCF("pico_client", "Read error", map[string]any{
"error": err.Error(),
})
}
return
}
_ = pc.conn.SetReadDeadline(time.Now().Add(readTimeout))
var msg PicoMessage
if err := json.Unmarshal(raw, &msg); err != nil {
continue
}
c.handleInbound(pc, msg)
}
}
func (c *PicoClientChannel) pingLoop(connCtx context.Context, pc *picoConn, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-connCtx.Done():
return
case <-ticker.C:
if pc.closed.Load() {
return
}
pc.writeMu.Lock()
err := pc.conn.WriteMessage(websocket.PingMessage, nil)
pc.writeMu.Unlock()
if err != nil {
return
}
}
}
}
// handleInbound processes messages from the remote server.
// In client mode the server sends message.create (responses) and the client
// sends message.send (user input). We treat message.create from the server
// as inbound user messages to feed into the agent loop.
func (c *PicoClientChannel) handleInbound(pc *picoConn, msg PicoMessage) {
switch msg.Type {
case TypePong:
// response to our ping, ignore
case TypeMessageCreate:
// Server sent us a message — treat as inbound
c.handleServerMessage(pc, msg)
case TypeMediaCreate:
c.handleServerMessage(pc, msg)
default:
logger.DebugCF("pico_client", "Ignoring message type", map[string]any{
"type": msg.Type,
})
}
}
func (c *PicoClientChannel) handleServerMessage(pc *picoConn, msg PicoMessage) {
if isThoughtPayload(msg.Payload) {
return
}
content, _ := msg.Payload[PayloadKeyContent].(string)
media, err := parseInlineImageMedia(msg.Payload)
if err != nil {
logger.WarnCF("pico_client", "Ignoring invalid media payload", map[string]any{
"error": err.Error(),
})
if strings.TrimSpace(content) == "" {
return
}
media = nil
}
if strings.TrimSpace(content) == "" && len(media) == 0 {
return
}
sessionID := msg.SessionID
if sessionID == "" {
sessionID = pc.sessionID
}
chatID := "pico_client:" + sessionID
senderID := "pico-remote"
sender := bus.SenderInfo{
Platform: "pico_client",
PlatformID: senderID,
CanonicalID: identity.BuildCanonicalID("pico_client", senderID),
}
if !c.IsAllowedSender(sender) {
return
}
inboundCtx := bus.InboundContext{
Channel: "pico_client",
ChatID: chatID,
ChatType: "direct",
SenderID: senderID,
MessageID: msg.ID,
Raw: map[string]string{
"platform": "pico_client",
"session_id": sessionID,
},
}
c.HandleInboundContext(c.ctx, chatID, content, media, inboundCtx, sender)
}
// Send sends a message to the remote server.
func (c *PicoClientChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]string, error) {
if !c.IsRunning() {
return nil, channels.ErrNotRunning
}
c.mu.Lock()
pc := c.conn
c.mu.Unlock()
if pc == nil || pc.closed.Load() {
return nil, channels.ErrSendFailed
}
outMsg := newMessage(TypeMessageSend, map[string]any{
PayloadKeyContent: msg.Content,
})
outMsg.SessionID = strings.TrimPrefix(msg.ChatID, "pico_client:")
return nil, pc.writeJSON(outMsg)
}
// StartTyping implements channels.TypingCapable.
func (c *PicoClientChannel) StartTyping(ctx context.Context, chatID string) (func(), error) {
c.mu.Lock()
pc := c.conn
c.mu.Unlock()
if pc == nil || pc.closed.Load() {
return func() {}, nil
}
startMsg := newMessage(TypeTypingStart, nil)
startMsg.SessionID = strings.TrimPrefix(chatID, "pico_client:")
if err := pc.writeJSON(startMsg); err != nil {
return func() {}, err
}
return func() {
c.mu.Lock()
currentPC := c.conn
c.mu.Unlock()
if currentPC == nil {
return
}
stopMsg := newMessage(TypeTypingStop, nil)
stopMsg.SessionID = strings.TrimPrefix(chatID, "pico_client:")
currentPC.writeJSON(stopMsg)
}, nil
}
-625
View File
@@ -1,625 +0,0 @@
package pico
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/config"
)
func TestNewPicoClientChannel_MissingURL(t *testing.T) {
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
_, err := NewPicoClientChannel(bc, &config.PicoClientSettings{}, bus.NewMessageBus())
if err == nil {
t.Fatal("expected error for missing URL")
}
if !strings.Contains(err.Error(), "url is required") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestNewPicoClientChannel_OK(t *testing.T) {
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:9999/ws",
}, bus.NewMessageBus())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ch.Name() != "pico_client" {
t.Fatalf("name = %q, want pico_client", ch.Name())
}
}
func TestSend_NotRunning(t *testing.T) {
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:9999/ws",
}, bus.NewMessageBus())
if err != nil {
t.Fatal(err)
}
_, err = ch.Send(context.Background(), bus.OutboundMessage{Content: "hi"})
if !errors.Is(err, channels.ErrNotRunning) {
t.Fatalf("expected ErrNotRunning, got %v", err)
}
}
// testServer starts a WS server that echoes message.send back as message.create.
func testServer(t *testing.T, token string) *httptest.Server {
t.Helper()
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token != "" {
auth := r.Header.Get("Authorization")
if auth != "Bearer "+token {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
t.Logf("upgrade error: %v", err)
return
}
defer conn.Close()
for {
_, raw, err := conn.ReadMessage()
if err != nil {
return
}
var msg PicoMessage
if err := json.Unmarshal(raw, &msg); err != nil {
continue
}
if msg.Type == TypeMessageSend {
reply := newMessage(TypeMessageCreate, msg.Payload)
reply.SessionID = msg.SessionID
if err := conn.WriteJSON(reply); err != nil {
return
}
}
}
}))
}
func wsURL(httpURL string) string {
return "ws" + strings.TrimPrefix(httpURL, "http")
}
func TestClientChannel_ConnectAndSend(t *testing.T) {
srv := testServer(t, "test-token")
defer srv.Close()
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: wsURL(srv.URL),
Token: *config.NewSecureString("test-token"),
SessionID: "sess-1",
PingInterval: 60,
ReadTimeout: 10,
}, mb)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err = ch.Start(ctx); err != nil {
t.Fatalf("Start: %v", err)
}
defer ch.Stop(ctx)
// Send a message
_, err = ch.Send(ctx, bus.OutboundMessage{
ChatID: "pico_client:sess-1",
Content: "hello",
})
if err != nil {
t.Fatalf("Send: %v", err)
}
}
func TestClientChannel_AuthFailure(t *testing.T) {
srv := testServer(t, "correct-token")
defer srv.Close()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: wsURL(srv.URL),
Token: *config.NewSecureString("wrong-token"),
}, bus.NewMessageBus())
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
err = ch.Start(ctx)
if err == nil {
ch.Stop(ctx)
t.Fatal("expected auth failure")
}
}
func TestClientChannel_ReceivesServerMessage(t *testing.T) {
srv := testServer(t, "")
defer srv.Close()
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: wsURL(srv.URL),
SessionID: "sess-echo",
ReadTimeout: 10,
}, mb)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err = ch.Start(ctx); err != nil {
t.Fatalf("Start: %v", err)
}
defer ch.Stop(ctx)
// Send a message; the echo server replies with message.create
_, err = ch.Send(ctx, bus.OutboundMessage{
ChatID: "pico_client:sess-echo",
Content: "ping",
})
if err != nil {
t.Fatalf("Send: %v", err)
}
// The echoed message.create is processed by handleServerMessage which
// calls HandleMessage → PublishInbound. Consume it from the bus.
select {
case msg := <-mb.InboundChan():
if msg.Content != "ping" {
t.Fatalf("received = %q, want %q", msg.Content, "ping")
}
case <-ctx.Done():
t.Fatal("timed out waiting for echoed message")
}
}
func TestClientChannel_StartTyping(t *testing.T) {
srv := testServer(t, "")
defer srv.Close()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: wsURL(srv.URL),
SessionID: "sess-type",
ReadTimeout: 10,
}, bus.NewMessageBus())
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err = ch.Start(ctx); err != nil {
t.Fatalf("Start: %v", err)
}
defer ch.Stop(ctx)
stop, err := ch.StartTyping(ctx, "pico_client:sess-type")
if err != nil {
t.Fatalf("StartTyping: %v", err)
}
stop() // should not panic
}
func TestSend_ClosedConnection(t *testing.T) {
srv := testServer(t, "")
defer srv.Close()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: wsURL(srv.URL),
SessionID: "sess-close",
ReadTimeout: 10,
}, bus.NewMessageBus())
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err = ch.Start(ctx); err != nil {
t.Fatalf("Start: %v", err)
}
// Force close the underlying connection
ch.mu.Lock()
ch.conn.close()
ch.mu.Unlock()
_, err = ch.Send(ctx, bus.OutboundMessage{
ChatID: "pico_client:sess-close",
Content: "should fail",
})
if !errors.Is(err, channels.ErrSendFailed) {
t.Fatalf("expected ErrSendFailed, got %v", err)
}
ch.Stop(ctx)
}
func TestParseInlineImageMedia_Valid(t *testing.T) {
media, err := parseInlineImageMedia(map[string]any{
"media": []any{
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=",
},
})
if err != nil {
t.Fatalf("parseInlineImageMedia() error = %v", err)
}
if len(media) != 1 {
t.Fatalf("len(media) = %d, want 1", len(media))
}
}
func TestParseInlineImageMedia_Attachments(t *testing.T) {
imageURL := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII="
media, err := parseInlineImageMedia(map[string]any{
"attachments": []any{
map[string]any{
"type": "image",
"url": imageURL,
},
},
})
if err != nil {
t.Fatalf("parseInlineImageMedia() error = %v", err)
}
if len(media) != 1 || media[0] != imageURL {
t.Fatalf("media = %#v, want attachment image payload", media)
}
}
func TestPicoChannel_HandleMessageSend_AllowsMediaOnly(t *testing.T) {
mb := bus.NewMessageBus()
bc := &config.Channel{Type: "pico", Enabled: true}
ch, err := NewPicoChannel(bc, &config.PicoSettings{
Token: *config.NewSecureString("test-token"),
}, mb)
if err != nil {
t.Fatalf("NewPicoChannel() error = %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := ch.Start(ctx); err != nil {
t.Fatalf("Start() error = %v", err)
}
defer ch.Stop(ctx)
pc := &picoConn{id: "conn-1", sessionID: "sess-1"}
ch.handleMessageSend(pc, PicoMessage{
ID: "msg-1",
Payload: map[string]any{
"media": []any{
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII=",
},
},
})
select {
case msg := <-mb.InboundChan():
if msg.Content != "" {
t.Fatalf("msg.Content = %q, want empty", msg.Content)
}
if len(msg.Media) != 1 || !strings.HasPrefix(msg.Media[0], "data:image/png;base64,") {
t.Fatalf("msg.Media = %#v, want inline image payload", msg.Media)
}
case <-ctx.Done():
t.Fatal("timed out waiting for inbound media message")
}
}
func newTestPicoClientChannel(t *testing.T) (*PicoClientChannel, *bus.MessageBus) {
t.Helper()
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:8080/ws",
}, mb)
if err != nil {
t.Fatalf("NewPicoClientChannel() error = %v", err)
}
ch.ctx = context.Background()
return ch, mb
}
func assertInboundMessage(
t *testing.T,
mb *bus.MessageBus,
wantContent string,
wantMedia []string,
timeoutMessage string,
) {
t.Helper()
select {
case msg := <-mb.InboundChan():
if msg.Content != wantContent {
t.Fatalf("msg.Content = %q, want %s", msg.Content, wantContent)
}
if len(msg.Media) != len(wantMedia) {
t.Fatalf("msg.Media = %#v, want %#v", msg.Media, wantMedia)
}
for i := range wantMedia {
if msg.Media[i] != wantMedia[i] {
t.Fatalf("msg.Media = %#v, want %#v", msg.Media, wantMedia)
}
}
case <-time.After(time.Second):
t.Fatal(timeoutMessage)
}
}
func TestPicoClientChannel_HandleServerMessage_ForwardsMedia(t *testing.T) {
ch, mb := newTestPicoClientChannel(t)
pc := &picoConn{sessionID: "sess-media"}
imageURL := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII="
ch.handleServerMessage(pc, PicoMessage{
Type: TypeMessageCreate,
Payload: map[string]any{
PayloadKeyContent: "describe this",
"attachments": []any{
map[string]any{
"type": "image",
"url": imageURL,
},
},
},
})
assertInboundMessage(
t,
mb,
"describe this",
[]string{imageURL},
"timed out waiting for forwarded media message",
)
}
func TestPicoClientChannel_HandleInbound_ForwardsMediaCreate(t *testing.T) {
ch, mb := newTestPicoClientChannel(t)
pc := &picoConn{sessionID: "sess-media-create"}
imageURL := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ioAAAAASUVORK5CYII="
ch.handleInbound(pc, PicoMessage{
Type: TypeMediaCreate,
Payload: map[string]any{
PayloadKeyContent: "describe media.create",
"attachments": []any{
map[string]any{
"type": "image",
"url": imageURL,
},
},
},
})
assertInboundMessage(
t,
mb,
"describe media.create",
[]string{imageURL},
"timed out waiting for media.create message",
)
}
func TestPicoClientChannel_HandleServerMessage_ForwardsTextWithDownloadAttachment(t *testing.T) {
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:8080/ws",
}, mb)
if err != nil {
t.Fatalf("NewPicoClientChannel() error = %v", err)
}
ch.ctx = context.Background()
pc := &picoConn{sessionID: "sess-download-attachment"}
ch.handleServerMessage(pc, PicoMessage{
Type: TypeMessageCreate,
Payload: map[string]any{
PayloadKeyContent: "see attached",
"attachments": []any{
map[string]any{
"type": "image",
"url": "/pico/media/abc",
"filename": "image.png",
"content_type": "image/png",
},
},
},
})
select {
case msg := <-mb.InboundChan():
if msg.Content != "see attached" {
t.Fatalf("msg.Content = %q, want see attached", msg.Content)
}
if len(msg.Media) != 0 {
t.Fatalf("msg.Media = %#v, want no inline media", msg.Media)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for text message with download attachment")
}
}
func TestPicoClientChannel_HandleServerMessage_ForwardsTextWithInvalidMediaPayload(t *testing.T) {
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:8080/ws",
}, mb)
if err != nil {
t.Fatalf("NewPicoClientChannel() error = %v", err)
}
ch.ctx = context.Background()
pc := &picoConn{sessionID: "sess-invalid-media"}
ch.handleServerMessage(pc, PicoMessage{
Type: TypeMessageCreate,
Payload: map[string]any{
PayloadKeyContent: "hello despite invalid media",
"attachments": "not-an-array",
},
})
select {
case msg := <-mb.InboundChan():
if msg.Content != "hello despite invalid media" {
t.Fatalf("msg.Content = %q, want hello despite invalid media", msg.Content)
}
if len(msg.Media) != 0 {
t.Fatalf("msg.Media = %#v, want no inline media", msg.Media)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for text message with invalid media payload")
}
}
func TestIsThoughtPayload(t *testing.T) {
tests := []struct {
name string
payload map[string]any
want bool
}{
{
name: "explicit thought kind",
payload: map[string]any{PayloadKeyKind: MessageKindThought},
want: true,
},
{
name: "thought kind ignores case and whitespace",
payload: map[string]any{PayloadKeyKind: " ThOuGhT "},
want: true,
},
{
name: "legacy thought bool remains supported for inbound compatibility",
payload: map[string]any{PayloadKeyThought: true},
want: true,
},
{
name: "legacy thought false",
payload: map[string]any{PayloadKeyThought: false},
want: false,
},
{
name: "tool calls kind",
payload: map[string]any{PayloadKeyKind: MessageKindToolCalls},
want: false,
},
{
name: "non-string kind ignored",
payload: map[string]any{PayloadKeyKind: true},
want: false,
},
{
name: "default normal",
payload: map[string]any{PayloadKeyContent: "hello"},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isThoughtPayload(tt.payload); got != tt.want {
t.Fatalf("isThoughtPayload() = %v, want %v", got, tt.want)
}
})
}
}
func TestPicoClientChannel_HandleServerMessage_IgnoresThought(t *testing.T) {
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:8080/ws",
}, mb)
if err != nil {
t.Fatalf("NewPicoClientChannel() error = %v", err)
}
ch.ctx = context.Background()
pc := &picoConn{sessionID: "sess-thought"}
ch.handleServerMessage(pc, PicoMessage{
Type: TypeMessageCreate,
Payload: map[string]any{
PayloadKeyContent: "internal reasoning",
PayloadKeyKind: MessageKindThought,
},
})
select {
case msg := <-mb.InboundChan():
t.Fatalf("expected no inbound publish for thought payload, got %+v", msg)
case <-time.After(150 * time.Millisecond):
}
}
func TestPicoClientChannel_HandleServerMessage_IgnoresLegacyThoughtBool(t *testing.T) {
mb := bus.NewMessageBus()
bc := &config.Channel{Type: config.ChannelPicoClient, Enabled: true}
ch, err := NewPicoClientChannel(bc, &config.PicoClientSettings{
URL: "ws://localhost:8080/ws",
}, mb)
if err != nil {
t.Fatalf("NewPicoClientChannel() error = %v", err)
}
ch.ctx = context.Background()
pc := &picoConn{sessionID: "sess-thought-legacy"}
ch.handleServerMessage(pc, PicoMessage{
Type: TypeMessageCreate,
Payload: map[string]any{
PayloadKeyContent: "legacy internal reasoning",
PayloadKeyThought: true,
},
})
select {
case msg := <-mb.InboundChan():
t.Fatalf("expected no inbound publish for legacy thought payload, got %+v", msg)
case <-time.After(150 * time.Millisecond):
}
}
-54
View File
@@ -1,54 +0,0 @@
package pico
import (
"github.com/sipeed/picoclaw/pkg/bus"
"github.com/sipeed/picoclaw/pkg/channels"
"github.com/sipeed/picoclaw/pkg/config"
)
func init() {
channels.RegisterFactory(
config.ChannelPico,
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
bc := cfg.Channels[channelName]
decoded, err := bc.GetDecoded()
if err != nil {
return nil, err
}
c, ok := decoded.(*config.PicoSettings)
if !ok {
return nil, channels.ErrSendFailed
}
ch, err := NewPicoChannel(bc, c, b)
if err != nil {
return nil, err
}
if channelName != config.ChannelPico {
ch.SetName(channelName)
}
return ch, nil
},
)
channels.RegisterFactory(
config.ChannelPicoClient,
func(channelName, channelType string, cfg *config.Config, b *bus.MessageBus) (channels.Channel, error) {
bc := cfg.Channels[channelName]
decoded, err := bc.GetDecoded()
if err != nil {
return nil, err
}
c, ok := decoded.(*config.PicoClientSettings)
if !ok {
return nil, channels.ErrSendFailed
}
ch, err := NewPicoClientChannel(bc, c, b)
if err != nil {
return nil, err
}
if channelName != config.ChannelPicoClient {
ch.SetName(channelName)
}
return ch, nil
},
)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-69
View File
@@ -1,69 +0,0 @@
package pico
import (
"context"
"testing"
)
func TestSetTurnUsagePayload(t *testing.T) {
t.Run("populates usage block when counts present", func(t *testing.T) {
payload := map[string]any{PayloadKeyContent: "hi"}
setTurnUsagePayload(payload, 1234, 567)
raw, ok := payload[PayloadKeyUsage]
if !ok {
t.Fatalf("expected %q key in payload", PayloadKeyUsage)
}
usage, ok := raw.(map[string]any)
if !ok {
t.Fatalf("usage block is not a map: %T", raw)
}
if usage["input_tokens"] != 1234 {
t.Errorf("input_tokens = %v, want 1234", usage["input_tokens"])
}
if usage["output_tokens"] != 567 {
t.Errorf("output_tokens = %v, want 567", usage["output_tokens"])
}
if usage["total_tokens"] != 1801 {
t.Errorf("total_tokens = %v, want 1801", usage["total_tokens"])
}
})
t.Run("omits usage block when both counts zero", func(t *testing.T) {
payload := map[string]any{PayloadKeyContent: "hi"}
setTurnUsagePayload(payload, 0, 0)
if _, ok := payload[PayloadKeyUsage]; ok {
t.Errorf("expected no %q key when counts are zero", PayloadKeyUsage)
}
})
}
// newCaptureStreamer returns a streamer whose broadcasts are captured into the
// returned map pointer, so tests need no live websocket.
func newCaptureStreamer() (*picoStreamer, *map[string]any) {
var last map[string]any
ch := &PicoChannel{}
ch.broadcastFn = func(chatID string, msg PicoMessage) error {
last = msg.Payload
return nil
}
s := &picoStreamer{channel: ch, chatID: "c1"}
return s, &last
}
func TestStreamerEmitsUsageOnFinalize(t *testing.T) {
s, last := newCaptureStreamer()
s.SetTurnUsage(100, 40)
// sendLocked with empty messageID takes the create branch, which attaches
// usage from the streamer's stored counts.
s.mu.Lock()
err := s.sendLocked(context.Background(), "answer", nil)
s.mu.Unlock()
if err != nil {
t.Fatalf("sendLocked: %v", err)
}
if _, ok := (*last)[PayloadKeyUsage]; !ok {
t.Fatalf("expected usage in payload, got %+v", *last)
}
}
-81
View File
@@ -1,81 +0,0 @@
package pico
import (
"strings"
"time"
)
// Protocol message types.
const (
// TypeMessageSend is sent from client to server.
TypeMessageSend = "message.send"
TypeMediaSend = "media.send"
TypePing = "ping"
// TypeMessageCreate is sent from server to client.
TypeMessageCreate = "message.create"
TypeMessageUpdate = "message.update"
TypeMessageDelete = "message.delete"
TypeMediaCreate = "media.create"
TypeTypingStart = "typing.start"
TypeTypingStop = "typing.stop"
TypeError = "error"
TypePong = "pong"
PayloadKeyContent = "content"
PayloadKeyThought = "thought"
PayloadKeyKind = "kind"
PayloadKeyPlaceholder = "placeholder"
PayloadKeyToolCalls = "tool_calls"
PayloadKeyModelName = "model_name"
PayloadKeyUsage = "usage"
MessageKindThought = "thought"
MessageKindToolCalls = "tool_calls"
)
// PicoMessage is the wire format for all Pico Protocol messages.
type PicoMessage struct {
Type string `json:"type"`
ID string `json:"id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Payload map[string]any `json:"payload,omitempty"`
}
// newMessage creates a PicoMessage with the given type and payload.
func newMessage(msgType string, payload map[string]any) PicoMessage {
return PicoMessage{
Type: msgType,
Timestamp: time.Now().UnixMilli(),
Payload: payload,
}
}
func isThoughtPayload(payload map[string]any) bool {
kind, _ := payload[PayloadKeyKind].(string)
if strings.EqualFold(strings.TrimSpace(kind), MessageKindThought) {
return true
}
// Keep pico_client inbound-compatible with legacy servers that still send
// the pre-kind boolean thought marker.
thought, _ := payload[PayloadKeyThought].(bool)
return thought
}
func newErrorWithPayload(code, message string, extra map[string]any) PicoMessage {
payload := map[string]any{
"code": code,
"message": message,
}
for key, value := range extra {
payload[key] = value
}
return newMessage(TypeError, payload)
}
// newError creates an error PicoMessage.
func newError(code, message string) PicoMessage {
return newErrorWithPayload(code, message, nil)
}
-33
View File
@@ -27,10 +27,6 @@ var rrCounter atomic.Uint64
// CurrentVersion is the latest config schema version
const CurrentVersion = 3
func init() {
initChannel()
}
// Config is the current config structure with version support.
type Config struct {
// Config schema version for migration.
@@ -565,11 +561,6 @@ type DiscordSettings struct {
MentionOnly bool `json:"mention_only" yaml:"-" env:"PICOCLAW_CHANNELS_DISCORD_MENTION_ONLY"`
}
type MaixCamSettings struct {
Host string `json:"host" yaml:"-" env:"PICOCLAW_CHANNELS_MAIXCAM_HOST"`
Port int `json:"port" yaml:"-" env:"PICOCLAW_CHANNELS_MAIXCAM_PORT"`
}
type QQSettings struct {
AppID string `json:"app_id" yaml:"-" env:"PICOCLAW_CHANNELS_QQ_APP_ID"`
AppSecret SecureString `json:"app_secret,omitzero" yaml:"app_secret,omitempty" env:"PICOCLAW_CHANNELS_QQ_APP_SECRET"`
@@ -668,30 +659,6 @@ func (c *WeixinSettings) SetToken(token string) {
c.Token = *NewSecureString(token)
}
type PicoSettings struct {
Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"PICOCLAW_CHANNELS_PICO_TOKEN"`
AllowTokenQuery bool `json:"allow_token_query,omitempty" yaml:"-"`
AllowOrigins []string `json:"allow_origins,omitempty" yaml:"-"`
Streaming StreamingConfig `json:"streaming,omitzero" yaml:"-"`
PingInterval int `json:"ping_interval,omitempty" yaml:"-"`
ReadTimeout int `json:"read_timeout,omitempty" yaml:"-"`
WriteTimeout int `json:"write_timeout,omitempty" yaml:"-"`
MaxConnections int `json:"max_connections,omitempty" yaml:"-"`
}
// SetToken sets the Pico token and marks it as dirty for security saving
func (c *PicoSettings) SetToken(token string) {
c.Token = *NewSecureString(token)
}
type PicoClientSettings struct {
URL string `json:"url" yaml:"-" env:"PICOCLAW_CHANNELS_PICO_CLIENT_URL"`
Token SecureString `json:"token,omitzero" yaml:"token,omitempty" env:"PICOCLAW_CHANNELS_PICO_CLIENT_TOKEN"`
SessionID string `json:"session_id,omitempty" yaml:"-"`
PingInterval int `json:"ping_interval,omitempty" yaml:"-"`
ReadTimeout int `json:"read_timeout,omitempty" yaml:"-"`
}
type IRCSettings struct {
Server string `json:"server" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_SERVER"`
TLS bool `json:"tls" yaml:"-" env:"PICOCLAW_CHANNELS_IRC_TLS"`
+4 -70
View File
@@ -17,8 +17,6 @@ import (
// Channel type constants — single source of truth for all channel type names.
const (
ChannelPico = "pico"
ChannelPicoClient = "pico_client"
ChannelTelegram = "telegram"
ChannelDiscord = "discord"
ChannelFeishu = "feishu"
@@ -33,7 +31,6 @@ const (
ChannelQQ = "qq"
ChannelIRC = "irc"
ChannelVK = "vk"
ChannelMaixCam = "maixcam"
ChannelWhatsApp = "whatsapp"
ChannelWhatsAppNative = "whatsapp_native"
ChannelTeamsWebHook = "teams_webhook"
@@ -41,27 +38,6 @@ const (
ChannelSlackWebHook = "slack_webhook"
)
func initChannel() {
registerSingletonChannel(ChannelPico)
registerSingletonChannel(ChannelPicoClient)
}
// singletonRegistry stores which channel types are singletons (only allow one instance).
// Each channel type should call registerSingletonChannel in its init() if it's a singleton.
var singletonRegistry = make(map[string]struct{})
// registerSingletonChannel marks a channel type as singleton (only one instance allowed).
// Should be called from the channel type's init() function.
func registerSingletonChannel(channelType string) {
singletonRegistry[channelType] = struct{}{}
}
// IsSingletonChannel returns true if the channel type only allows one instance.
func IsSingletonChannel(channelType string) bool {
_, ok := singletonRegistry[channelType]
return ok
}
// RawNode stores raw configuration data as JSON bytes, supporting both JSON and YAML.
// Internally uses json.RawMessage, so Decode always uses json.Unmarshal
// which correctly respects json struct tags.
@@ -506,37 +482,6 @@ func (c ChannelsConfig) SetEnabled(name string, enabled bool) bool {
return true
}
// validateSingletonChannels checks that singleton channel types have at most
// one enabled instance. Returns an error if a singleton type has multiple enabled channels.
func validateSingletonChannels(channels ChannelsConfig) error {
typeCount := make(map[string]int)
typeNames := make(map[string][]string)
for name, bc := range channels {
if !bc.Enabled {
continue
}
t := bc.Type
if t == "" {
t = name
}
if IsSingletonChannel(t) {
typeCount[t]++
typeNames[t] = append(typeNames[t], name)
}
}
for t, count := range typeCount {
if count > 1 {
return fmt.Errorf(
"channel type %q is singleton and does not support multiple instances, found %d enabled instances: %v",
t,
count,
typeNames[t],
)
}
}
return nil
}
// BaseFieldNames are JSON keys that belong to Channel, not to channel-specific settings.
var BaseFieldNames = map[string]struct{}{
"enabled": {},
@@ -660,8 +605,6 @@ func filterSecureFields(r RawNode, secureFields map[string]struct{}) RawNode {
var channelSettingsMu sync.RWMutex
var channelSettingsFactory = map[string]any{
ChannelPico: (PicoSettings{}),
ChannelPicoClient: (PicoClientSettings{}),
ChannelTelegram: (TelegramSettings{}),
ChannelDiscord: (DiscordSettings{}),
ChannelFeishu: (FeishuSettings{}),
@@ -676,7 +619,6 @@ var channelSettingsFactory = map[string]any{
ChannelQQ: (QQSettings{}),
ChannelIRC: (IRCSettings{}),
ChannelVK: (VKSettings{}),
ChannelMaixCam: (MaixCamSettings{}),
ChannelWhatsApp: (WhatsAppSettings{}),
ChannelWhatsAppNative: (WhatsAppSettings{}),
ChannelTeamsWebHook: (TeamsWebhookSettings{}),
@@ -717,16 +659,15 @@ func isValidChannelType(channelType string) bool {
}
// InitChannelList validates and initializes all channels in the ChannelsConfig.
// It performs three steps:
// It performs two steps:
// 1. Validates that each channel has a non-empty Type
// 2. Validates singleton constraints
// 3. Decodes Settings into the correct typed struct based on Type,
// so that b.extend contains the actual settings (e.g., PicoSettings)
// 2. Decodes Settings into the correct typed struct based on Type,
// so that b.extend contains the actual settings (e.g., TelegramSettings)
//
// After calling this method, callers can safely use b.extend via Decode()
// without re-parsing raw Settings.
func InitChannelList(channels ChannelsConfig) error {
// Step 1 & 3: validate type and decode into typed settings
// Validate type and decode into typed settings.
for name, bc := range channels {
if bc == nil {
delete(channels, name)
@@ -757,11 +698,6 @@ func InitChannelList(channels ChannelsConfig) error {
}
}
// Step 2: validate singleton constraints
if err := validateSingletonChannels(channels); err != nil {
return err
}
return nil
}
@@ -791,8 +727,6 @@ func applyTelegramStreamingEnvCompat(target any) {
func validateChannelStreamingConfig(channelName string, target any) error {
var streaming StreamingConfig
switch settings := target.(type) {
case *PicoSettings:
streaming = settings.Streaming
case *TelegramSettings:
streaming = settings.Streaming
case *WeComSettings:
+14 -48
View File
@@ -144,30 +144,6 @@ func TestStreamingConfig_IsChannelGeneric(t *testing.T) {
}
}
func TestPicoSettings_StreamingConfig(t *testing.T) {
raw := RawNode(`{
"token": "test-token",
"streaming": {
"enabled": true,
"throttle_seconds": 2,
"min_growth_chars": 80
}
}`)
ch := &Channel{
Type: ChannelPico,
Enabled: true,
Settings: raw,
}
ch.SetName("pico")
var picoCfg PicoSettings
if err := ch.Decode(&picoCfg); err != nil {
t.Fatalf("Decode() error = %v", err)
}
assert.True(t, picoCfg.Streaming.Enabled)
assert.Equal(t, 2, picoCfg.Streaming.ThrottleSeconds)
assert.Equal(t, 80, picoCfg.Streaming.MinGrowthChars)
}
func TestWeComSettings_StreamingConfig(t *testing.T) {
raw := RawNode(`{
"bot_id": "bot-1",
@@ -192,7 +168,7 @@ func TestWeComSettings_StreamingConfig(t *testing.T) {
assert.Equal(t, 160, wecomCfg.Streaming.MinGrowthChars)
}
func TestPicoStreamingConfig_Defaults(t *testing.T) {
func TestStreamingConfig_Defaults(t *testing.T) {
cfg := StreamingConfig{Enabled: true}
got := cfg.WithDefaults(1, 40)
assert.Equal(t, 1, got.ThrottleSeconds)
@@ -220,10 +196,10 @@ func TestInitChannelList_TelegramStreamingEnvCompatibility(t *testing.T) {
Enabled: true,
Settings: RawNode(`{"token":"telegram-token"}`),
},
"pico": {
Type: ChannelPico,
"wecom": {
Type: ChannelWeCom,
Enabled: true,
Settings: RawNode(`{"token":"pico-token"}`),
Settings: RawNode(`{"bot_id":"bot-1"}`),
},
}
if err := InitChannelList(channels); err != nil {
@@ -239,14 +215,14 @@ func TestInitChannelList_TelegramStreamingEnvCompatibility(t *testing.T) {
assert.Equal(t, 3, tgCfg.Streaming.ThrottleSeconds)
assert.Equal(t, 120, tgCfg.Streaming.MinGrowthChars)
picoDecoded, err := channels["pico"].GetDecoded()
wecomDecoded, err := channels["wecom"].GetDecoded()
if err != nil {
t.Fatalf("pico GetDecoded() error = %v", err)
t.Fatalf("wecom GetDecoded() error = %v", err)
}
picoCfg := picoDecoded.(*PicoSettings)
assert.False(t, picoCfg.Streaming.Enabled)
assert.Equal(t, 0, picoCfg.Streaming.ThrottleSeconds)
assert.Equal(t, 0, picoCfg.Streaming.MinGrowthChars)
wecomCfg := wecomDecoded.(*WeComSettings)
assert.False(t, wecomCfg.Streaming.Enabled)
assert.Equal(t, 0, wecomCfg.Streaming.ThrottleSeconds)
assert.Equal(t, 0, wecomCfg.Streaming.MinGrowthChars)
}
func TestInitChannelList_RejectsNegativeStreamingDeliveryValues(t *testing.T) {
@@ -255,16 +231,6 @@ func TestInitChannelList_RejectsNegativeStreamingDeliveryValues(t *testing.T) {
channelType string
settings string
}{
{
name: "pico throttle",
channelType: ChannelPico,
settings: `{"token":"pico-token","streaming":{"enabled":true,"throttle_seconds":-1}}`,
},
{
name: "pico growth",
channelType: ChannelPico,
settings: `{"token":"pico-token","streaming":{"enabled":true,"min_growth_chars":-1}}`,
},
{
name: "telegram throttle",
channelType: ChannelTelegram,
@@ -338,11 +304,11 @@ func TestChannel_JSON_Marshal_SecureMasked(t *testing.T) {
func TestChannel_JSON_Marshal_OmitsUnconfiguredStreaming(t *testing.T) {
ch := Channel{
Enabled: true,
Type: ChannelPico,
name: "pico",
Settings: mustParseRawNode(`{"ping_interval":30}`),
Type: ChannelWeCom,
name: "wecom",
Settings: mustParseRawNode(`{"bot_id":"bot-1"}`),
}
var cfg PicoSettings
var cfg WeComSettings
require.NoError(t, ch.Decode(&cfg))
data, err := json.MarshalIndent(ch, "", " ")
+43 -105
View File
@@ -1002,21 +1002,6 @@ func TestDefaultConfig_ChannelStreamingDisabled(t *testing.T) {
t.Fatal("DefaultConfig().telegram.settings.streaming.enabled should be false")
}
pico := cfg.Channels.Get(ChannelPico)
if pico == nil {
t.Fatal("DefaultConfig() missing pico channel")
}
decoded, err = pico.GetDecoded()
if err != nil {
t.Fatalf("pico GetDecoded() error = %v", err)
}
picoSettings, ok := decoded.(*PicoSettings)
if !ok {
t.Fatalf("pico settings type = %T, want *PicoSettings", decoded)
}
if !picoSettings.Streaming.Enabled {
t.Fatal("DefaultConfig().pico.settings.streaming.enabled should be true")
}
}
func TestDefaultConfig_DeltaChatExample(t *testing.T) {
@@ -1051,52 +1036,6 @@ func TestDefaultConfig_DeltaChatExample(t *testing.T) {
}
}
func TestValidateSingletonChannels_RejectsMultipleInstances(t *testing.T) {
channels := ChannelsConfig{
"pico1": &Channel{Enabled: true, Type: ChannelPico},
"pico2": &Channel{Enabled: true, Type: ChannelPico},
}
err := validateSingletonChannels(channels)
if err == nil {
t.Fatal("expected error for multiple pico channels, got nil")
}
if !strings.Contains(err.Error(), "singleton") {
t.Fatalf("expected singleton error, got: %v", err)
}
}
func TestValidateSingletonChannels_AllowsSingleInstance(t *testing.T) {
channels := ChannelsConfig{
"pico1": &Channel{Enabled: true, Type: ChannelPico},
}
err := validateSingletonChannels(channels)
if err != nil {
t.Fatalf("expected no error for single pico channel, got: %v", err)
}
}
func TestValidateSingletonChannels_IgnoresDisabledInstances(t *testing.T) {
channels := ChannelsConfig{
"pico1": &Channel{Enabled: true, Type: ChannelPico},
"pico2": &Channel{Enabled: false, Type: ChannelPico},
}
err := validateSingletonChannels(channels)
if err != nil {
t.Fatalf("expected no error when only one pico channel is enabled, got: %v", err)
}
}
func TestValidateSingletonChannels_AllowsMultiInstanceTypes(t *testing.T) {
channels := ChannelsConfig{
"tg1": &Channel{Enabled: true, Type: ChannelTelegram},
"tg2": &Channel{Enabled: true, Type: ChannelTelegram},
}
err := validateSingletonChannels(channels)
if err != nil {
t.Fatalf("telegram should allow multiple instances, got error: %v", err)
}
}
// TestDefaultConfig_WebTools verifies web tools config
func TestDefaultConfig_WebTools(t *testing.T) {
cfg := DefaultConfig()
@@ -1190,49 +1129,6 @@ func TestSaveConfig_PreservesDisabledTelegramPlaceholder(t *testing.T) {
}
}
func TestSaveConfig_PreservesExplicitDisabledPicoStreaming(t *testing.T) {
tmpDir := t.TempDir()
path := filepath.Join(tmpDir, "config.json")
cfg := DefaultConfig()
pico := cfg.Channels.Get(ChannelPico)
if pico == nil {
t.Fatal("DefaultConfig() missing pico channel")
}
pico.Settings = RawNode(`{"streaming":{"enabled":false}}`)
if err := SaveConfig(path, cfg); err != nil {
t.Fatalf("SaveConfig failed: %v", err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile failed: %v", err)
}
if !strings.Contains(string(data), `"streaming"`) || !strings.Contains(string(data), `"enabled": false`) {
t.Fatalf("saved config should preserve explicit disabled pico streaming, got:\n%s", string(data))
}
loaded, err := LoadConfig(path)
if err != nil {
t.Fatalf("LoadConfig failed: %v", err)
}
loadedPico := loaded.Channels.Get(ChannelPico)
if loadedPico == nil {
t.Fatal("loaded config missing pico channel")
}
decoded, err := loadedPico.GetDecoded()
if err != nil {
t.Fatalf("pico GetDecoded() error = %v", err)
}
settings, ok := decoded.(*PicoSettings)
if !ok {
t.Fatalf("pico settings type = %T, want *PicoSettings", decoded)
}
if settings.Streaming.Enabled {
t.Fatal("explicit disabled pico streaming should remain disabled after SaveConfig/LoadConfig round-trip")
}
}
// TestSaveConfig_FiltersVirtualModels verifies that SaveConfig does not write
// virtual models (generated by expandMultiKeyModels) to the config file.
func TestSaveConfig_FiltersVirtualModels(t *testing.T) {
@@ -3251,7 +3147,6 @@ func testChannelsConfigWithTokens() ChannelsConfig {
{"dingtalk", DingTalkSettings{ClientSecret: *NewSecureString("dingtalk-client-secret")}},
{"onebot", OneBotSettings{AccessToken: *NewSecureString("onebot-access-token")}},
{"wecom", WeComSettings{Secret: *NewSecureString("wecom-secret")}},
{"pico", PicoSettings{Token: *NewSecureString("pico-token-abc123")}},
{
"irc",
IRCSettings{
@@ -3269,3 +3164,46 @@ func testChannelsConfigWithTokens() ChannelsConfig {
}
return channels
}
func TestSaveConfig_PreservesExplicitDisabledTelegramStreaming(t *testing.T) {
tmpDir := t.TempDir()
path := filepath.Join(tmpDir, "config.json")
cfg := DefaultConfig()
telegram := cfg.Channels.Get(ChannelTelegram)
if telegram == nil {
t.Fatal("DefaultConfig() missing telegram channel")
}
telegram.Settings = RawNode(`{"streaming":{"enabled":false}}`)
if err := SaveConfig(path, cfg); err != nil {
t.Fatalf("SaveConfig failed: %v", err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile failed: %v", err)
}
if !strings.Contains(string(data), `"streaming"`) || !strings.Contains(string(data), `"enabled": false`) {
t.Fatalf("saved config should preserve explicit disabled telegram streaming, got:\n%s", string(data))
}
loaded, err := LoadConfig(path)
if err != nil {
t.Fatalf("LoadConfig failed: %v", err)
}
loadedTelegram := loaded.Channels.Get(ChannelTelegram)
if loadedTelegram == nil {
t.Fatal("loaded config missing telegram channel")
}
decoded, err := loadedTelegram.GetDecoded()
if err != nil {
t.Fatalf("telegram GetDecoded() error = %v", err)
}
settings, ok := decoded.(*TelegramSettings)
if !ok {
t.Fatalf("telegram settings type = %T, want *TelegramSettings", decoded)
}
if settings.Streaming.Enabled {
t.Fatal("explicit disabled telegram streaming should remain disabled after SaveConfig/LoadConfig round-trip")
}
}
-12
View File
@@ -533,9 +533,6 @@ func defaultChannels() ChannelsConfig {
},
"feishu": map[string]any{},
"discord": map[string]any{},
"maixcam": map[string]any{
"settings": map[string]any{"host": "0.0.0.0", "port": 18790},
},
"qq": map[string]any{
"settings": map[string]any{"max_message_length": 2000},
},
@@ -582,15 +579,6 @@ func defaultChannels() ChannelsConfig {
"cdn_base_url": "https://novac2c.cdn.weixin.qq.com/c2c",
},
},
"pico": map[string]any{
"settings": map[string]any{
"ping_interval": 30,
"read_timeout": 60,
"write_timeout": 10,
"max_connections": 100,
"streaming": map[string]any{"enabled": true},
},
},
"irc": map[string]any{
"settings": map[string]any{
"server": "",
-10
View File
@@ -250,9 +250,6 @@ func TestAllSecurityKeysAccessible(t *testing.T) {
"enabled": true,
"bot_id": "test_wecom_bot_id"
},
"pico": {
"enabled": true
},
"irc": {
"enabled": true,
"server": "irc.example.com",
@@ -319,8 +316,6 @@ channels:
access_token: "onebot_test_access_token"
wecom:
secret: "wecom_test_secret"
pico:
token: "pico_test_token"
irc:
password: "irc_test_password"
nickserv_password: "irc_test_nickserv_password"
@@ -437,11 +432,6 @@ skills:
t.Logf("WeCom BotID: %s", wcSec.(*WeComSettings).BotID)
t.Logf("WeCom Secret(): %s", secureStr(wcSec.(*WeComSettings).Secret))
// Pico
picoSec := decodeChannel("pico")
assert.Equal(t, "pico_test_token", secureStr(picoSec.(*PicoSettings).Token))
t.Logf("Pico Token(): %s", secureStr(picoSec.(*PicoSettings).Token))
// IRC
ircSec := decodeChannel("irc")
assert.Equal(t, "irc_test_password", secureStr(ircSec.(*IRCSettings).Password))
-6
View File
@@ -115,7 +115,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) {
{"feishu", `{"enabled":true,"settings":{"app_id":"feishu_app_id","app_secret":"feishu_app_secret"}}`},
{"discord", `{"enabled":true,"settings":{"token":"discord_token"}}`},
{"qq", `{"enabled":true,"settings":{"app_secret":"qq_app_secret"}}`},
{"pico_client", `{"enabled":true,"settings":{"token":"pico_client_token"}}`},
} {
bc := &Channel{}
json.Unmarshal([]byte(d.raw), bc)
@@ -129,8 +128,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) {
bc.Decode(&DiscordSettings{})
case "feishu":
bc.Decode(&FeishuSettings{})
case "pico_client":
bc.Decode(&PicoClientSettings{})
}
chs[d.name] = bc
}
@@ -185,7 +182,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) {
assert.Contains(t, getSetting("feishu")["app_secret"], "feishu_app_secret")
assert.Contains(t, getSetting("discord")["token"], "discord_token")
assert.Contains(t, getSetting("qq")["app_secret"], "qq_app_secret")
assert.Contains(t, getSetting("pico_client")["token"], "pico_client_token")
// Rewrite file with deterministic content for load test (use channel_list)
yamlOutput := `channel_list:
@@ -197,8 +193,6 @@ func TestSaveAndLoadSecurityConfig(t *testing.T) {
token: discord_token
qq:
app_secret: qq_app_secret
pico_client:
token: pico_client_token
model_list:
model1:0:
api_keys:
-2
View File
@@ -25,10 +25,8 @@ import (
_ "github.com/sipeed/picoclaw/pkg/channels/feishu"
_ "github.com/sipeed/picoclaw/pkg/channels/irc"
_ "github.com/sipeed/picoclaw/pkg/channels/line"
_ "github.com/sipeed/picoclaw/pkg/channels/maixcam"
_ "github.com/sipeed/picoclaw/pkg/channels/mqtt"
_ "github.com/sipeed/picoclaw/pkg/channels/onebot"
_ "github.com/sipeed/picoclaw/pkg/channels/pico"
_ "github.com/sipeed/picoclaw/pkg/channels/qq"
_ "github.com/sipeed/picoclaw/pkg/channels/slack"
_ "github.com/sipeed/picoclaw/pkg/channels/slack_webhook"
+1 -1
View File
@@ -262,7 +262,7 @@ This file contains tasks for the heartbeat service to check periodically.
- Check for unread messages
- Review upcoming calendar events
- Check device status (e.g., MaixCam)
- Check device status
## Instructions
-1
View File
@@ -17,7 +17,6 @@ var supportedChannels = map[string]bool{
"telegram": true,
"feishu": true,
"discord": true,
"maixcam": true,
"qq": true,
"dingtalk": true,
"slack": true,
@@ -128,7 +128,6 @@ type OpenClawChannels struct {
BlueBubbles *OpenClawBlueBubblesConfig `json:"bluebubbles"`
QQ *OpenClawQQConfig `json:"qq"`
DingTalk *OpenClawDingTalkConfig `json:"dingtalk"`
MaixCam *OpenClawMaixCamConfig `json:"maixcam"`
}
type OpenClawTelegramConfig struct {
@@ -267,14 +266,6 @@ type OpenClawDingTalkConfig struct {
Enabled *bool `json:"enabled"`
}
type OpenClawMaixCamConfig struct {
Host *string `json:"host"`
Port *int `json:"port"`
DmPolicy *string `json:"dmPolicy"`
AllowFrom []string `json:"allowFrom"`
Enabled *bool `json:"enabled"`
}
type OpenClawSkills struct {
Entries map[string]json.RawMessage `json:"entries"`
Load json.RawMessage `json:"load"`
@@ -631,7 +622,6 @@ type ChannelsConfig struct {
Telegram TelegramConfig `json:"telegram"`
Feishu FeishuConfig `json:"feishu"`
Discord DiscordConfig `json:"discord"`
MaixCam MaixCamConfig `json:"maixcam"`
QQ QQConfig `json:"qq"`
DingTalk DingTalkConfig `json:"dingtalk"`
Slack SlackConfig `json:"slack"`
@@ -669,13 +659,6 @@ type DiscordConfig struct {
AllowFrom []string `json:"allow_from"`
}
type MaixCamConfig struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int `json:"port"`
AllowFrom []string `json:"allow_from"`
}
type QQConfig struct {
Enabled bool `json:"enabled"`
AppID string `json:"app_id"`
@@ -872,19 +855,6 @@ func (c *OpenClawConfig) convertChannels(warnings *[]string) ChannelsConfig {
}
}
if c.Channels.MaixCam != nil && supportedChannels["maixcam"] {
channels.MaixCam = MaixCamConfig{
Enabled: true,
AllowFrom: c.Channels.MaixCam.AllowFrom,
}
if c.Channels.MaixCam.Host != nil {
channels.MaixCam.Host = *c.Channels.MaixCam.Host
}
if c.Channels.MaixCam.Port != nil {
channels.MaixCam.Port = *c.Channels.MaixCam.Port
}
}
if c.Channels.Matrix != nil && supportedChannels["matrix"] {
enabled := c.Channels.Matrix.Enabled == nil || *c.Channels.Matrix.Enabled
channels.Matrix = MatrixConfig{
@@ -1064,12 +1034,6 @@ func (c ChannelsConfig) ToStandardChannels() config.ChannelsConfig {
return m
}())
setChannel(channels, "maixcam", map[string]any{
"enabled": c.MaixCam.Enabled,
"host": c.MaixCam.Host,
"port": c.MaixCam.Port,
})
setChannel(channels, "qq", func() map[string]any {
m := map[string]any{
"enabled": c.QQ.Enabled,
@@ -329,11 +329,6 @@ func TestConvertToPicoClawWithQQAndDingTalk(t *testing.T) {
"appId": "ding-app-id",
"appSecret": "ding-app-secret"
},
"maixcam": {
"enabled": true,
"host": "192.168.1.100",
"port": 9000
},
"slack": {
"enabled": true,
"botToken": "xoxb-test",
@@ -371,16 +366,6 @@ func TestConvertToPicoClawWithQQAndDingTalk(t *testing.T) {
t.Errorf("expected dingtalk client ID 'ding-app-id', got '%s'", picoCfg.Channels.DingTalk.ClientID)
}
if !picoCfg.Channels.MaixCam.Enabled {
t.Error("maixcam should be enabled")
}
if picoCfg.Channels.MaixCam.Host != "192.168.1.100" {
t.Errorf("expected maixcam host '192.168.1.100', got '%s'", picoCfg.Channels.MaixCam.Host)
}
if picoCfg.Channels.MaixCam.Port != 9000 {
t.Errorf("expected maixcam port 9000, got %d", picoCfg.Channels.MaixCam.Port)
}
if !picoCfg.Channels.Slack.Enabled {
t.Error("slack should be enabled")
}
+3 -3
View File
@@ -123,9 +123,9 @@ func TestAllocateRouteSession_PicoDirectAliasesIncludeLegacyChatKey(t *testing.T
allocation := AllocateRouteSession(AllocationInput{
AgentID: "main",
Context: bus.InboundContext{
Channel: "pico",
Channel: "telegram",
Account: "default",
ChatID: "pico:session-123",
ChatID: "telegram:session-123",
ChatType: "direct",
SenderID: "pico-user",
},
@@ -134,7 +134,7 @@ func TestAllocateRouteSession_PicoDirectAliasesIncludeLegacyChatKey(t *testing.T
},
})
if !containsAlias(allocation.SessionAliases, "agent:main:pico:direct:pico:session-123") {
if !containsAlias(allocation.SessionAliases, "agent:main:telegram:direct:telegram:session-123") {
t.Fatalf("SessionAliases = %v, want pico legacy alias", allocation.SessionAliases)
}
}
+4 -4
View File
@@ -264,13 +264,13 @@ func TestJSONLBackend_EnsureSessionMetadata_PromotesLegacyAliasHistory(t *testin
func TestJSONLBackend_EnsureSessionMetadata_PromotesLegacyPicoDirectAliasHistory(t *testing.T) {
b := newBackend(t)
legacyKey := "agent:main:pico:direct:pico:session-123"
legacyKey := "agent:main:telegram:direct:telegram:session-123"
b.AddMessage(legacyKey, "user", "legacy pico history")
scope := &session.SessionScope{
Version: session.ScopeVersionV1,
AgentID: "main",
Channel: "pico",
Channel: "telegram",
Account: "default",
Dimensions: []string{"sender"},
Values: map[string]string{
@@ -280,9 +280,9 @@ func TestJSONLBackend_EnsureSessionMetadata_PromotesLegacyPicoDirectAliasHistory
allocation := session.AllocateRouteSession(session.AllocationInput{
AgentID: "main",
Context: bus.InboundContext{
Channel: "pico",
Channel: "telegram",
Account: "default",
ChatID: "pico:session-123",
ChatID: "telegram:session-123",
ChatType: "direct",
SenderID: "pico-user",
},