feat: support fresh IM sessions and OpenAI reasoning controls
支持 /new 清空会话或携带新问题执行,忙碌时拒绝并保留原任务状态。 修复路由会话隔离及旧摘要回写,完善 OpenAI reasoning.effort 和 temperature 处理。 补充中英文文档与测试;相关包回归、race、lint 和 Gateway 构建通过。
This commit is contained in:
1 parent
1190c27751
commit
a7dba6859b
34 files changed
+998
-129
No files matched your search
@@ -199,6 +199,8 @@ dammi le ultime news
|
||||
- Generic slash commands are executed through a single path in `pkg/agent/loop.go` via `commands.Executor`.
|
||||
- Channel adapters no longer consume generic commands locally; they forward inbound text to the bus/agent path. Telegram still auto-registers supported commands such as `/start`, `/help`, `/show`, `/list`, `/use`, and `/btw` at startup.
|
||||
- Unknown slash command (for example `/foo`) passes through to normal LLM processing.
|
||||
- `/new` clears the current session's history and summary, like `/clear`. `/new <prompt>` clears them and immediately runs the supplied prompt; subsequent messages continue that fresh conversation. The model, workspace, and system instructions remain active. Spaces, tabs, and newlines can separate the command from its prompt.
|
||||
- If the same session already has a running or queued task, `/new` (with or without a prompt) replies with the current task's name and asks you to retry later. It does not interrupt the task or queue the new prompt. Other sessions can still use `/new`.
|
||||
- Registered but unsupported command on the current channel (for example `/show` on WhatsApp) returns an explicit user-facing error and stops further processing.
|
||||
|
||||
### Session Isolation
|
||||
|
||||
@@ -193,6 +193,8 @@ dammi le ultime news
|
||||
- 通用斜杠命令通过 `pkg/agent/loop.go` 中的 `commands.Executor` 统一执行。
|
||||
- Channel 适配器不再在本地消费通用命令;它们只负责把入站文本转发到 bus/agent 路径。Telegram 仍会在启动时自动注册其支持的命令菜单,例如 `/start`、`/help`、`/show`、`/list`、`/use` 和 `/btw`。
|
||||
- 未注册的斜杠命令(例如 `/foo`)会透传给 LLM 按普通输入处理。
|
||||
- `/new` 与 `/clear` 一样,清除当前会话的历史和摘要。`/new <prompt>` 会先清除,再立即执行后面的新问题,后续消息继续这段新对话。当前模型、工作区和系统提示保持生效;命令与问题之间可以使用空格、制表符或换行分隔。
|
||||
- 如果同一会话已有正在执行或等待执行的任务,`/new`(包括带新问题的形式)会回复当前任务名称,提示稍后重试;不会打断旧任务,也不会将新问题加入队列。其他会话仍可使用 `/new`。
|
||||
- 已注册但当前 channel 不支持的命令(例如 WhatsApp 上的 `/show`)会返回明确的用户可见错误,并停止后续处理。
|
||||
|
||||
### Session 隔离
|
||||
|
||||
@@ -254,10 +254,13 @@ Notes that matter:
|
||||
"model_name": "gpt-5.4",
|
||||
"provider": "openai",
|
||||
"model": "gpt-5.4",
|
||||
"api_keys": ["sk-..."]
|
||||
"api_keys": ["sk-..."],
|
||||
"thinking_level": "high"
|
||||
}
|
||||
```
|
||||
|
||||
For OpenAI Responses models that support reasoning, `thinking_level` maps to `reasoning.effort`: `off` becomes `none`, `low`, `medium`, `high`, and `xhigh` pass through, and `adaptive` uses the model default. Supported levels vary by model. PicoClaw omits its default `temperature` when reasoning is enabled.
|
||||
|
||||
**NEAR AI Cloud**
|
||||
|
||||
```json
|
||||
|
||||
@@ -187,10 +187,13 @@ PicoClaw 按下面的规则解析 `provider` 和最终发给上游的模型 ID
|
||||
"model_name": "gpt-5.4",
|
||||
"provider": "openai",
|
||||
"model": "gpt-5.4",
|
||||
"api_keys": ["sk-..."]
|
||||
"api_keys": ["sk-..."],
|
||||
"thinking_level": "high"
|
||||
}
|
||||
```
|
||||
|
||||
对于支持推理的 OpenAI Responses 模型,`thinking_level` 会映射为 `reasoning.effort`:`off` 对应 `none`,`low`、`medium`、`high`、`xhigh` 原样传递,`adaptive` 使用模型默认值。各模型支持的级别可能不同。启用思考时,PicoClaw 会省略默认的 `temperature` 参数。
|
||||
|
||||
**火山引擎(Doubao)**
|
||||
|
||||
```json
|
||||
|
||||
+8
-3
@@ -132,6 +132,7 @@ const (
|
||||
messageKindToolFeedback = "tool_feedback"
|
||||
messageKindToolCalls = "tool_calls"
|
||||
outboundKindFinal = "final"
|
||||
outboundKindCommandReply = "command_reply"
|
||||
metadataKeyAccountID = "account_id"
|
||||
metadataKeyGuildID = "guild_id"
|
||||
metadataKeyTeamID = "team_id"
|
||||
@@ -185,10 +186,14 @@ func (al *AgentLoop) Run(ctx context.Context) error {
|
||||
// during turn setup. Each placeholder has a unique turnID to prevent
|
||||
// cross-worker cleanup issues.
|
||||
placeholder := &turnState{
|
||||
turnID: makePendingTurnID(sessionKey, al.turnSeq.Add(1)),
|
||||
phase: TurnPhaseSetup,
|
||||
turnID: makePendingTurnID(sessionKey, al.turnSeq.Add(1)),
|
||||
phase: TurnPhaseSetup,
|
||||
userMessage: msg.Content,
|
||||
}
|
||||
if _, loaded := al.activeTurnStates.LoadOrStore(sessionKey, placeholder); loaded {
|
||||
if active, loaded := al.activeTurnStates.LoadOrStore(sessionKey, placeholder); loaded {
|
||||
if al.tryRejectNewCommand(ctx, msg, sessionKey, active.(*turnState)) {
|
||||
continue
|
||||
}
|
||||
if al.tryHandleStopCommand(ctx, msg, sessionKey) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -393,6 +393,18 @@ func (al *AgentLoop) buildCommandsRuntime(
|
||||
return al.contextManager.Clear(ctx, opts.SessionKey)
|
||||
}
|
||||
|
||||
rt.StartNewConversation = func(ctx context.Context, prompt string) (string, error) {
|
||||
if err := rt.ClearHistory(); err != nil {
|
||||
return "", fmt.Errorf("failed to clear chat history: %w", err)
|
||||
}
|
||||
if prompt == "" {
|
||||
return "Chat history cleared!", nil
|
||||
}
|
||||
opts.Dispatch.UserMessage = prompt
|
||||
opts.UserMessage = prompt
|
||||
return al.runMessagePrompt(ctx, agent, *opts)
|
||||
}
|
||||
|
||||
rt.AskSideQuestion = func(ctx context.Context, question string) (string, error) {
|
||||
return al.askSideQuestion(ctx, agent, opts, question)
|
||||
}
|
||||
|
||||
@@ -205,6 +205,10 @@ func (al *AgentLoop) processMessage(ctx context.Context, msg bus.InboundMessage)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
return al.runMessagePrompt(ctx, agent, opts)
|
||||
}
|
||||
|
||||
func (al *AgentLoop) runMessagePrompt(ctx context.Context, agent *AgentInstance, opts processOptions) (string, error) {
|
||||
if pending := al.takePendingSkills(opts.Dispatch.SessionKey); len(pending) > 0 {
|
||||
opts.ForcedSkills = append(opts.ForcedSkills, pending...)
|
||||
logger.InfoCF("agent", "Applying pending skill override",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/commands"
|
||||
)
|
||||
|
||||
// A busy session must reject /new before it can enter the steering queue.
|
||||
func (al *AgentLoop) tryRejectNewCommand(
|
||||
ctx context.Context,
|
||||
msg bus.InboundMessage,
|
||||
sessionKey string,
|
||||
active *turnState,
|
||||
) bool {
|
||||
if name, ok := commands.CommandName(msg.Content); !ok || name != "new" {
|
||||
return false
|
||||
}
|
||||
|
||||
taskName := []rune(strings.Join(strings.Fields(active.snapshot().UserMessage), " "))
|
||||
if len(taskName) == 0 {
|
||||
taskName = []rune("当前任务")
|
||||
} else if len(taskName) > 80 {
|
||||
taskName = append(taskName[:77], '.', '.', '.')
|
||||
}
|
||||
// This is a separate command reply, not the running task's final answer.
|
||||
// Bypass response deduplication and leave its stream/placeholder intact.
|
||||
outboundCtx := *cloneInboundContext(&msg.Context)
|
||||
outboundCtx.ReplyToMessageID = msg.MessageID
|
||||
if outboundCtx.Raw == nil {
|
||||
outboundCtx.Raw = make(map[string]string)
|
||||
}
|
||||
outboundCtx.Raw[metadataKeyOutboundKind] = outboundKindCommandReply
|
||||
al.bus.PublishOutbound(ctx, bus.OutboundMessage{
|
||||
Context: outboundCtx,
|
||||
SessionKey: sessionKey,
|
||||
Content: fmt.Sprintf("当前有个「%s」任务在执行,请待会再试。", string(taskName)),
|
||||
})
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/providers"
|
||||
)
|
||||
|
||||
func newConversationTestLoop(t *testing.T, provider providers.LLMProvider) (*AgentLoop, *bus.MessageBus) {
|
||||
t.Helper()
|
||||
cfg := &config.Config{
|
||||
Agents: config.AgentsConfig{Defaults: config.AgentDefaults{
|
||||
Workspace: t.TempDir(), ModelName: "test-model", MaxTokens: 4096,
|
||||
ContextWindow: 32768, MaxToolIterations: 5,
|
||||
}},
|
||||
Session: config.SessionConfig{Dimensions: []string{"chat"}},
|
||||
}
|
||||
msgBus := bus.NewMessageBus()
|
||||
al := NewAgentLoop(cfg, msgBus, provider)
|
||||
t.Cleanup(al.Close)
|
||||
return al, msgBus
|
||||
}
|
||||
|
||||
func newConversationTestMessage(content, chatID string) bus.InboundMessage {
|
||||
return testInboundMessage(bus.InboundMessage{
|
||||
Context: bus.InboundContext{Channel: "telegram", ChatID: chatID, ChatType: "direct", SenderID: "user1"},
|
||||
Content: content,
|
||||
})
|
||||
}
|
||||
|
||||
func TestProcessMessage_NewConversation(t *testing.T) {
|
||||
var calls [][]providers.Message
|
||||
provider := &capturingMockProvider{response: "新回答", captureFn: func(messages []providers.Message) {
|
||||
calls = append(calls, append([]providers.Message(nil), messages...))
|
||||
}}
|
||||
al, _ := newConversationTestLoop(t, provider)
|
||||
agent := al.registry.GetDefaultAgent()
|
||||
msg := newConversationTestMessage("/new", "chat1")
|
||||
route, _, err := al.resolveMessageRoute(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := al.allocateRouteSession(route, msg).SessionKey
|
||||
agent.Sessions.AddMessage(key, "user", "旧对话暗号")
|
||||
agent.Sessions.SetSummary(key, "旧摘要暗号")
|
||||
|
||||
reply, err := al.processMessage(t.Context(), msg)
|
||||
if err != nil || reply != "Chat history cleared!" || len(calls) != 0 {
|
||||
t.Fatalf("/new reply = %q, error = %v, calls = %d", reply, err, len(calls))
|
||||
}
|
||||
if len(agent.Sessions.GetHistory(key)) != 0 || agent.Sessions.GetSummary(key) != "" {
|
||||
t.Fatal("/new did not clear history and summary")
|
||||
}
|
||||
|
||||
// Re-seed old state to verify that /new with a prompt also performs the reset.
|
||||
agent.Sessions.AddMessage(key, "user", "旧对话暗号")
|
||||
agent.Sessions.SetSummary(key, "旧摘要暗号")
|
||||
for i, prompt := range []string{"帮我查查今天成都的天气", "看看今天有啥新咖啡"} {
|
||||
msg.Content = "/new " + prompt
|
||||
reply, err = al.processMessage(t.Context(), msg)
|
||||
if err != nil || reply != "新回答" || len(calls) != i+1 {
|
||||
t.Fatalf("reply = %q, error = %v, calls = %d", reply, err, len(calls))
|
||||
}
|
||||
messages := calls[i]
|
||||
var userMessages []string
|
||||
for _, message := range messages {
|
||||
if strings.Contains(message.Content, "旧对话暗号") || strings.Contains(message.Content, "旧摘要暗号") {
|
||||
t.Fatalf("old context leaked: %+v", messages)
|
||||
}
|
||||
if message.Role == "user" {
|
||||
userMessages = append(userMessages, message.Content)
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(userMessages, []string{prompt}) {
|
||||
t.Fatalf("user messages = %q, want only %q", userMessages, prompt)
|
||||
}
|
||||
history := agent.Sessions.GetHistory(key)
|
||||
if len(history) != 2 || history[0].Content != prompt || history[1].Content != "新回答" {
|
||||
t.Fatalf("new history = %+v", history)
|
||||
}
|
||||
}
|
||||
|
||||
msg.Content = "展开说说"
|
||||
if _, err := al.processMessage(t.Context(), msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var userMessages []string
|
||||
for _, message := range calls[2] {
|
||||
if message.Role == "user" {
|
||||
userMessages = append(userMessages, message.Content)
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(userMessages, []string{"看看今天有啥新咖啡", "展开说说"}) {
|
||||
t.Fatalf("follow-up context = %q", userMessages)
|
||||
}
|
||||
reopened := initSessionStore(filepath.Join(agent.Workspace, "sessions"))
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if history := reopened.GetHistory(key); len(history) != 4 || history[0].Content != "看看今天有啥新咖啡" {
|
||||
t.Fatalf("persisted history = %+v", history)
|
||||
}
|
||||
}
|
||||
|
||||
type newConversationClearFailure struct{ ContextManager }
|
||||
|
||||
func (newConversationClearFailure) Clear(context.Context, string) error {
|
||||
return errors.New("storage unavailable")
|
||||
}
|
||||
|
||||
func TestProcessMessage_NewConversationClearFailure(t *testing.T) {
|
||||
provider := &countingMockProvider{response: "must not run"}
|
||||
al, _ := newConversationTestLoop(t, provider)
|
||||
al.contextManager = newConversationClearFailure{al.contextManager}
|
||||
reply, err := al.processMessage(t.Context(), newConversationTestMessage("/new question", "chat1"))
|
||||
if err != nil || !strings.Contains(reply, "storage unavailable") || provider.calls != 0 {
|
||||
t.Fatalf("reply = %q, error = %v, calls = %d", reply, err, provider.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessMessage_NewConversationPromptIsLiteral(t *testing.T) {
|
||||
provider := &recordingProvider{}
|
||||
al, _ := newConversationTestLoop(t, provider)
|
||||
for _, prompt := range []string{"第一行 内容\n第二行\t内容", "/clear"} {
|
||||
_, err := al.processMessage(t.Context(), newConversationTestMessage("/new@bot\t"+prompt, "chat1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
messages := provider.lastMessages
|
||||
if len(messages) == 0 || messages[len(messages)-1].Content != prompt {
|
||||
t.Fatalf("prompt %q not preserved: %+v", prompt, messages)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessMessage_NewConversationDiscardsPendingSummary(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
provider := &blockingDirectProvider{
|
||||
firstStarted: started, releaseFirst: release, firstResp: "旧摘要暗号", finalResp: "新回答",
|
||||
}
|
||||
al, _ := newConversationTestLoop(t, provider)
|
||||
agent := al.registry.GetDefaultAgent()
|
||||
msg := newConversationTestMessage("/new 新问题", "chat1")
|
||||
route, _, err := al.resolveMessageRoute(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := al.allocateRouteSession(route, msg).SessionKey
|
||||
for range 6 {
|
||||
agent.Sessions.AddMessage(key, "user", "旧问题")
|
||||
agent.Sessions.AddMessage(key, "assistant", "旧回答")
|
||||
}
|
||||
manager := al.contextManager.(*legacyContextManager)
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); manager.summarizeSession(agent, key) }()
|
||||
t.Cleanup(func() {
|
||||
select {
|
||||
case <-release:
|
||||
default:
|
||||
close(release)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("summary did not finish")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("summary did not start")
|
||||
}
|
||||
if reply, err := al.processMessage(t.Context(), msg); err != nil || reply != "新回答" {
|
||||
t.Fatalf("new reply = %q, error = %v", reply, err)
|
||||
}
|
||||
close(release)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("summary did not finish")
|
||||
}
|
||||
if summary := agent.Sessions.GetSummary(key); summary != "" {
|
||||
t.Fatalf("old summary restored: %q", summary)
|
||||
}
|
||||
if history := agent.Sessions.GetHistory(key); len(history) != 2 || history[0].Content != "新问题" {
|
||||
t.Fatalf("old summary altered new history: %+v", history)
|
||||
}
|
||||
}
|
||||
|
||||
func startNewConversationTestLoop(t *testing.T, al *AgentLoop) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- al.Run(ctx) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Errorf("Run() error = %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("Run() did not stop")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func publishNewConversationTestMessage(t *testing.T, msgBus *bus.MessageBus, msg bus.InboundMessage) {
|
||||
t.Helper()
|
||||
if err := msgBus.PublishInbound(t.Context(), msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func receiveNewConversationTestReply(t *testing.T, msgBus *bus.MessageBus) bus.OutboundMessage {
|
||||
t.Helper()
|
||||
select {
|
||||
case msg := <-msgBus.OutboundChan():
|
||||
return msg
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for reply")
|
||||
return bus.OutboundMessage{}
|
||||
}
|
||||
}
|
||||
|
||||
func waitNewConversationTestCondition(t *testing.T, ready func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.NewTimer(5 * time.Second)
|
||||
defer deadline.Stop()
|
||||
ticker := time.NewTicker(time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for !ready() {
|
||||
select {
|
||||
case <-deadline.C:
|
||||
t.Fatal("timed out waiting for session state")
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentLoop_NewConversationRejectsBusySession(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
provider := &blockingDirectProvider{
|
||||
firstStarted: started, releaseFirst: release, firstResp: "原任务完成", finalResp: "其他任务完成",
|
||||
}
|
||||
al, msgBus := newConversationTestLoop(t, provider)
|
||||
al.workerSem = make(chan struct{}, 2)
|
||||
startNewConversationTestLoop(t, al)
|
||||
t.Cleanup(func() {
|
||||
select {
|
||||
case <-release:
|
||||
default:
|
||||
close(release)
|
||||
}
|
||||
})
|
||||
msg := newConversationTestMessage("帮我查天气", "chat1")
|
||||
route, _, err := al.resolveMessageRoute(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := al.allocateRouteSession(route, msg).SessionKey
|
||||
publishNewConversationTestMessage(t, msgBus, msg)
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("original request did not start")
|
||||
}
|
||||
agent := al.registry.GetDefaultAgent()
|
||||
before := agent.Sessions.GetHistory(key)
|
||||
for _, command := range []string{"/new", "/new 新问题"} {
|
||||
msg.Content = command
|
||||
publishNewConversationTestMessage(t, msgBus, msg)
|
||||
reply := receiveNewConversationTestReply(t, msgBus)
|
||||
if reply.Content != "当前有个「帮我查天气」任务在执行,请待会再试。" ||
|
||||
reply.Context.Raw[metadataKeyOutboundKind] != outboundKindCommandReply {
|
||||
t.Fatalf("busy reply = %+v", reply)
|
||||
}
|
||||
if !reflect.DeepEqual(before, agent.Sessions.GetHistory(key)) || al.GetActiveTurnBySession(key) == nil {
|
||||
t.Fatal("/new altered the running task or its history")
|
||||
}
|
||||
if al.pendingSteeringCountForScope(key) != 0 {
|
||||
t.Fatal("/new was queued as steering")
|
||||
}
|
||||
}
|
||||
// A different chat can reset and run its own prompt while chat1 is busy.
|
||||
publishNewConversationTestMessage(t, msgBus, newConversationTestMessage("/new 其他问题", "chat2"))
|
||||
if reply := receiveNewConversationTestReply(t, msgBus); reply.Content != "其他任务完成" || reply.ChatID != "chat2" {
|
||||
t.Fatalf("other chat reply = %+v", reply)
|
||||
}
|
||||
close(release)
|
||||
if reply := receiveNewConversationTestReply(t, msgBus); reply.Content != "原任务完成" {
|
||||
t.Fatalf("original reply = %+v", reply)
|
||||
}
|
||||
waitNewConversationTestCondition(t, func() bool { return al.GetActiveTurnBySession(key) == nil })
|
||||
provider.mu.Lock()
|
||||
calls := provider.calls
|
||||
provider.mu.Unlock()
|
||||
if calls != 2 {
|
||||
t.Fatalf("calls = %d, rejected prompt must not execute", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentLoop_NewConversationRejectsPendingSession(t *testing.T) {
|
||||
provider := &countingMockProvider{response: "原任务完成"}
|
||||
al, msgBus := newConversationTestLoop(t, provider)
|
||||
// Reserve the only worker slot so the first message stays in setup.
|
||||
al.workerSem <- struct{}{}
|
||||
startNewConversationTestLoop(t, al)
|
||||
msg := newConversationTestMessage("等待执行的问题", "chat1")
|
||||
route, _, err := al.resolveMessageRoute(msg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := al.allocateRouteSession(route, msg).SessionKey
|
||||
publishNewConversationTestMessage(t, msgBus, msg)
|
||||
waitNewConversationTestCondition(t, func() bool { return al.GetActiveTurnBySession(key) != nil })
|
||||
msg.Content = "/new 不应该执行"
|
||||
publishNewConversationTestMessage(t, msgBus, msg)
|
||||
if reply := receiveNewConversationTestReply(t, msgBus); reply.Content != "当前有个「等待执行的问题」任务在执行,请待会再试。" {
|
||||
t.Fatalf("pending reply = %+v", reply)
|
||||
}
|
||||
if al.pendingSteeringCountForScope(key) != 0 {
|
||||
t.Fatal("/new was queued")
|
||||
}
|
||||
<-al.workerSem
|
||||
if reply := receiveNewConversationTestReply(t, msgBus); reply.Content != "原任务完成" {
|
||||
t.Fatalf("original reply = %+v", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentLoop_NewConversationRejectsRunningTool(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
provider := &toolCallProvider{
|
||||
toolCalls: []providers.ToolCall{
|
||||
{ID: "call_1", Type: "function", Name: "busy_tool", Arguments: map[string]any{}},
|
||||
},
|
||||
}
|
||||
al, msgBus := newConversationTestLoop(t, provider)
|
||||
al.RegisterTool(&interruptibleTool{name: "busy_tool", started: started})
|
||||
startNewConversationTestLoop(t, al)
|
||||
msg := newConversationTestMessage("工具任务", "chat1")
|
||||
publishNewConversationTestMessage(t, msgBus, msg)
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("tool did not start")
|
||||
}
|
||||
msg.Content = "/new 新问题"
|
||||
publishNewConversationTestMessage(t, msgBus, msg)
|
||||
for {
|
||||
reply := receiveNewConversationTestReply(t, msgBus)
|
||||
if reply.Context.Raw[metadataKeyOutboundKind] == outboundKindCommandReply {
|
||||
if reply.Content != "当前有个「工具任务」任务在执行,请待会再试。" {
|
||||
t.Fatalf("busy reply = %+v", reply)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
provider.mu.Lock()
|
||||
calls := provider.calls
|
||||
provider.mu.Unlock()
|
||||
if calls != 1 {
|
||||
t.Fatalf("calls = %d, running tool must not be canceled", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectNewCommand_UnicodeTaskName(t *testing.T) {
|
||||
al, msgBus := newConversationTestLoop(t, &simpleMockProvider{})
|
||||
active := &turnState{userMessage: strings.Repeat("成", 100) + "\n 天气"}
|
||||
msg := newConversationTestMessage("/NEW@bot question", "chat1")
|
||||
msg.Context.Account, msg.Context.TopicID, msg.MessageID = "bot1", "42", "incoming-1"
|
||||
msg.Context.ReplyHandles = map[string]string{"reply_token": "handle"}
|
||||
if err := al.enqueueSteeringMessage("key", "main", providers.Message{
|
||||
Role: "user", Content: "existing follow-up",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !al.tryRejectNewCommand(t.Context(), msg, "key", active) {
|
||||
t.Fatal("/NEW@bot not recognized")
|
||||
}
|
||||
reply := receiveNewConversationTestReply(t, msgBus)
|
||||
if !utf8.ValidString(reply.Content) || !strings.Contains(reply.Content, strings.Repeat("成", 77)+"...") {
|
||||
t.Fatalf("invalid truncated task name: %q", reply.Content)
|
||||
}
|
||||
if reply.Context.Account != "bot1" || reply.Context.TopicID != "42" ||
|
||||
reply.ReplyToMessageID != "incoming-1" || reply.Context.ReplyHandles["reply_token"] != "handle" {
|
||||
t.Fatalf("reply lost addressing context: %+v", reply.Context)
|
||||
}
|
||||
if al.pendingSteeringCountForScope("key") != 1 {
|
||||
t.Fatal("busy rejection changed the existing steering queue")
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,6 @@ func (al *AgentLoop) stopActiveTurnForSession(sessionKey string) (commands.StopR
|
||||
}
|
||||
|
||||
snap := ts.snapshot()
|
||||
result.TaskName = snap.UserMessage
|
||||
|
||||
if strings.HasPrefix(snap.TurnID, pendingTurnPrefix) {
|
||||
// A pending placeholder means this session is either idle (our own
|
||||
@@ -76,6 +75,7 @@ func (al *AgentLoop) stopActiveTurnForSession(sessionKey string) (commands.StopR
|
||||
// case explicitly, since it knows loaded=true.
|
||||
return result, nil
|
||||
}
|
||||
result.TaskName = snap.UserMessage
|
||||
|
||||
if err := al.HardAbort(sessionKey); err != nil {
|
||||
if al.getActiveTurnState(sessionKey) == nil {
|
||||
|
||||
+111
-90
@@ -3375,110 +3375,131 @@ func TestProcessMessage_CommandOutcomes(t *testing.T) {
|
||||
},
|
||||
Content: "/new",
|
||||
})
|
||||
if newResp != "LLM reply" {
|
||||
if newResp != "Chat history cleared!" {
|
||||
t.Fatalf("unexpected /new reply: %q", newResp)
|
||||
}
|
||||
if provider.calls != 2 {
|
||||
t.Fatalf("LLM should be called for passthrough /new command, calls=%d", provider.calls)
|
||||
if provider.calls != 1 {
|
||||
t.Fatalf("LLM should not be called for /new, calls=%d", provider.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessMessage_ClearCommandClearsRoutedAgentSession(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
cfg := &config.Config{
|
||||
Agents: config.AgentsConfig{
|
||||
Defaults: config.AgentDefaults{
|
||||
Workspace: filepath.Join(workspace, "default"),
|
||||
ModelName: "test-model",
|
||||
MaxTokens: 4096,
|
||||
MaxToolIterations: 10,
|
||||
},
|
||||
List: []config.AgentConfig{
|
||||
{
|
||||
ID: "main",
|
||||
Default: true,
|
||||
Workspace: filepath.Join(workspace, "main"),
|
||||
},
|
||||
{
|
||||
ID: "support",
|
||||
Workspace: filepath.Join(workspace, "support"),
|
||||
},
|
||||
},
|
||||
Dispatch: &config.DispatchConfig{
|
||||
Rules: []config.DispatchRule{
|
||||
{
|
||||
Name: "support-dingtalk",
|
||||
Agent: "support",
|
||||
When: config.DispatchSelector{
|
||||
Channel: "dingtalk",
|
||||
for _, command := range []string{"/clear", "/new", "/new 新问题"} {
|
||||
t.Run(command, func(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
cfg := &config.Config{
|
||||
Agents: config.AgentsConfig{
|
||||
Defaults: config.AgentDefaults{
|
||||
Workspace: filepath.Join(workspace, "default"),
|
||||
ModelName: "test-model",
|
||||
MaxTokens: 4096,
|
||||
MaxToolIterations: 10,
|
||||
},
|
||||
List: []config.AgentConfig{
|
||||
{
|
||||
ID: "main",
|
||||
Default: true,
|
||||
Workspace: filepath.Join(workspace, "main"),
|
||||
},
|
||||
{
|
||||
ID: "support",
|
||||
Workspace: filepath.Join(workspace, "support"),
|
||||
},
|
||||
},
|
||||
Dispatch: &config.DispatchConfig{
|
||||
Rules: []config.DispatchRule{
|
||||
{
|
||||
Name: "support-dingtalk",
|
||||
Agent: "support",
|
||||
When: config.DispatchSelector{
|
||||
Channel: "dingtalk",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Session: config.SessionConfig{
|
||||
Dimensions: []string{"chat"},
|
||||
},
|
||||
}
|
||||
Session: config.SessionConfig{
|
||||
Dimensions: []string{"chat"},
|
||||
},
|
||||
}
|
||||
|
||||
al := NewAgentLoop(cfg, bus.NewMessageBus(), &countingMockProvider{response: "LLM reply"})
|
||||
mainAgent, ok := al.registry.GetAgent("main")
|
||||
if !ok {
|
||||
t.Fatal("expected main agent")
|
||||
}
|
||||
supportAgent, ok := al.registry.GetAgent("support")
|
||||
if !ok {
|
||||
t.Fatal("expected support agent")
|
||||
}
|
||||
provider := &capturingMockProvider{response: "LLM reply", captureFn: func(messages []providers.Message) {
|
||||
for _, message := range messages {
|
||||
if strings.Contains(message.Content, "main history") ||
|
||||
strings.Contains(message.Content, "main summary") ||
|
||||
strings.Contains(message.Content, "support history") ||
|
||||
strings.Contains(message.Content, "support summary") {
|
||||
t.Fatalf("another conversation leaked into /new prompt: %+v", messages)
|
||||
}
|
||||
}
|
||||
}}
|
||||
al := NewAgentLoop(cfg, bus.NewMessageBus(), provider)
|
||||
t.Cleanup(al.Close)
|
||||
mainAgent, ok := al.registry.GetAgent("main")
|
||||
if !ok {
|
||||
t.Fatal("expected main agent")
|
||||
}
|
||||
supportAgent, ok := al.registry.GetAgent("support")
|
||||
if !ok {
|
||||
t.Fatal("expected support agent")
|
||||
}
|
||||
|
||||
msg := testInboundMessage(bus.InboundMessage{
|
||||
Context: bus.InboundContext{
|
||||
Channel: "dingtalk",
|
||||
ChatID: "chat1",
|
||||
ChatType: "direct",
|
||||
SenderID: "user1",
|
||||
},
|
||||
Content: "/clear",
|
||||
})
|
||||
route, routedAgent, err := al.resolveMessageRoute(msg)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveMessageRoute() error = %v", err)
|
||||
}
|
||||
if routedAgent != supportAgent {
|
||||
t.Fatalf("routed agent = %s, want support", routedAgent.ID)
|
||||
}
|
||||
sessionKey := al.allocateRouteSession(route, msg).SessionKey
|
||||
msg := testInboundMessage(bus.InboundMessage{
|
||||
Context: bus.InboundContext{
|
||||
Channel: "dingtalk",
|
||||
ChatID: "chat1",
|
||||
ChatType: "direct",
|
||||
SenderID: "user1",
|
||||
},
|
||||
Content: command,
|
||||
})
|
||||
route, routedAgent, err := al.resolveMessageRoute(msg)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveMessageRoute() error = %v", err)
|
||||
}
|
||||
if routedAgent != supportAgent {
|
||||
t.Fatalf("routed agent = %s, want support", routedAgent.ID)
|
||||
}
|
||||
sessionKey := al.allocateRouteSession(route, msg).SessionKey
|
||||
|
||||
mainHistory := []providers.Message{{Role: "user", Content: "main history"}}
|
||||
supportHistory := []providers.Message{{Role: "user", Content: "support history"}}
|
||||
mainAgent.Sessions.SetHistory(sessionKey, mainHistory)
|
||||
mainAgent.Sessions.SetSummary(sessionKey, "main summary")
|
||||
supportAgent.Sessions.SetHistory(sessionKey, supportHistory)
|
||||
supportAgent.Sessions.SetSummary(sessionKey, "support summary")
|
||||
mainHistory := []providers.Message{{Role: "user", Content: "main history"}}
|
||||
supportHistory := []providers.Message{{Role: "user", Content: "support history"}}
|
||||
mainAgent.Sessions.SetHistory(sessionKey, mainHistory)
|
||||
mainAgent.Sessions.SetSummary(sessionKey, "main summary")
|
||||
supportAgent.Sessions.SetHistory(sessionKey, supportHistory)
|
||||
supportAgent.Sessions.SetSummary(sessionKey, "support summary")
|
||||
|
||||
response, err := al.processMessage(context.Background(), msg)
|
||||
if err != nil {
|
||||
t.Fatalf("processMessage() error = %v", err)
|
||||
}
|
||||
if response != "Chat history cleared!" {
|
||||
t.Fatalf("response = %q, want clear confirmation", response)
|
||||
}
|
||||
response, err := al.processMessage(context.Background(), msg)
|
||||
if err != nil {
|
||||
t.Fatalf("processMessage() error = %v", err)
|
||||
}
|
||||
wantResponse, wantHistory := "Chat history cleared!", 0
|
||||
if command == "/new 新问题" {
|
||||
wantResponse, wantHistory = "LLM reply", 2
|
||||
}
|
||||
if response != wantResponse {
|
||||
t.Fatalf("response = %q, want clear confirmation", response)
|
||||
}
|
||||
|
||||
if got := supportAgent.Sessions.GetHistory(sessionKey); len(got) != 0 {
|
||||
t.Fatalf("support history len = %d, want 0", len(got))
|
||||
}
|
||||
if got := supportAgent.Sessions.GetSummary(sessionKey); got != "" {
|
||||
t.Fatalf("support summary = %q, want empty", got)
|
||||
}
|
||||
if got := mainAgent.Sessions.GetHistory(sessionKey); len(got) != len(mainHistory) {
|
||||
t.Fatalf("main history len = %d, want %d", len(got), len(mainHistory))
|
||||
} else if got[0].Role != mainHistory[0].Role {
|
||||
t.Fatalf("main history[0].Role = %q, want %q", got[0].Role, mainHistory[0].Role)
|
||||
} else if got[0].Content != mainHistory[0].Content {
|
||||
t.Fatalf("main history[0].Content = %q, want %q", got[0].Content, mainHistory[0].Content)
|
||||
}
|
||||
if got := mainAgent.Sessions.GetSummary(sessionKey); got != "main summary" {
|
||||
t.Fatalf("main summary = %q, want %q", got, "main summary")
|
||||
if got := supportAgent.Sessions.GetHistory(sessionKey); len(got) != wantHistory {
|
||||
t.Fatalf("support history len = %d, want %d", len(got), wantHistory)
|
||||
} else if wantHistory > 0 && got[0].Content != "新问题" {
|
||||
t.Fatalf("new prompt = %q", got[0].Content)
|
||||
}
|
||||
if got := supportAgent.Sessions.GetSummary(sessionKey); got != "" {
|
||||
t.Fatalf("support summary = %q, want empty", got)
|
||||
}
|
||||
if got := mainAgent.Sessions.GetHistory(sessionKey); len(got) != len(mainHistory) {
|
||||
t.Fatalf("main history len = %d, want %d", len(got), len(mainHistory))
|
||||
} else if got[0].Role != mainHistory[0].Role {
|
||||
t.Fatalf("main history[0].Role = %q, want %q", got[0].Role, mainHistory[0].Role)
|
||||
} else if got[0].Content != mainHistory[0].Content {
|
||||
t.Fatalf("main history[0].Content = %q, want %q", got[0].Content, mainHistory[0].Content)
|
||||
}
|
||||
if got := mainAgent.Sessions.GetSummary(sessionKey); got != "main summary" {
|
||||
t.Fatalf("main summary = %q, want %q", got, "main summary")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,15 +16,17 @@ import (
|
||||
// as a ContextManager implementation. It is the default when no other
|
||||
// ContextManager is configured.
|
||||
type legacyContextManager struct {
|
||||
al *AgentLoop
|
||||
summarizing sync.Map // dedup for async Compact (post-turn)
|
||||
al *AgentLoop
|
||||
summarizing sync.Map // dedup for async Compact (post-turn)
|
||||
contextMu sync.Mutex
|
||||
resetVersions map[string]uint64 // invalidate summaries started before a reset
|
||||
}
|
||||
|
||||
func (m *legacyContextManager) Assemble(_ context.Context, req *AssembleRequest) (*AssembleResponse, error) {
|
||||
// Legacy: read history from session, return as-is.
|
||||
// Budget enforcement happens in BuildMessages caller via
|
||||
// isOverContextBudget + forceCompression.
|
||||
agent := m.al.registry.GetDefaultAgent()
|
||||
agent := m.al.agentForSession(req.SessionKey)
|
||||
if agent == nil {
|
||||
return &AssembleResponse{}, nil
|
||||
}
|
||||
@@ -63,12 +65,18 @@ func (m *legacyContextManager) Ingest(_ context.Context, _ *IngestRequest) error
|
||||
}
|
||||
|
||||
func (m *legacyContextManager) Clear(_ context.Context, sessionKey string) error {
|
||||
m.contextMu.Lock()
|
||||
defer m.contextMu.Unlock()
|
||||
// Routed (non-default) agents keep history in their own session store,
|
||||
// so resolve the owning agent instead of assuming the default one.
|
||||
agent := m.al.agentForSession(sessionKey)
|
||||
if agent == nil || agent.Sessions == nil {
|
||||
return fmt.Errorf("sessions not initialized")
|
||||
}
|
||||
if m.resetVersions == nil {
|
||||
m.resetVersions = make(map[string]uint64)
|
||||
}
|
||||
m.resetVersions[sessionKey]++
|
||||
agent.Sessions.SetHistory(sessionKey, []providers.Message{})
|
||||
agent.Sessions.SetSummary(sessionKey, "")
|
||||
return agent.Sessions.Save(sessionKey)
|
||||
@@ -77,7 +85,7 @@ func (m *legacyContextManager) Clear(_ context.Context, sessionKey string) error
|
||||
// maybeSummarize triggers summarization if the session history exceeds thresholds.
|
||||
// It runs asynchronously in a goroutine.
|
||||
func (m *legacyContextManager) maybeSummarize(sessionKey string) {
|
||||
agent := m.al.registry.GetDefaultAgent()
|
||||
agent := m.al.agentForSession(sessionKey)
|
||||
if agent == nil {
|
||||
return
|
||||
}
|
||||
@@ -175,8 +183,11 @@ func (m *legacyContextManager) summarizeSession(agent *AgentInstance, sessionKey
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||||
defer cancel()
|
||||
|
||||
m.contextMu.Lock()
|
||||
version := m.resetVersions[sessionKey]
|
||||
history := agent.Sessions.GetHistory(sessionKey)
|
||||
summary := agent.Sessions.GetSummary(sessionKey)
|
||||
m.contextMu.Unlock()
|
||||
|
||||
if len(history) <= 4 {
|
||||
return
|
||||
@@ -245,9 +256,15 @@ func (m *legacyContextManager) summarizeSession(agent *AgentInstance, sessionKey
|
||||
}
|
||||
|
||||
if finalSummary != "" {
|
||||
m.contextMu.Lock()
|
||||
if version != m.resetVersions[sessionKey] {
|
||||
m.contextMu.Unlock()
|
||||
return
|
||||
}
|
||||
agent.Sessions.SetSummary(sessionKey, finalSummary)
|
||||
agent.Sessions.TruncateHistory(sessionKey, keepCount)
|
||||
agent.Sessions.Save(sessionKey)
|
||||
m.contextMu.Unlock()
|
||||
m.al.emitEvent(
|
||||
runtimeevents.KindAgentSessionSummarize,
|
||||
m.al.newTurnEventScope(agent.ID, sessionKey, nil).meta(0, "summarizeSession", "turn.session.summarize"),
|
||||
|
||||
@@ -26,7 +26,7 @@ type ContextManager interface {
|
||||
Ingest(ctx context.Context, req *IngestRequest) error
|
||||
|
||||
// Clear removes all stored context for a session (messages, summaries, etc.).
|
||||
// Called when the user issues /clear or /reset.
|
||||
// Called when the user issues /clear or /new.
|
||||
Clear(ctx context.Context, sessionKey string) error
|
||||
}
|
||||
|
||||
|
||||
@@ -859,6 +859,11 @@ func TestEvolutionBridge_TurnEndUsesExplicitAttemptTrail(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("newEvolutionBridge: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if closeErr := bridge.Close(); closeErr != nil {
|
||||
t.Errorf("Close: %v", closeErr)
|
||||
}
|
||||
})
|
||||
|
||||
err = bridge.OnEvent(context.Background(), Event{
|
||||
Kind: EventKindTurnEnd,
|
||||
|
||||
@@ -8,11 +8,8 @@ import (
|
||||
"github.com/sipeed/picoclaw/pkg/providers"
|
||||
)
|
||||
|
||||
// ThinkingLevel controls how the provider sends thinking parameters.
|
||||
//
|
||||
// - "adaptive": sends {thinking: {type: "adaptive"}} + output_config.effort (Claude 4.6+)
|
||||
// - "low"/"medium"/"high"/"xhigh": sends {thinking: {type: "enabled", budget_tokens: N}} (all models)
|
||||
// - "off": disables thinking
|
||||
// ThinkingLevel requests a provider-specific reasoning effort. Each provider
|
||||
// maps supported levels to its own API parameters.
|
||||
type ThinkingLevel string
|
||||
|
||||
const (
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/commands"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/identity"
|
||||
"github.com/sipeed/picoclaw/pkg/logger"
|
||||
@@ -318,7 +319,10 @@ func (c *BaseChannel) HandleMessageWithContext(
|
||||
// If streaming actually activates, preSend will skip the placeholder edit (streamActive map)
|
||||
// and the typing stop will still be called. This avoids the problem of compile-time interface
|
||||
// checks incorrectly skipping indicators when streaming may not work at runtime.
|
||||
if c.owner != nil && c.placeholderRecorder != nil {
|
||||
command, _ := commands.CommandName(content)
|
||||
// /new may be rejected while a task is running. Do not overwrite that
|
||||
// task's indicators before the agent has made the command decision.
|
||||
if c.owner != nil && c.placeholderRecorder != nil && command != "new" {
|
||||
// Typing
|
||||
if tc, ok := c.owner.(TypingCapable); ok {
|
||||
if stop, err := tc.StartTyping(ctx, deliveryChatID); err == nil {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package channels
|
||||
|
||||
import "github.com/sipeed/picoclaw/pkg/bus"
|
||||
|
||||
// IsCommandReply identifies a reply that must leave the running task's
|
||||
// placeholder, stream, and tool feedback messages intact.
|
||||
func IsCommandReply(msg bus.OutboundMessage) bool {
|
||||
return msg.Context.Raw["outbound_kind"] == "command_reply"
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package channels
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
)
|
||||
|
||||
func TestPreSend_CommandReplyPreservesRunningTurn(t *testing.T) {
|
||||
for _, streaming := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "placeholder", true: "stream"}[streaming], func(t *testing.T) {
|
||||
m := newTestManager()
|
||||
m.RecordPlaceholder("test", "123", "placeholder-1")
|
||||
m.RecordTypingStop("test", "123", func() { t.Error("command reply stopped typing") })
|
||||
m.reactionUndos.Store("test:123", reactionEntry{undo: func() { t.Error("command reply undid reaction") }})
|
||||
streamKey := streamSuppressionKey("test", "123", "session-1")
|
||||
if streaming {
|
||||
m.streamActive.Store(streamKey, true)
|
||||
m.streamAuxiliaryTombstones.Store(streamKey, time.Now())
|
||||
}
|
||||
ch := &mockChannel{}
|
||||
msg := testOutboundMessage(bus.OutboundMessage{
|
||||
Context: bus.InboundContext{Channel: "test", ChatID: "123", Raw: map[string]string{
|
||||
"outbound_kind": "command_reply",
|
||||
}},
|
||||
SessionKey: "session-1",
|
||||
Content: "当前有个任务在执行,请待会再试。",
|
||||
})
|
||||
if _, handled := m.preSend(context.Background(), "test", msg, ch); handled {
|
||||
t.Fatal("command reply should be sent as a separate message")
|
||||
}
|
||||
if _, ok := m.placeholders.Load("test:123"); !ok || ch.editedMessages != 0 {
|
||||
t.Fatal("command reply consumed the running turn's placeholder")
|
||||
}
|
||||
if _, ok := m.typingStops.Load("test:123"); !ok {
|
||||
t.Fatal("command reply consumed the typing state")
|
||||
}
|
||||
if _, ok := m.reactionUndos.Load("test:123"); !ok {
|
||||
t.Fatal("command reply consumed the reaction state")
|
||||
}
|
||||
if streaming {
|
||||
if _, ok := m.streamActive.Load(streamKey); !ok || !m.streamAuxiliaryTombstoneActive(streamKey) {
|
||||
t.Fatal("command reply changed stream finalization state")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseChannel_NewDoesNotReplaceRunningIndicators(t *testing.T) {
|
||||
msgBus := bus.NewMessageBus()
|
||||
ch := &mockChannel{BaseChannel: *NewBaseChannel("test", nil, msgBus, []string{"*"})}
|
||||
m := newTestManager()
|
||||
ch.SetOwner(ch)
|
||||
ch.SetPlaceholderRecorder(m)
|
||||
m.RecordPlaceholder("test", "123", "original-placeholder")
|
||||
for _, content := range []string{"/new", "/new 新问题", "/NEW@bot\t新问题"} {
|
||||
if err := ch.HandleMessageWithContext(t.Context(), "123", content, nil, bus.InboundContext{
|
||||
ChatID: "123", SenderID: "user1",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case msg := <-msgBus.InboundChan():
|
||||
if msg.Content != content {
|
||||
t.Fatalf("forwarded content = %q", msg.Content)
|
||||
}
|
||||
default:
|
||||
t.Fatal("command not forwarded")
|
||||
}
|
||||
}
|
||||
if ch.placeholdersSent != 0 {
|
||||
t.Fatal("/new created a replacement placeholder")
|
||||
}
|
||||
v, ok := m.placeholders.Load("test:123")
|
||||
if !ok || v.(placeholderEntry).id != "original-placeholder" {
|
||||
t.Fatal("original placeholder was replaced")
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,10 @@ func (c *DiscordChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]s
|
||||
}
|
||||
}
|
||||
trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(channelID)
|
||||
c.maybeStartTTS(channelID, msg.Content, isToolFeedback)
|
||||
hasTrackedMsg = hasTrackedMsg && !channels.IsCommandReply(msg)
|
||||
if !channels.IsCommandReply(msg) {
|
||||
c.maybeStartTTS(channelID, msg.Content, isToolFeedback)
|
||||
}
|
||||
if !isToolFeedback {
|
||||
if msgIDs, handled := c.FinalizeToolFeedbackMessage(ctx, msg); handled {
|
||||
return msgIDs, nil
|
||||
@@ -462,7 +465,7 @@ func (c *DiscordChannel) finalizeTrackedToolFeedbackMessage(
|
||||
}
|
||||
|
||||
func (c *DiscordChannel) FinalizeToolFeedbackMessage(ctx context.Context, msg bus.OutboundMessage) ([]string, bool) {
|
||||
if outboundMessageIsToolFeedback(msg) {
|
||||
if outboundMessageIsToolFeedback(msg) || channels.IsCommandReply(msg) {
|
||||
return nil, false
|
||||
}
|
||||
return c.finalizeTrackedToolFeedbackMessage(ctx, msg.ChatID, msg.Content, c.EditMessage)
|
||||
|
||||
@@ -258,6 +258,21 @@ func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeToolFeedbackMessage_CommandReplyPreservesProgress(t *testing.T) {
|
||||
ch := &DiscordChannel{progress: channels.NewToolFeedbackAnimator(nil)}
|
||||
ch.RecordToolFeedbackMessage("chat-1", "progress-1", "Working")
|
||||
_, handled := ch.FinalizeToolFeedbackMessage(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "chat-1", Content: "请待会再试",
|
||||
Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}},
|
||||
})
|
||||
if handled {
|
||||
t.Fatal("command reply finalized task progress")
|
||||
}
|
||||
if id, ok := ch.currentToolFeedbackMessage("chat-1"); !ok || id != "progress-1" {
|
||||
t.Fatal("task progress was removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSend_NonToolFeedbackFinalizerStillStartsTTS(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
|
||||
@@ -180,6 +180,7 @@ func (c *FeishuChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]st
|
||||
}
|
||||
}
|
||||
trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(msg.ChatID)
|
||||
hasTrackedMsg = hasTrackedMsg && !channels.IsCommandReply(msg)
|
||||
|
||||
// Build interactive card with markdown content
|
||||
sendContent := msg.Content
|
||||
@@ -412,7 +413,7 @@ func (c *FeishuChannel) finalizeTrackedToolFeedbackMessage(
|
||||
}
|
||||
|
||||
func (c *FeishuChannel) FinalizeToolFeedbackMessage(ctx context.Context, msg bus.OutboundMessage) ([]string, bool) {
|
||||
if outboundMessageIsToolFeedback(msg) {
|
||||
if outboundMessageIsToolFeedback(msg) || channels.IsCommandReply(msg) {
|
||||
return nil, false
|
||||
}
|
||||
return c.finalizeTrackedToolFeedbackMessage(ctx, msg.ChatID, msg.Content, c.EditMessage)
|
||||
|
||||
@@ -386,6 +386,21 @@ func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeToolFeedbackMessage_CommandReplyPreservesProgress(t *testing.T) {
|
||||
ch := &FeishuChannel{progress: channels.NewToolFeedbackAnimator(nil)}
|
||||
ch.RecordToolFeedbackMessage("chat-1", "progress-1", "Working")
|
||||
_, handled := ch.FinalizeToolFeedbackMessage(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "chat-1", Content: "请待会再试",
|
||||
Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}},
|
||||
})
|
||||
if handled {
|
||||
t.Fatal("command reply finalized task progress")
|
||||
}
|
||||
if id, ok := ch.currentToolFeedbackMessage("chat-1"); !ok || id != "progress-1" {
|
||||
t.Fatal("task progress was removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeTrackedToolFeedbackMessage_EditFailureKeepsTrackedMessage(t *testing.T) {
|
||||
ch := &FeishuChannel{
|
||||
progress: channels.NewToolFeedbackAnimator(nil),
|
||||
|
||||
@@ -368,6 +368,11 @@ func (m *Manager) RecordReactionUndo(channel, chatID string, undo func()) {
|
||||
// preSend handles typing stop, reaction undo, and placeholder editing before sending a message.
|
||||
// Returns the delivered message IDs and true when delivery completed before a normal Send.
|
||||
func (m *Manager) preSend(ctx context.Context, name string, msg bus.OutboundMessage, ch Channel) ([]string, bool) {
|
||||
// Command replies during a running turn must not consume its placeholder,
|
||||
// stop typing, or alter stream finalization state.
|
||||
if IsCommandReply(msg) {
|
||||
return nil, false
|
||||
}
|
||||
chatID := outboundMessageChatID(msg)
|
||||
key := name + ":" + chatID
|
||||
streamKey := streamSuppressionKey(name, chatID, msg.SessionKey)
|
||||
|
||||
@@ -421,6 +421,7 @@ func (c *MatrixChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]st
|
||||
}
|
||||
}
|
||||
trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(msg.ChatID)
|
||||
hasTrackedMsg = hasTrackedMsg && !channels.IsCommandReply(msg)
|
||||
if !isToolFeedback {
|
||||
if msgIDs, handled := c.FinalizeToolFeedbackMessage(ctx, msg); handled {
|
||||
return msgIDs, nil
|
||||
@@ -733,7 +734,7 @@ func (c *MatrixChannel) finalizeTrackedToolFeedbackMessage(
|
||||
}
|
||||
|
||||
func (c *MatrixChannel) FinalizeToolFeedbackMessage(ctx context.Context, msg bus.OutboundMessage) ([]string, bool) {
|
||||
if outboundMessageIsToolFeedback(msg) {
|
||||
if outboundMessageIsToolFeedback(msg) || channels.IsCommandReply(msg) {
|
||||
return nil, false
|
||||
}
|
||||
return c.finalizeTrackedToolFeedbackMessage(ctx, msg.ChatID, msg.Content, c.EditMessage)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"maunium.net/go/mautrix/event"
|
||||
"maunium.net/go/mautrix/id"
|
||||
|
||||
"github.com/sipeed/picoclaw/pkg/bus"
|
||||
"github.com/sipeed/picoclaw/pkg/channels"
|
||||
"github.com/sipeed/picoclaw/pkg/config"
|
||||
"github.com/sipeed/picoclaw/pkg/media"
|
||||
@@ -70,6 +71,21 @@ func TestFinalizeTrackedToolFeedbackMessage_StopsTrackingBeforeEdit(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalizeToolFeedbackMessage_CommandReplyPreservesProgress(t *testing.T) {
|
||||
ch := &MatrixChannel{progress: channels.NewToolFeedbackAnimator(nil)}
|
||||
ch.RecordToolFeedbackMessage("!room:matrix.org", "$progress", "Working")
|
||||
_, handled := ch.FinalizeToolFeedbackMessage(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "!room:matrix.org", Content: "请待会再试",
|
||||
Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}},
|
||||
})
|
||||
if handled {
|
||||
t.Fatal("command reply finalized task progress")
|
||||
}
|
||||
if id, ok := ch.currentToolFeedbackMessage("!room:matrix.org"); !ok || id != "$progress" {
|
||||
t.Fatal("task progress was removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripUserMention(t *testing.T) {
|
||||
userID := id.UserID("@picoclaw:matrix.org")
|
||||
|
||||
|
||||
@@ -66,7 +66,8 @@ func outboundMessageIsToolCalls(msg bus.OutboundMessage) bool {
|
||||
}
|
||||
|
||||
func outboundMessageFinalizesTrackedToolFeedback(msg bus.OutboundMessage) bool {
|
||||
return !outboundMessageIsToolFeedback(msg) &&
|
||||
return !channels.IsCommandReply(msg) &&
|
||||
!outboundMessageIsToolFeedback(msg) &&
|
||||
!outboundMessageIsThought(msg) &&
|
||||
!outboundMessageIsToolCalls(msg)
|
||||
}
|
||||
|
||||
@@ -240,6 +240,37 @@ func TestSend_ThoughtMessageDoesNotFinalizeTrackedToolFeedback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSend_CommandReplyPreservesToolFeedback(t *testing.T) {
|
||||
ch := newTestPicoChannel(t)
|
||||
if err := ch.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ch.Stop(context.Background()) })
|
||||
clientConn, received, cleanup := newTestPicoWebSocket(t)
|
||||
t.Cleanup(cleanup)
|
||||
ch.addConnForTest(&picoConn{id: "conn-1", conn: clientConn, sessionID: "sess-1"})
|
||||
ch.RecordToolFeedbackMessage("pico:sess-1", "progress-1", "Working")
|
||||
_, err := ch.Send(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "pico:sess-1", Content: "请待会再试",
|
||||
Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case msg := <-received:
|
||||
if msg.Type != TypeMessageCreate || msg.Payload[PayloadKeyContent] != "请待会再试" ||
|
||||
msg.Payload["message_id"] == "progress-1" {
|
||||
t.Fatalf("command reply replaced task progress: %+v", msg)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("command reply was not delivered")
|
||||
}
|
||||
if id, ok := ch.currentToolFeedbackMessage("pico:sess-1"); !ok || id != "progress-1" {
|
||||
t.Fatal("task progress was removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSend_ToolCallsMessageIncludesModelName(t *testing.T) {
|
||||
ch := newTestPicoChannel(t)
|
||||
|
||||
|
||||
@@ -246,6 +246,7 @@ func (c *TelegramChannel) Send(ctx context.Context, msg bus.OutboundMessage) ([]
|
||||
}
|
||||
}
|
||||
trackedMsgID, hasTrackedMsg := c.currentToolFeedbackMessage(trackedChatID)
|
||||
hasTrackedMsg = hasTrackedMsg && !channels.IsCommandReply(msg)
|
||||
if !isToolFeedback {
|
||||
if msgIDs, handled := c.finalizeToolFeedbackMessageForChat(ctx, trackedChatID, msg); handled {
|
||||
return msgIDs, nil
|
||||
@@ -594,6 +595,9 @@ func (c *TelegramChannel) finalizeToolFeedbackMessageForChat(
|
||||
chatID string,
|
||||
msg bus.OutboundMessage,
|
||||
) ([]string, bool) {
|
||||
if channels.IsCommandReply(msg) {
|
||||
return nil, false
|
||||
}
|
||||
return c.finalizeTrackedToolFeedbackMessage(ctx, chatID, msg.Content, c.EditMessage)
|
||||
}
|
||||
|
||||
|
||||
@@ -610,6 +610,26 @@ func TestSend_NonToolFeedbackDeletesTrackedProgressMessage(t *testing.T) {
|
||||
assert.False(t, ok, "tracked tool feedback should be cleared after final reply")
|
||||
}
|
||||
|
||||
func TestSend_CommandReplyPreservesToolFeedback(t *testing.T) {
|
||||
caller := &stubCaller{callFn: func(_ context.Context, url string, _ *ta.RequestData) (*ta.Response, error) {
|
||||
if !strings.Contains(url, "sendMessage") {
|
||||
t.Fatalf("command reply edited or deleted task progress: %s", url)
|
||||
}
|
||||
return successResponseWithMessageID(t, 2), nil
|
||||
}}
|
||||
ch := newTestChannel(t, caller)
|
||||
ch.RecordToolFeedbackMessage("12345", "1", "Working")
|
||||
ids, err := ch.Send(t.Context(), bus.OutboundMessage{
|
||||
ChatID: "12345", Content: "请待会再试",
|
||||
Context: bus.InboundContext{Raw: map[string]string{"outbound_kind": "command_reply"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"2"}, ids)
|
||||
msgID, ok := ch.currentToolFeedbackMessage("12345")
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "1", msgID)
|
||||
}
|
||||
|
||||
func TestSend_ToolFeedbackTrackingIsTopicScoped(t *testing.T) {
|
||||
nextMessageID := 0
|
||||
caller := &stubCaller{
|
||||
|
||||
@@ -16,6 +16,7 @@ func BuiltinDefinitions() []Definition {
|
||||
switchCommand(),
|
||||
checkCommand(),
|
||||
clearCommand(),
|
||||
newCommand(),
|
||||
contextCommand(),
|
||||
subagentsCommand(),
|
||||
reloadCommand(),
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
func newCommand() Definition {
|
||||
return Definition{
|
||||
Name: "new",
|
||||
Description: "Clear the chat history and optionally run a new prompt",
|
||||
Usage: "/new [prompt]",
|
||||
Handler: func(ctx context.Context, req Request, rt *Runtime) error {
|
||||
if rt == nil || rt.StartNewConversation == nil {
|
||||
return req.Reply(unavailableMsg)
|
||||
}
|
||||
text := strings.TrimSpace(req.Text)
|
||||
var prompt string
|
||||
if i := strings.IndexFunc(text, unicode.IsSpace); i >= 0 {
|
||||
prompt = strings.TrimSpace(text[i:])
|
||||
}
|
||||
response, err := rt.StartNewConversation(ctx, prompt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return req.Reply(response)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewCommand(t *testing.T) {
|
||||
for _, tt := range []struct{ input, prompt string }{
|
||||
{"/new", ""},
|
||||
{" /new \t\n", ""},
|
||||
{"/new 帮我查查今天成都的天气", "帮我查查今天成都的天气"},
|
||||
{"/new 看看今天有啥新咖啡", "看看今天有啥新咖啡"},
|
||||
{"/NEW@testbot\t first line\nsecond\tline ", "first line\nsecond\tline"},
|
||||
{"!new\n问题", "问题"},
|
||||
{"/new /clear", "/clear"},
|
||||
} {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
calls := 0
|
||||
rt := &Runtime{StartNewConversation: func(ctx context.Context, prompt string) (string, error) {
|
||||
calls++
|
||||
if prompt != tt.prompt {
|
||||
t.Fatalf("prompt = %q, want %q", prompt, tt.prompt)
|
||||
}
|
||||
return "new reply", nil
|
||||
}}
|
||||
var reply string
|
||||
res := NewExecutor(NewRegistry(BuiltinDefinitions()), rt).Execute(t.Context(), Request{
|
||||
Text: tt.input,
|
||||
Reply: func(text string) error { reply = text; return nil },
|
||||
})
|
||||
if res.Outcome != OutcomeHandled || res.Err != nil || calls != 1 || reply != "new reply" {
|
||||
t.Fatalf("result = %+v, calls = %d, reply = %q", res, calls, reply)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCommand_UnavailableAndFailure(t *testing.T) {
|
||||
for _, rt := range []*Runtime{nil, {}} {
|
||||
var reply string
|
||||
res := NewExecutor(NewRegistry(BuiltinDefinitions()), rt).Execute(t.Context(), Request{
|
||||
Text: "/new question",
|
||||
Reply: func(text string) error { reply = text; return nil },
|
||||
})
|
||||
if res.Outcome != OutcomeHandled || reply != unavailableMsg {
|
||||
t.Fatalf("result = %+v, reply = %q", res, reply)
|
||||
}
|
||||
}
|
||||
wantErr := errors.New("clear failed")
|
||||
res := NewExecutor(NewRegistry(BuiltinDefinitions()), &Runtime{
|
||||
StartNewConversation: func(context.Context, string) (string, error) { return "", wantErr },
|
||||
}).Execute(t.Context(), Request{Text: "/new question"})
|
||||
if res.Outcome != OutcomeHandled || !errors.Is(res.Err, wantErr) {
|
||||
t.Fatalf("result = %+v, want clear error", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCommand_Help(t *testing.T) {
|
||||
if help := formatHelpMessage(BuiltinDefinitions()); !strings.Contains(help, "/new [prompt]") {
|
||||
t.Fatalf("help missing /new: %s", help)
|
||||
}
|
||||
}
|
||||
+17
-16
@@ -48,20 +48,21 @@ type StopResult struct {
|
||||
// per-request by the agent loop so that per-request state (like session scope)
|
||||
// can coexist with long-lived callbacks (like GetModelInfo).
|
||||
type Runtime struct {
|
||||
Config *config.Config
|
||||
GetModelInfo func() (name, provider string)
|
||||
AskSideQuestion func(ctx context.Context, question string) (string, error)
|
||||
ListAgentIDs func() []string
|
||||
ListDefinitions func() []Definition
|
||||
ListSkillNames func() []string
|
||||
ListMCPServers func(ctx context.Context) []MCPServerInfo
|
||||
ListMCPTools func(ctx context.Context, serverName string) ([]MCPToolInfo, error)
|
||||
GetEnabledChannels func() []string
|
||||
GetActiveTurn func() any // Returning any to avoid circular dependency with agent package
|
||||
GetContextStats func() *ContextStats
|
||||
SwitchModel func(value string) (oldModel string, err error)
|
||||
SwitchChannel func(value string) error
|
||||
ClearHistory func() error
|
||||
ReloadConfig func() error
|
||||
StopActiveTurn func() (StopResult, error)
|
||||
Config *config.Config
|
||||
GetModelInfo func() (name, provider string)
|
||||
AskSideQuestion func(ctx context.Context, question string) (string, error)
|
||||
ListAgentIDs func() []string
|
||||
ListDefinitions func() []Definition
|
||||
ListSkillNames func() []string
|
||||
ListMCPServers func(ctx context.Context) []MCPServerInfo
|
||||
ListMCPTools func(ctx context.Context, serverName string) ([]MCPToolInfo, error)
|
||||
GetEnabledChannels func() []string
|
||||
GetActiveTurn func() any // Returning any to avoid circular dependency with agent package
|
||||
GetContextStats func() *ContextStats
|
||||
SwitchModel func(value string) (oldModel string, err error)
|
||||
SwitchChannel func(value string) error
|
||||
ClearHistory func() error
|
||||
StartNewConversation func(ctx context.Context, prompt string) (string, error)
|
||||
ReloadConfig func() error
|
||||
StopActiveTurn func() (StopResult, error)
|
||||
}
|
||||
@@ -225,7 +225,7 @@ func (p *Provider) applyThinkingControl(requestBody map[string]any, model string
|
||||
return
|
||||
}
|
||||
|
||||
if p.SupportsThinking() {
|
||||
if p.supportsDeepSeekThinking() {
|
||||
p.applyDeepSeekThinkingControl(requestBody, level)
|
||||
return
|
||||
}
|
||||
@@ -339,6 +339,10 @@ func (p *Provider) SetProviderName(providerName string) {
|
||||
}
|
||||
|
||||
func (p *Provider) SupportsThinking() bool {
|
||||
return strings.EqualFold(strings.TrimSpace(p.providerName), "openai") || p.supportsDeepSeekThinking()
|
||||
}
|
||||
|
||||
func (p *Provider) supportsDeepSeekThinking() bool {
|
||||
return strings.EqualFold(strings.TrimSpace(p.providerName), "deepseek") || isDeepSeekHost(p.apiBase)
|
||||
}
|
||||
|
||||
@@ -504,6 +508,15 @@ func (p *Provider) buildResponsesRequestBody(
|
||||
if maxTokens, ok := common.AsInt(options["max_tokens"]); ok {
|
||||
requestBody["max_output_tokens"] = maxTokens
|
||||
}
|
||||
if level, ok := normalizedThinkingLevel(options); ok && level != "adaptive" {
|
||||
effort := level
|
||||
if level == "off" {
|
||||
effort = "none"
|
||||
}
|
||||
if level != "off" || isOpenAIReasoningModel(model) {
|
||||
requestBody["reasoning"] = map[string]any{"effort": effort}
|
||||
}
|
||||
}
|
||||
if temperature, ok := common.AsFloat(options["temperature"]); ok {
|
||||
requestBody["temperature"] = temperature
|
||||
}
|
||||
@@ -513,9 +526,49 @@ func (p *Provider) buildResponsesRequestBody(
|
||||
}
|
||||
|
||||
maps.Copy(requestBody, p.extraBody)
|
||||
// Agent calls include a default temperature. Reasoning models reject it
|
||||
// unless their effective effort is "none". Keep explicit extra_body values
|
||||
// so callers can override the model default when their endpoint supports it.
|
||||
if _, explicit := p.extraBody["temperature"]; !explicit &&
|
||||
shouldOmitResponsesTemperature(model, requestBody["reasoning"]) {
|
||||
delete(requestBody, "temperature")
|
||||
}
|
||||
return requestBody
|
||||
}
|
||||
|
||||
func shouldOmitResponsesTemperature(model string, reasoning any) bool {
|
||||
if settings, ok := reasoning.(map[string]any); ok {
|
||||
if effort, ok := settings["effort"].(string); ok {
|
||||
return !strings.EqualFold(strings.TrimSpace(effort), "none")
|
||||
}
|
||||
}
|
||||
return isOpenAIReasoningModel(model)
|
||||
}
|
||||
|
||||
// The agent supplies a temperature even when the user leaves it unset, so
|
||||
// recognize reasoning model families when no effort is specified explicitly.
|
||||
func isOpenAIReasoningModel(model string) bool {
|
||||
model = strings.ToLower(strings.TrimSpace(model))
|
||||
if strings.HasPrefix(model, "gpt-oss") {
|
||||
return true
|
||||
}
|
||||
if len(model) > 1 && model[0] == 'o' && model[1] >= '0' && model[1] <= '9' {
|
||||
return true
|
||||
}
|
||||
if !strings.HasPrefix(model, "gpt-") {
|
||||
return false
|
||||
}
|
||||
version := strings.TrimPrefix(model, "gpt-")
|
||||
major := 0
|
||||
for _, digit := range version {
|
||||
if digit < '0' || digit > '9' {
|
||||
break
|
||||
}
|
||||
major = major*10 + int(digit-'0')
|
||||
}
|
||||
return major >= 5
|
||||
}
|
||||
|
||||
func (p *Provider) Chat(
|
||||
ctx context.Context,
|
||||
messages []Message,
|
||||
|
||||
Reference in new issue
Block a user