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",
},