Merge branch 'main' into oidc
This commit is contained in:
+224
-129
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
// toolDisplayNames maps internal tool names to user-friendly display labels.
|
||||
@@ -62,6 +64,7 @@ func formatToolHint(name string, args map[string]any) string {
|
||||
|
||||
// executeToolCalls runs every tool call in the LLM response, appending results to step.ToolCalls.
|
||||
// It also emits tool-call and tool-result events, and optionally runs reflection after each call.
|
||||
// When ParallelToolCalls is enabled and there are 2+ tool calls, they execute concurrently.
|
||||
func (e *AgentEngine) executeToolCalls(
|
||||
ctx context.Context, response *types.ChatResponse,
|
||||
step *types.AgentStep, iteration int, sessionID string,
|
||||
@@ -71,165 +74,257 @@ func (e *AgentEngine) executeToolCalls(
|
||||
}
|
||||
|
||||
round := iteration + 1
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Executing %d tool call(s)", round, len(response.ToolCalls))
|
||||
n := len(response.ToolCalls)
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Executing %d tool call(s)", round, n)
|
||||
|
||||
// Use parallel execution when enabled and there are multiple tool calls
|
||||
if e.config.ParallelToolCalls && n >= 2 {
|
||||
e.executeToolCallsParallel(ctx, response, step, iteration, sessionID)
|
||||
return
|
||||
}
|
||||
|
||||
for i, tc := range response.ToolCalls {
|
||||
// Normalize tool call ID for cross-provider compatibility
|
||||
tc.ID = agenttools.NormalizeToolCallID(tc.ID, tc.Function.Name, i)
|
||||
toolTag := fmt.Sprintf("[Agent][Round-%d][Tool %s (%d/%d)]",
|
||||
round, tc.Function.Name, i+1, len(response.ToolCalls))
|
||||
e.executeSingleToolCall(ctx, tc, i, step, iteration, round, sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
var args map[string]any
|
||||
argsStr := tc.Function.Arguments
|
||||
if err := json.Unmarshal([]byte(argsStr), &args); err != nil {
|
||||
// Attempt JSON repair before giving up
|
||||
repaired := agenttools.RepairJSON(argsStr)
|
||||
if repairErr := json.Unmarshal([]byte(repaired), &args); repairErr != nil {
|
||||
logger.Errorf(ctx, "%s Failed to parse arguments (repair failed): %v", toolTag, err)
|
||||
step.ToolCalls = append(step.ToolCalls, types.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Args: map[string]any{"_raw": argsStr},
|
||||
Result: &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf(
|
||||
"Failed to parse tool arguments: %v", err,
|
||||
) + "\n\n[Analyze the error above and try a different approach.]",
|
||||
},
|
||||
})
|
||||
continue
|
||||
}
|
||||
logger.Warnf(ctx, "%s Repaired malformed JSON arguments", toolTag)
|
||||
tc.Function.Arguments = repaired
|
||||
}
|
||||
// executeToolCallsParallel runs all tool calls concurrently using errgroup,
|
||||
// collecting results in original order.
|
||||
func (e *AgentEngine) executeToolCallsParallel(
|
||||
ctx context.Context, response *types.ChatResponse,
|
||||
step *types.AgentStep, iteration int, sessionID string,
|
||||
) {
|
||||
round := iteration + 1
|
||||
n := len(response.ToolCalls)
|
||||
logger.Infof(ctx, "[Agent][Round-%d] Parallel execution of %d tool calls", round, n)
|
||||
|
||||
logger.Debugf(ctx, "%s Args: %s", toolTag, tc.Function.Arguments)
|
||||
results := make([]types.ToolCall, n)
|
||||
var mu sync.Mutex
|
||||
g, gCtx := errgroup.WithContext(ctx)
|
||||
|
||||
toolCallStartTime := time.Now()
|
||||
|
||||
// Emit tool hint for UI progress display
|
||||
toolHint := formatToolHint(tc.Function.Name, args)
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: tc.ID + "-tool-hint",
|
||||
Type: event.EventAgentToolCall,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentToolCallData{
|
||||
ToolCallID: tc.ID,
|
||||
ToolName: tc.Function.Name,
|
||||
Arguments: args,
|
||||
Iteration: iteration,
|
||||
Hint: toolHint,
|
||||
},
|
||||
for i, tc := range response.ToolCalls {
|
||||
i, tc := i, tc // capture loop vars
|
||||
g.Go(func() error {
|
||||
toolCall := e.runToolCall(gCtx, tc, i, iteration, round, sessionID)
|
||||
mu.Lock()
|
||||
results[i] = toolCall
|
||||
mu.Unlock()
|
||||
return nil // best-effort: don't cancel siblings on failure
|
||||
})
|
||||
}
|
||||
|
||||
// Execute tool with timeout to prevent indefinite hangs
|
||||
common.PipelineInfo(ctx, "Agent", "tool_call_start", map[string]interface{}{
|
||||
"iteration": iteration,
|
||||
"round": round,
|
||||
"tool": tc.Function.Name,
|
||||
"tool_call_id": tc.ID,
|
||||
"tool_index": fmt.Sprintf("%d/%d", i+1, len(response.ToolCalls)),
|
||||
})
|
||||
toolCtx, toolCancel := context.WithTimeout(ctx, defaultToolExecTimeout)
|
||||
result, err := e.toolRegistry.ExecuteTool(
|
||||
toolCtx, tc.Function.Name,
|
||||
json.RawMessage(tc.Function.Arguments),
|
||||
)
|
||||
toolCancel()
|
||||
duration := time.Since(toolCallStartTime).Milliseconds()
|
||||
_ = g.Wait()
|
||||
|
||||
toolCall := types.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Args: args,
|
||||
Result: result,
|
||||
Duration: duration,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "%s Failed in %dms: %v", toolTag, duration, err)
|
||||
toolCall.Result = &types.ToolResult{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}
|
||||
} else {
|
||||
success := result != nil && result.Success
|
||||
outputLen := 0
|
||||
if result != nil {
|
||||
outputLen = len(result.Output)
|
||||
}
|
||||
logger.Infof(ctx, "%s Completed in %dms: success=%v, output=%d chars",
|
||||
toolTag, duration, success, outputLen)
|
||||
}
|
||||
|
||||
// Pipeline event for monitoring
|
||||
toolSuccess := toolCall.Result != nil && toolCall.Result.Success
|
||||
pipelineFields := map[string]interface{}{
|
||||
"iteration": iteration,
|
||||
"round": round,
|
||||
"tool": tc.Function.Name,
|
||||
"tool_call_id": tc.ID,
|
||||
"duration_ms": duration,
|
||||
"success": toolSuccess,
|
||||
}
|
||||
if toolCall.Result != nil && toolCall.Result.Error != "" {
|
||||
pipelineFields["error"] = toolCall.Result.Error
|
||||
}
|
||||
if err != nil {
|
||||
common.PipelineError(ctx, "Agent", "tool_call_result", pipelineFields)
|
||||
} else if toolSuccess {
|
||||
common.PipelineInfo(ctx, "Agent", "tool_call_result", pipelineFields)
|
||||
} else {
|
||||
common.PipelineWarn(ctx, "Agent", "tool_call_result", pipelineFields)
|
||||
}
|
||||
|
||||
// Debug-level output preview
|
||||
if toolCall.Result != nil && toolCall.Result.Output != "" {
|
||||
preview := toolCall.Result.Output
|
||||
if len(preview) > 500 {
|
||||
preview = preview[:500] + "... (truncated)"
|
||||
}
|
||||
logger.Debugf(ctx, "%s Output preview:\n%s", toolTag, preview)
|
||||
}
|
||||
if toolCall.Result != nil && toolCall.Result.Error != "" {
|
||||
logger.Debugf(ctx, "%s Tool error: %s", toolTag, toolCall.Result.Error)
|
||||
}
|
||||
|
||||
// Store tool call
|
||||
// Append results and emit events in original order
|
||||
for _, toolCall := range results {
|
||||
step.ToolCalls = append(step.ToolCalls, toolCall)
|
||||
|
||||
// Emit tool result event (include structured data from tool result)
|
||||
result := toolCall.Result
|
||||
if result == nil {
|
||||
result = &types.ToolResult{Success: false, Error: "no result"}
|
||||
}
|
||||
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: tc.ID + "-tool-result",
|
||||
ID: toolCall.ID + "-tool-result",
|
||||
Type: event.EventAgentToolResult,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentToolResultData{
|
||||
ToolCallID: tc.ID,
|
||||
ToolName: tc.Function.Name,
|
||||
ToolCallID: toolCall.ID,
|
||||
ToolName: toolCall.Name,
|
||||
Output: result.Output,
|
||||
Error: result.Error,
|
||||
Success: result.Success,
|
||||
Duration: duration,
|
||||
Duration: toolCall.Duration,
|
||||
Iteration: iteration,
|
||||
Data: result.Data, // Pass structured data for frontend rendering
|
||||
Data: result.Data,
|
||||
},
|
||||
})
|
||||
|
||||
// Emit tool execution event (for internal monitoring)
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: tc.ID + "-tool-exec",
|
||||
ID: toolCall.ID + "-tool-exec",
|
||||
Type: event.EventAgentTool,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentActionData{
|
||||
Iteration: iteration,
|
||||
ToolName: tc.Function.Name,
|
||||
ToolInput: args,
|
||||
ToolName: toolCall.Name,
|
||||
ToolInput: toolCall.Args,
|
||||
ToolOutput: result.Output,
|
||||
Success: result.Success,
|
||||
Error: result.Error,
|
||||
Duration: duration,
|
||||
Duration: toolCall.Duration,
|
||||
},
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// executeSingleToolCall runs one tool call sequentially (original behavior).
|
||||
func (e *AgentEngine) executeSingleToolCall(
|
||||
ctx context.Context, tc types.LLMToolCall, i int,
|
||||
step *types.AgentStep, iteration, round int, sessionID string,
|
||||
) {
|
||||
toolCall := e.runToolCall(ctx, tc, i, iteration, round, sessionID)
|
||||
step.ToolCalls = append(step.ToolCalls, toolCall)
|
||||
|
||||
result := toolCall.Result
|
||||
if result == nil {
|
||||
result = &types.ToolResult{Success: false, Error: "no result"}
|
||||
}
|
||||
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: toolCall.ID + "-tool-result",
|
||||
Type: event.EventAgentToolResult,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentToolResultData{
|
||||
ToolCallID: toolCall.ID,
|
||||
ToolName: toolCall.Name,
|
||||
Output: result.Output,
|
||||
Error: result.Error,
|
||||
Success: result.Success,
|
||||
Duration: toolCall.Duration,
|
||||
Iteration: iteration,
|
||||
Data: result.Data,
|
||||
},
|
||||
})
|
||||
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: toolCall.ID + "-tool-exec",
|
||||
Type: event.EventAgentTool,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentActionData{
|
||||
Iteration: iteration,
|
||||
ToolName: toolCall.Name,
|
||||
ToolInput: toolCall.Args,
|
||||
ToolOutput: result.Output,
|
||||
Success: result.Success,
|
||||
Error: result.Error,
|
||||
Duration: toolCall.Duration,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// runToolCall handles argument parsing, execution, logging, and pipeline events for a single tool call.
|
||||
// It returns the completed ToolCall struct. Safe to call from multiple goroutines.
|
||||
func (e *AgentEngine) runToolCall(
|
||||
ctx context.Context, tc types.LLMToolCall, i int,
|
||||
iteration, round int, sessionID string,
|
||||
) types.ToolCall {
|
||||
tc.ID = agenttools.NormalizeToolCallID(tc.ID, tc.Function.Name, i)
|
||||
total := "?" // unknown in isolation; callers log the batch size
|
||||
toolTag := fmt.Sprintf("[Agent][Round-%d][Tool %s (%d/%s)]",
|
||||
round, tc.Function.Name, i+1, total)
|
||||
|
||||
var args map[string]any
|
||||
argsStr := tc.Function.Arguments
|
||||
if err := json.Unmarshal([]byte(argsStr), &args); err != nil {
|
||||
repaired := agenttools.RepairJSON(argsStr)
|
||||
if repairErr := json.Unmarshal([]byte(repaired), &args); repairErr != nil {
|
||||
logger.Errorf(ctx, "%s Failed to parse arguments (repair failed): %v", toolTag, err)
|
||||
return types.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Args: map[string]any{"_raw": argsStr},
|
||||
Result: &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf(
|
||||
"Failed to parse tool arguments: %v", err,
|
||||
) + "\n\n[Analyze the error above and try a different approach.]",
|
||||
},
|
||||
}
|
||||
}
|
||||
logger.Warnf(ctx, "%s Repaired malformed JSON arguments", toolTag)
|
||||
tc.Function.Arguments = repaired
|
||||
}
|
||||
|
||||
logger.Debugf(ctx, "%s Args: %s", toolTag, tc.Function.Arguments)
|
||||
|
||||
toolCallStartTime := time.Now()
|
||||
|
||||
// Emit tool hint for UI progress display
|
||||
toolHint := formatToolHint(tc.Function.Name, args)
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: tc.ID + "-tool-hint",
|
||||
Type: event.EventAgentToolCall,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentToolCallData{
|
||||
ToolCallID: tc.ID,
|
||||
ToolName: tc.Function.Name,
|
||||
Arguments: args,
|
||||
Iteration: iteration,
|
||||
Hint: toolHint,
|
||||
},
|
||||
})
|
||||
|
||||
common.PipelineInfo(ctx, "Agent", "tool_call_start", map[string]interface{}{
|
||||
"iteration": iteration,
|
||||
"round": round,
|
||||
"tool": tc.Function.Name,
|
||||
"tool_call_id": tc.ID,
|
||||
"tool_index": fmt.Sprintf("%d/%s", i+1, total),
|
||||
})
|
||||
|
||||
toolCtx, toolCancel := context.WithTimeout(ctx, defaultToolExecTimeout)
|
||||
result, err := e.toolRegistry.ExecuteTool(
|
||||
toolCtx, tc.Function.Name,
|
||||
json.RawMessage(tc.Function.Arguments),
|
||||
)
|
||||
toolCancel()
|
||||
duration := time.Since(toolCallStartTime).Milliseconds()
|
||||
|
||||
toolCall := types.ToolCall{
|
||||
ID: tc.ID,
|
||||
Name: tc.Function.Name,
|
||||
Args: args,
|
||||
Result: result,
|
||||
Duration: duration,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "%s Failed in %dms: %v", toolTag, duration, err)
|
||||
toolCall.Result = &types.ToolResult{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
}
|
||||
} else {
|
||||
success := result != nil && result.Success
|
||||
outputLen := 0
|
||||
if result != nil {
|
||||
outputLen = len(result.Output)
|
||||
}
|
||||
logger.Infof(ctx, "%s Completed in %dms: success=%v, output=%d chars",
|
||||
toolTag, duration, success, outputLen)
|
||||
}
|
||||
|
||||
// Pipeline event for monitoring
|
||||
toolSuccess := toolCall.Result != nil && toolCall.Result.Success
|
||||
pipelineFields := map[string]interface{}{
|
||||
"iteration": iteration,
|
||||
"round": round,
|
||||
"tool": tc.Function.Name,
|
||||
"tool_call_id": tc.ID,
|
||||
"duration_ms": duration,
|
||||
"success": toolSuccess,
|
||||
}
|
||||
if toolCall.Result != nil && toolCall.Result.Error != "" {
|
||||
pipelineFields["error"] = toolCall.Result.Error
|
||||
}
|
||||
if err != nil {
|
||||
common.PipelineError(ctx, "Agent", "tool_call_result", pipelineFields)
|
||||
} else if toolSuccess {
|
||||
common.PipelineInfo(ctx, "Agent", "tool_call_result", pipelineFields)
|
||||
} else {
|
||||
common.PipelineWarn(ctx, "Agent", "tool_call_result", pipelineFields)
|
||||
}
|
||||
|
||||
if toolCall.Result != nil && toolCall.Result.Output != "" {
|
||||
preview := toolCall.Result.Output
|
||||
if len(preview) > 500 {
|
||||
preview = preview[:500] + "... (truncated)"
|
||||
}
|
||||
logger.Debugf(ctx, "%s Output preview:\n%s", toolTag, preview)
|
||||
}
|
||||
if toolCall.Result != nil && toolCall.Result.Error != "" {
|
||||
logger.Debugf(ctx, "%s Tool error: %s", toolTag, toolCall.Result.Error)
|
||||
}
|
||||
|
||||
return toolCall
|
||||
}
|
||||
|
||||
@@ -19,6 +19,16 @@ const (
|
||||
PlatformMattermost Platform = "mattermost"
|
||||
)
|
||||
|
||||
// SessionMode determines how IM sessions are resolved.
|
||||
type SessionMode string
|
||||
|
||||
const (
|
||||
// SessionModeUser resolves sessions by (platform, user_id, chat_id, tenant_id).
|
||||
SessionModeUser SessionMode = "user"
|
||||
// SessionModeThread resolves sessions by (platform, thread_id, chat_id, tenant_id).
|
||||
SessionModeThread SessionMode = "thread"
|
||||
)
|
||||
|
||||
// MessageType identifies the kind of IM message.
|
||||
type MessageType string
|
||||
|
||||
@@ -52,6 +62,15 @@ type IncomingMessage struct {
|
||||
FileName string
|
||||
// FileSize is the file size in bytes (for file messages, optional).
|
||||
FileSize int64
|
||||
// ThreadID is the platform-specific thread identifier.
|
||||
// - Slack: thread_ts (top-level message uses its own timestamp)
|
||||
// - Mattermost: root_id, or post_id if top-level
|
||||
// - Feishu: root_id, or message_id if top-level
|
||||
// - Telegram: message_thread_id (Forum Topics only)
|
||||
// Empty for platforms without thread support (WeCom, DingTalk).
|
||||
// In thread mode, top-level messages use their own ID as ThreadID,
|
||||
// effectively creating a new session per top-level message.
|
||||
ThreadID string
|
||||
// Extra holds platform-specific fields (e.g., WeCom stream ID).
|
||||
Extra map[string]string
|
||||
}
|
||||
|
||||
@@ -205,6 +205,8 @@ type feishuEvent struct {
|
||||
|
||||
type feishuMessage struct {
|
||||
MessageID string `json:"message_id"`
|
||||
RootID string `json:"root_id"`
|
||||
ParentID string `json:"parent_id"`
|
||||
MessageType string `json:"message_type"`
|
||||
ChatType string `json:"chat_type"`
|
||||
ChatID string `json:"chat_id"`
|
||||
@@ -263,6 +265,12 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
}
|
||||
msg := eventBody.Event.Message
|
||||
|
||||
// Compute thread ID: use root_id for threaded replies, or message_id for top-level messages.
|
||||
threadID := msg.RootID
|
||||
if threadID == "" {
|
||||
threadID = msg.MessageID
|
||||
}
|
||||
|
||||
// Determine chat type
|
||||
chatType := im.ChatTypeDirect
|
||||
chatID := ""
|
||||
@@ -308,6 +316,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
ChatType: chatType,
|
||||
Content: strings.TrimSpace(content),
|
||||
MessageID: msg.MessageID,
|
||||
ThreadID: threadID,
|
||||
}, nil
|
||||
|
||||
case "file":
|
||||
@@ -328,6 +337,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
MessageID: msg.MessageID,
|
||||
ThreadID: threadID,
|
||||
FileKey: fileContent.FileKey,
|
||||
FileName: fileContent.FileName,
|
||||
}, nil
|
||||
@@ -349,6 +359,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
MessageID: msg.MessageID,
|
||||
ThreadID: threadID,
|
||||
FileKey: imageContent.ImageKey,
|
||||
FileName: imageContent.ImageKey + ".png",
|
||||
}, nil
|
||||
@@ -411,6 +422,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
ChatType: chatType,
|
||||
Content: content,
|
||||
MessageID: msg.MessageID,
|
||||
ThreadID: threadID,
|
||||
}, nil
|
||||
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package feishu
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFeishuThreadID_ThreadedReply(t *testing.T) {
|
||||
// Simulate: message is a reply in a thread (root_id is set)
|
||||
msg := &feishuMessage{
|
||||
MessageID: "msg-reply-1",
|
||||
RootID: "msg-root-1",
|
||||
ParentID: "msg-parent-1",
|
||||
}
|
||||
|
||||
threadID := msg.RootID
|
||||
if threadID == "" {
|
||||
threadID = msg.MessageID
|
||||
}
|
||||
|
||||
if threadID != "msg-root-1" {
|
||||
t.Errorf("threadID = %q, want %q", threadID, "msg-root-1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeishuThreadID_TopLevelMessage(t *testing.T) {
|
||||
// Simulate: top-level message (root_id is empty)
|
||||
msg := &feishuMessage{
|
||||
MessageID: "msg-top-1",
|
||||
RootID: "",
|
||||
ParentID: "",
|
||||
}
|
||||
|
||||
threadID := msg.RootID
|
||||
if threadID == "" {
|
||||
threadID = msg.MessageID
|
||||
}
|
||||
|
||||
if threadID != "msg-top-1" {
|
||||
t.Errorf("threadID = %q, want %q (should use MessageID as fallback)", threadID, "msg-top-1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeishuMessageStruct_JSONFields(t *testing.T) {
|
||||
// Verify the struct fields exist and have correct zero values
|
||||
msg := feishuMessage{}
|
||||
if msg.RootID != "" {
|
||||
t.Errorf("RootID zero value = %q, want empty", msg.RootID)
|
||||
}
|
||||
if msg.ParentID != "" {
|
||||
t.Errorf("ParentID zero value = %q, want empty", msg.ParentID)
|
||||
}
|
||||
if msg.MessageID != "" {
|
||||
t.Errorf("MessageID zero value = %q, want empty", msg.MessageID)
|
||||
}
|
||||
}
|
||||
@@ -114,7 +114,14 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
} else {
|
||||
threadRoot = payload.RootID
|
||||
if threadRoot == "" {
|
||||
threadRoot = payload.PostID
|
||||
// Outgoing webhooks may omit root_id for thread replies.
|
||||
// Fetch the post to resolve the actual thread root.
|
||||
if actualRootID, err := a.client.GetPost(c.Request.Context(), payload.PostID); err == nil && actualRootID != "" {
|
||||
threadRoot = actualRootID
|
||||
} else {
|
||||
// Top-level message: use its own PostID as thread root.
|
||||
threadRoot = payload.PostID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +133,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
ChatType: im.ChatTypeGroup,
|
||||
Content: strings.TrimSpace(payload.Text),
|
||||
MessageID: payload.PostID,
|
||||
ThreadID: threadRoot,
|
||||
Extra: map[string]string{
|
||||
extraKeyThreadRoot: threadRoot,
|
||||
extraKeyChannelID: payload.ChannelID,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package mattermost
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseOutgoingBody_ThreadRoot(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload outgoingPayload
|
||||
postReplyToMain bool
|
||||
wantThreadRoot string
|
||||
}{
|
||||
{
|
||||
name: "threaded reply has RootID",
|
||||
payload: outgoingPayload{
|
||||
PostID: "post-123",
|
||||
RootID: "root-456",
|
||||
},
|
||||
postReplyToMain: false,
|
||||
wantThreadRoot: "root-456",
|
||||
},
|
||||
{
|
||||
name: "top-level message uses PostID as thread root",
|
||||
payload: outgoingPayload{
|
||||
PostID: "post-789",
|
||||
RootID: "",
|
||||
},
|
||||
postReplyToMain: false,
|
||||
wantThreadRoot: "post-789",
|
||||
},
|
||||
{
|
||||
name: "postReplyToMain clears thread root",
|
||||
payload: outgoingPayload{
|
||||
PostID: "post-123",
|
||||
RootID: "root-456",
|
||||
},
|
||||
postReplyToMain: true,
|
||||
wantThreadRoot: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var threadRoot string
|
||||
if tt.postReplyToMain {
|
||||
threadRoot = ""
|
||||
} else {
|
||||
threadRoot = tt.payload.RootID
|
||||
if threadRoot == "" {
|
||||
threadRoot = tt.payload.PostID
|
||||
}
|
||||
}
|
||||
|
||||
if threadRoot != tt.wantThreadRoot {
|
||||
t.Errorf("threadRoot = %q, want %q", threadRoot, tt.wantThreadRoot)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOutgoingBody_JSON(t *testing.T) {
|
||||
body := `{"token":"tok","user_id":"u1","user_name":"alice","channel_id":"ch1","post_id":"p1","text":"hello","root_id":"r1"}`
|
||||
|
||||
payload, err := parseOutgoingBody("application/json", []byte(body))
|
||||
if err != nil {
|
||||
t.Fatalf("parseOutgoingBody error: %v", err)
|
||||
}
|
||||
|
||||
if payload.RootID != "r1" {
|
||||
t.Errorf("RootID = %q, want %q", payload.RootID, "r1")
|
||||
}
|
||||
if payload.PostID != "p1" {
|
||||
t.Errorf("PostID = %q, want %q", payload.PostID, "p1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOutgoingBody_FormEncoded(t *testing.T) {
|
||||
body := "token=tok&user_id=u1&channel_id=ch1&post_id=p2&text=hello&root_id=r2"
|
||||
|
||||
payload, err := parseOutgoingBody("application/x-www-form-urlencoded", []byte(body))
|
||||
if err != nil {
|
||||
t.Fatalf("parseOutgoingBody error: %v", err)
|
||||
}
|
||||
|
||||
if payload.RootID != "r2" {
|
||||
t.Errorf("RootID = %q, want %q", payload.RootID, "r2")
|
||||
}
|
||||
if payload.PostID != "p2" {
|
||||
t.Errorf("PostID = %q, want %q", payload.PostID, "p2")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThreadIDInMessage(t *testing.T) {
|
||||
// Simulate the adapter logic: build the message and verify ThreadID
|
||||
payload := outgoingPayload{
|
||||
Token: "tok",
|
||||
UserID: "user-1",
|
||||
UserName: "alice",
|
||||
ChannelID: "ch-1",
|
||||
PostID: "post-100",
|
||||
Text: "hello",
|
||||
RootID: "root-200",
|
||||
}
|
||||
|
||||
threadRoot := payload.RootID
|
||||
if threadRoot == "" {
|
||||
threadRoot = payload.PostID
|
||||
}
|
||||
|
||||
// Verify the Extra map and ThreadID would be consistent
|
||||
extra := map[string]string{
|
||||
extraKeyThreadRoot: threadRoot,
|
||||
extraKeyChannelID: payload.ChannelID,
|
||||
}
|
||||
|
||||
if extra[extraKeyThreadRoot] != "root-200" {
|
||||
t.Errorf("Extra thread_root_id = %q, want %q", extra[extraKeyThreadRoot], "root-200")
|
||||
}
|
||||
|
||||
// ThreadID should equal threadRoot
|
||||
threadID := threadRoot
|
||||
if threadID != "root-200" {
|
||||
t.Errorf("ThreadID = %q, want %q", threadID, "root-200")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFileIDs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw json.RawMessage
|
||||
want []string
|
||||
}{
|
||||
{"array", json.RawMessage(`["f1","f2"]`), []string{"f1", "f2"}},
|
||||
{"string", json.RawMessage(`"f3"`), []string{"f3"}},
|
||||
{"empty", nil, nil},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := parseFileIDs(tt.raw)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Fatalf("parseFileIDs() len = %d, want %d", len(got), len(tt.want))
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Errorf("parseFileIDs()[%d] = %q, want %q", i, got[i], tt.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,37 @@ func (c *Client) CreatePost(ctx context.Context, channelID, rootID, message stri
|
||||
return created.ID, nil
|
||||
}
|
||||
|
||||
// GetPost fetches a post by ID, returning its root_id (empty if top-level).
|
||||
func (c *Client) GetPost(ctx context.Context, postID string) (rootID string, err error) {
|
||||
url := fmt.Sprintf("%s/posts/%s", c.baseURL, postID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
c.authHeader(req)
|
||||
req.Header.Del("Content-Type")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("mattermost get post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody))
|
||||
}
|
||||
|
||||
var post struct {
|
||||
ID string `json:"id"`
|
||||
RootID string `json:"root_id"`
|
||||
}
|
||||
if err := json.Unmarshal(respBody, &post); err != nil {
|
||||
return "", fmt.Errorf("decode get post: %w", err)
|
||||
}
|
||||
return post.RootID, nil
|
||||
}
|
||||
|
||||
// PatchPostMessage updates a post's message field.
|
||||
func (c *Client) PatchPostMessage(ctx context.Context, postID, message string) error {
|
||||
payload, err := json.Marshal(map[string]string{"message": message})
|
||||
|
||||
+115
-13
@@ -151,7 +151,12 @@ type Service struct {
|
||||
|
||||
// makeUserKey builds the canonical key used to identify a user's request
|
||||
// across the queue, inflight map, and /stop command.
|
||||
func makeUserKey(channelID, userID, chatID string) string {
|
||||
// threadID should only be non-empty when channel.SessionMode == "thread";
|
||||
// callers must guard this to avoid leaking thread scope into user-mode keys.
|
||||
func makeUserKey(channelID, userID, chatID, threadID string) string {
|
||||
if threadID != "" {
|
||||
return fmt.Sprintf("%s:%s:%s:%s", channelID, userID, chatID, threadID)
|
||||
}
|
||||
return fmt.Sprintf("%s:%s:%s", channelID, userID, chatID)
|
||||
}
|
||||
|
||||
@@ -716,6 +721,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
attribute.String("im.platform", string(msg.Platform)),
|
||||
attribute.String("im.user_id", msg.UserID),
|
||||
attribute.String("im.chat_id", msg.ChatID),
|
||||
attribute.String("im.thread_id", msg.ThreadID),
|
||||
attribute.String("im.message_type", string(msg.MessageType)),
|
||||
)
|
||||
|
||||
@@ -752,12 +758,21 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
}
|
||||
}
|
||||
|
||||
span.SetAttributes(attribute.String("im.session_mode", channel.SessionMode))
|
||||
|
||||
// Resolve threadID for key building — only include in thread mode to avoid
|
||||
// leaking thread scope into user-mode rate limit / inflight keys.
|
||||
threadID := ""
|
||||
if channel.SessionMode == string(SessionModeThread) {
|
||||
threadID = msg.ThreadID
|
||||
}
|
||||
|
||||
// Rate limit: enforce per-user sliding window to prevent abuse.
|
||||
// Slash-commands (/stop, /clear, etc.) bypass rate limiting so the user
|
||||
// always retains control over the bot even under heavy messaging.
|
||||
isCommand := s.cmdRegistry.IsRegistered(msg.Content)
|
||||
if !isCommand {
|
||||
rateLimitKey := makeUserKey(channelID, msg.UserID, msg.ChatID)
|
||||
rateLimitKey := makeUserKey(channelID, msg.UserID, msg.ChatID, threadID)
|
||||
if !s.rateLimiter.Allow(rateLimitKey) {
|
||||
logger.Warnf(ctx, "[IM] Rate limited: channel=%s user=%s chat=%s", channelID, msg.UserID, msg.ChatID)
|
||||
_ = adapter.SendReply(ctx, msg, &ReplyMessage{
|
||||
@@ -792,7 +807,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
sessionCtx = context.WithValue(sessionCtx, types.TenantInfoContextKey, tenant)
|
||||
|
||||
// 2. Resolve or create a WeKnora session
|
||||
channelSession, err := s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID)
|
||||
channelSession, err := s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID, channel.SessionMode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve session: %w", err)
|
||||
}
|
||||
@@ -831,7 +846,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
||||
// 5. Enqueue the QA request into the bounded worker pool.
|
||||
// The worker pool controls LLM concurrency and provides backpressure.
|
||||
qaCtx, qaCancel := context.WithCancel(sessionCtx)
|
||||
userKey := makeUserKey(channelID, msg.UserID, msg.ChatID)
|
||||
userKey := makeUserKey(channelID, msg.UserID, msg.ChatID, threadID)
|
||||
|
||||
req := &qaRequest{
|
||||
ctx: qaCtx,
|
||||
@@ -1000,7 +1015,11 @@ func (s *Service) handleCommand(
|
||||
logger.Warnf(ctx, "[IM] Failed to clear session context: %v", err)
|
||||
}
|
||||
case ActionStop:
|
||||
inflightKey := makeUserKey(channel.ID, msg.UserID, msg.ChatID)
|
||||
stopThreadID := ""
|
||||
if channel.SessionMode == string(SessionModeThread) {
|
||||
stopThreadID = msg.ThreadID
|
||||
}
|
||||
inflightKey := makeUserKey(channel.ID, msg.UserID, msg.ChatID, stopThreadID)
|
||||
|
||||
// 1. Try local cancel: remove from queue or cancel in-flight.
|
||||
var localSessionID, localMessageID string
|
||||
@@ -1080,9 +1099,20 @@ func (s *Service) sendStreamReply(ctx context.Context, msg *IncomingMessage, str
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveSession finds or creates a ChannelSession for the given IM message.
|
||||
// ctx must already carry TenantIDContextKey and TenantInfoContextKey.
|
||||
func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||
// resolveSession dispatches to the appropriate session resolution strategy
|
||||
// based on the channel's session mode.
|
||||
func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string, sessionMode string) (*ChannelSession, error) {
|
||||
switch SessionMode(sessionMode) {
|
||||
case SessionModeThread:
|
||||
return s.resolveThreadSession(ctx, msg, tenantID, agentID, imChannelID)
|
||||
default: // SessionModeUser
|
||||
return s.resolveUserSession(ctx, msg, tenantID, agentID, imChannelID)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id).
|
||||
// This is the original session resolution strategy.
|
||||
func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||
var cs ChannelSession
|
||||
result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), msg.UserID, msg.ChatID, tenantID).
|
||||
@@ -1125,14 +1155,9 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena
|
||||
IMChannelID: imChannelID,
|
||||
}
|
||||
if err := s.db.Create(&cs).Error; err != nil {
|
||||
// The insert failed (likely unique constraint from a concurrent request on
|
||||
// another instance). Clean up the orphaned Session we just created — it has
|
||||
// no messages yet, so a direct delete is safe.
|
||||
if delErr := s.db.Where("id = ?", createdSession.ID).Delete(createdSession).Error; delErr != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to clean up orphaned session %s: %v", createdSession.ID, delErr)
|
||||
}
|
||||
|
||||
// Fetch the existing ChannelSession created by the winning instance.
|
||||
var existing ChannelSession
|
||||
if findErr := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), msg.UserID, msg.ChatID, tenantID).
|
||||
@@ -1148,6 +1173,83 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
// resolveThreadSession finds or creates a ChannelSession keyed by (platform, chat_id, thread_id, tenant_id).
|
||||
// In thread mode, each message thread gets its own session. Multiple users in the
|
||||
// same thread share the same session. Top-level messages use their own ID as
|
||||
// ThreadID, creating a new session per top-level message.
|
||||
func (s *Service) resolveThreadSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||
threadID := msg.ThreadID
|
||||
if threadID == "" {
|
||||
// Defense-in-depth: frontend blocks thread mode for unsupported platforms,
|
||||
// but if ThreadID is somehow empty, fall back to user-mode resolution
|
||||
// to avoid creating a shared session for all empty-thread messages.
|
||||
logger.Warnf(ctx, "[IM] Thread mode but ThreadID is empty (platform=%s chat=%s), falling back to user session", msg.Platform, msg.ChatID)
|
||||
return s.resolveUserSession(ctx, msg, tenantID, agentID, imChannelID)
|
||||
}
|
||||
|
||||
var cs ChannelSession
|
||||
result := s.db.Where(
|
||||
"platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), threadID, msg.ChatID, tenantID,
|
||||
).First(&cs)
|
||||
|
||||
if result.Error == nil {
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
if result.Error != gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("query thread session: %w", result.Error)
|
||||
}
|
||||
|
||||
// Build a session title with thread ID suffix for traceability.
|
||||
threadSuffix := threadID
|
||||
if len(threadSuffix) > 8 {
|
||||
threadSuffix = threadSuffix[len(threadSuffix)-8:]
|
||||
}
|
||||
title := fmt.Sprintf("IM-%s-thread-%s", msg.Platform, threadSuffix)
|
||||
|
||||
newSession := &types.Session{
|
||||
TenantID: tenantID,
|
||||
Title: title,
|
||||
Description: fmt.Sprintf("Thread-based session from %s IM", msg.Platform),
|
||||
}
|
||||
|
||||
createdSession, err := s.sessionService.CreateSession(ctx, newSession)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
|
||||
cs = ChannelSession{
|
||||
Platform: string(msg.Platform),
|
||||
UserID: msg.UserID, // record the first creator
|
||||
ChatID: msg.ChatID,
|
||||
ThreadID: threadID,
|
||||
SessionID: createdSession.ID,
|
||||
TenantID: tenantID,
|
||||
AgentID: agentID,
|
||||
IMChannelID: imChannelID,
|
||||
}
|
||||
|
||||
if err := s.db.Create(&cs).Error; err != nil {
|
||||
// Unique constraint fallback for concurrent creation.
|
||||
if delErr := s.db.Where("id = ?", createdSession.ID).Delete(createdSession).Error; delErr != nil {
|
||||
logger.Warnf(ctx, "[IM] Failed to clean up orphaned session %s: %v", createdSession.ID, delErr)
|
||||
}
|
||||
var existing ChannelSession
|
||||
if findErr := s.db.Where(
|
||||
"platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND deleted_at IS NULL",
|
||||
string(msg.Platform), msg.ChatID, threadID, tenantID,
|
||||
).First(&existing).Error; findErr != nil {
|
||||
return nil, fmt.Errorf("create thread session: %w (lookup fallback: %v)", err, findErr)
|
||||
}
|
||||
return &existing, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[IM] Created new thread session: platform=%s thread=%s chat=%s -> session=%s",
|
||||
msg.Platform, threadID, msg.ChatID, createdSession.ID)
|
||||
return &cs, nil
|
||||
}
|
||||
|
||||
// ── Agent tool call progress formatting ──────────────────────────────
|
||||
// These helpers format tool-call / tool-result events as Markdown text
|
||||
// that is injected into the streaming reply so IM users can see the
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package im
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMakeUserKey_UserMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
channelID string
|
||||
userID string
|
||||
chatID string
|
||||
threadID string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "user mode with empty threadID",
|
||||
channelID: "ch-1",
|
||||
userID: "user-1",
|
||||
chatID: "chat-1",
|
||||
threadID: "",
|
||||
want: "ch-1:user-1:chat-1",
|
||||
},
|
||||
{
|
||||
name: "user mode with empty chatID (DM)",
|
||||
channelID: "ch-1",
|
||||
userID: "user-1",
|
||||
chatID: "",
|
||||
threadID: "",
|
||||
want: "ch-1:user-1:",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := makeUserKey(tt.channelID, tt.userID, tt.chatID, tt.threadID)
|
||||
if got != tt.want {
|
||||
t.Errorf("makeUserKey() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMakeUserKey_ThreadMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
channelID string
|
||||
userID string
|
||||
chatID string
|
||||
threadID string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "thread mode with Slack thread_ts",
|
||||
channelID: "ch-1",
|
||||
userID: "user-1",
|
||||
chatID: "chat-1",
|
||||
threadID: "1234567890.123456",
|
||||
want: "ch-1:user-1:chat-1:1234567890.123456",
|
||||
},
|
||||
{
|
||||
name: "thread mode with Mattermost root_id",
|
||||
channelID: "ch-2",
|
||||
userID: "user-2",
|
||||
chatID: "chat-2",
|
||||
threadID: "abc123def456",
|
||||
want: "ch-2:user-2:chat-2:abc123def456",
|
||||
},
|
||||
{
|
||||
name: "thread mode with Telegram topic ID",
|
||||
channelID: "ch-3",
|
||||
userID: "user-3",
|
||||
chatID: "chat-3",
|
||||
threadID: "42",
|
||||
want: "ch-3:user-3:chat-3:42",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := makeUserKey(tt.channelID, tt.userID, tt.chatID, tt.threadID)
|
||||
if got != tt.want {
|
||||
t.Errorf("makeUserKey() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMakeUserKey_ThreadIDGuard(t *testing.T) {
|
||||
// Verify that the same user+chat produces different keys with different threadIDs
|
||||
keyA := makeUserKey("ch", "user", "chat", "thread-A")
|
||||
keyB := makeUserKey("ch", "user", "chat", "thread-B")
|
||||
keyNone := makeUserKey("ch", "user", "chat", "")
|
||||
|
||||
if keyA == keyB {
|
||||
t.Error("different threadIDs should produce different keys")
|
||||
}
|
||||
if keyA == keyNone {
|
||||
t.Error("thread key should differ from non-thread key")
|
||||
}
|
||||
if keyB == keyNone {
|
||||
t.Error("thread key should differ from non-thread key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMakeUserKey_SameThreadDifferentUsers(t *testing.T) {
|
||||
// In thread mode, different users in the same thread produce different keys
|
||||
// (this is intentional: /stop only cancels the caller's own request)
|
||||
keyUserA := makeUserKey("ch", "alice", "chat", "thread-1")
|
||||
keyUserB := makeUserKey("ch", "bob", "chat", "thread-1")
|
||||
|
||||
if keyUserA == keyUserB {
|
||||
t.Error("different users in same thread should have different keys")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncomingMessageThreadID(t *testing.T) {
|
||||
// Verify ThreadID field works correctly on IncomingMessage
|
||||
msg := &IncomingMessage{
|
||||
Platform: PlatformSlack,
|
||||
UserID: "U123",
|
||||
ChatID: "C456",
|
||||
MessageID: "1234567890.123456",
|
||||
ThreadID: "1234567890.123456",
|
||||
}
|
||||
|
||||
if msg.ThreadID != msg.MessageID {
|
||||
t.Errorf("Slack ThreadID should equal MessageID for top-level, got ThreadID=%q MessageID=%q",
|
||||
msg.ThreadID, msg.MessageID)
|
||||
}
|
||||
|
||||
// Mattermost: ThreadID from Extra
|
||||
msgMM := &IncomingMessage{
|
||||
Platform: PlatformMattermost,
|
||||
UserID: "user-1",
|
||||
ChatID: "channel-1",
|
||||
MessageID: "post-123",
|
||||
ThreadID: "root-456",
|
||||
Extra: map[string]string{
|
||||
"thread_root_id": "root-456",
|
||||
},
|
||||
}
|
||||
|
||||
if msgMM.ThreadID != msgMM.Extra["thread_root_id"] {
|
||||
t.Error("Mattermost ThreadID should match Extra thread_root_id")
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ func parseIncomingMessage(user, channel, text, ts string, chatType im.ChatType,
|
||||
ChatType: chatType,
|
||||
Content: strings.TrimSpace(content),
|
||||
MessageID: ts,
|
||||
ThreadID: ts,
|
||||
}
|
||||
|
||||
if len(files) > 0 {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package slack
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
slacklib "github.com/slack-go/slack"
|
||||
)
|
||||
|
||||
func TestParseIncomingMessage_ThreadID(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ts string
|
||||
wantThreadID string
|
||||
wantMessageID string
|
||||
}{
|
||||
{
|
||||
name: "top-level message uses own timestamp",
|
||||
ts: "1234567890.123456",
|
||||
wantThreadID: "1234567890.123456",
|
||||
wantMessageID: "1234567890.123456",
|
||||
},
|
||||
{
|
||||
name: "threaded reply uses thread_ts",
|
||||
ts: "1234567890.000001",
|
||||
wantThreadID: "1234567890.000001",
|
||||
wantMessageID: "1234567890.000001",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
msg := parseIncomingMessage("U123", "C456", "hello", tt.ts, im.ChatTypeGroup, nil)
|
||||
|
||||
if msg.ThreadID != tt.wantThreadID {
|
||||
t.Errorf("ThreadID = %q, want %q", msg.ThreadID, tt.wantThreadID)
|
||||
}
|
||||
if msg.MessageID != tt.wantMessageID {
|
||||
t.Errorf("MessageID = %q, want %q", msg.MessageID, tt.wantMessageID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseIncomingMessage_ThreadID_WithFiles(t *testing.T) {
|
||||
files := []slacklib.File{
|
||||
{ID: "F123", Name: "test.pdf", Size: 1024, Mimetype: "application/pdf"},
|
||||
}
|
||||
|
||||
msg := parseIncomingMessage("U123", "C456", "", "1234567890.999", im.ChatTypeDirect, files)
|
||||
|
||||
if msg.ThreadID != "1234567890.999" {
|
||||
t.Errorf("ThreadID = %q, want %q", msg.ThreadID, "1234567890.999")
|
||||
}
|
||||
if msg.MessageType != im.MessageTypeFile {
|
||||
t.Errorf("MessageType = %q, want %q", msg.MessageType, im.MessageTypeFile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseIncomingMessage_MentionStripping(t *testing.T) {
|
||||
// Ensure mention stripping doesn't affect ThreadID
|
||||
msg := parseIncomingMessage("U123", "C456", "<@U999> hello world", "ts-123", im.ChatTypeGroup, nil)
|
||||
|
||||
if msg.ThreadID != "ts-123" {
|
||||
t.Errorf("ThreadID = %q, want %q", msg.ThreadID, "ts-123")
|
||||
}
|
||||
if msg.Content != "hello world" {
|
||||
t.Errorf("Content = %q, want %q", msg.Content, "hello world")
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -76,12 +77,13 @@ type telegramUpdate struct {
|
||||
}
|
||||
|
||||
type telegramMsg struct {
|
||||
MessageID int `json:"message_id"`
|
||||
From *telegramUser `json:"from"`
|
||||
Chat telegramChat `json:"chat"`
|
||||
Text string `json:"text"`
|
||||
Document *telegramDoc `json:"document"`
|
||||
Photo []telegramPhoto `json:"photo"`
|
||||
MessageID int `json:"message_id"`
|
||||
MessageThreadID int `json:"message_thread_id"`
|
||||
From *telegramUser `json:"from"`
|
||||
Chat telegramChat `json:"chat"`
|
||||
Text string `json:"text"`
|
||||
Document *telegramDoc `json:"document"`
|
||||
Photo []telegramPhoto `json:"photo"`
|
||||
}
|
||||
|
||||
type telegramUser struct {
|
||||
@@ -154,6 +156,11 @@ func parseTelegramMessage(msg *telegramMsg) *im.IncomingMessage {
|
||||
}
|
||||
}
|
||||
|
||||
threadID := ""
|
||||
if msg.MessageThreadID != 0 {
|
||||
threadID = fmt.Sprintf("%d", msg.MessageThreadID)
|
||||
}
|
||||
|
||||
incoming := &im.IncomingMessage{
|
||||
Platform: im.PlatformTelegram,
|
||||
UserID: userID,
|
||||
@@ -161,6 +168,7 @@ func parseTelegramMessage(msg *telegramMsg) *im.IncomingMessage {
|
||||
ChatID: chatID,
|
||||
ChatType: chatType,
|
||||
MessageID: fmt.Sprintf("%d", msg.MessageID),
|
||||
ThreadID: threadID,
|
||||
MessageType: im.MessageTypeText,
|
||||
Content: msg.Text,
|
||||
}
|
||||
@@ -206,7 +214,20 @@ func resolveChatID(incoming *im.IncomingMessage) string {
|
||||
// ── Send reply ──
|
||||
|
||||
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
return a.sendMessage(ctx, resolveChatID(incoming), transformThinkBlocks(reply.Content), "")
|
||||
chatID := resolveChatID(incoming)
|
||||
text := transformThinkBlocks(reply.Content)
|
||||
|
||||
body := map[string]interface{}{
|
||||
"chat_id": chatID,
|
||||
"text": text,
|
||||
"parse_mode": "Markdown",
|
||||
}
|
||||
if incoming.ThreadID != "" {
|
||||
if tid, err := strconv.Atoi(incoming.ThreadID); err == nil {
|
||||
body["message_thread_id"] = tid
|
||||
}
|
||||
}
|
||||
return a.callAPI(ctx, "sendMessage", body)
|
||||
}
|
||||
|
||||
func (a *Adapter) sendMessage(ctx context.Context, chatID, text, replyToMessageID string) error {
|
||||
@@ -343,6 +364,11 @@ func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage)
|
||||
"chat_id": chatID,
|
||||
"text": "正在思考...",
|
||||
}
|
||||
if incoming.ThreadID != "" {
|
||||
if tid, err := strconv.Atoi(incoming.ThreadID); err == nil {
|
||||
body["message_thread_id"] = tid
|
||||
}
|
||||
}
|
||||
var sentMsg struct {
|
||||
MessageID int `json:"message_id"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
)
|
||||
|
||||
func TestParseTelegramMessage_ForumTopicThread(t *testing.T) {
|
||||
msg := &telegramMsg{
|
||||
MessageID: 100,
|
||||
MessageThreadID: 42, // Forum topic ID
|
||||
From: &telegramUser{ID: 1001, FirstName: "Alice"},
|
||||
Chat: telegramChat{ID: -9999, Type: "supergroup"},
|
||||
Text: "hello",
|
||||
}
|
||||
|
||||
incoming := parseTelegramMessage(msg)
|
||||
if incoming == nil {
|
||||
t.Fatal("expected non-nil message")
|
||||
}
|
||||
|
||||
if incoming.ThreadID != "42" {
|
||||
t.Errorf("ThreadID = %q, want %q", incoming.ThreadID, "42")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTelegramMessage_NonForumGroup(t *testing.T) {
|
||||
msg := &telegramMsg{
|
||||
MessageID: 200,
|
||||
MessageThreadID: 0, // not a Forum group
|
||||
From: &telegramUser{ID: 1002, FirstName: "Bob"},
|
||||
Chat: telegramChat{ID: -8888, Type: "group"},
|
||||
Text: "hello",
|
||||
}
|
||||
|
||||
incoming := parseTelegramMessage(msg)
|
||||
if incoming == nil {
|
||||
t.Fatal("expected non-nil message")
|
||||
}
|
||||
|
||||
// Non-Forum groups: ThreadID should be empty
|
||||
if incoming.ThreadID != "" {
|
||||
t.Errorf("ThreadID = %q, want empty for non-Forum group", incoming.ThreadID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTelegramMessage_DirectMessage(t *testing.T) {
|
||||
msg := &telegramMsg{
|
||||
MessageID: 300,
|
||||
From: &telegramUser{ID: 1003, FirstName: "Carol"},
|
||||
Chat: telegramChat{ID: 1003, Type: "private"},
|
||||
Text: "hi bot",
|
||||
}
|
||||
|
||||
incoming := parseTelegramMessage(msg)
|
||||
if incoming == nil {
|
||||
t.Fatal("expected non-nil message")
|
||||
}
|
||||
|
||||
if incoming.ThreadID != "" {
|
||||
t.Errorf("ThreadID = %q, want empty for DM", incoming.ThreadID)
|
||||
}
|
||||
if incoming.ChatType != im.ChatTypeDirect {
|
||||
t.Errorf("ChatType = %q, want %q", incoming.ChatType, im.ChatTypeDirect)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTelegramMessage_NilMessage(t *testing.T) {
|
||||
incoming := parseTelegramMessage(nil)
|
||||
if incoming != nil {
|
||||
t.Error("expected nil for nil message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTelegramMessage_Document(t *testing.T) {
|
||||
msg := &telegramMsg{
|
||||
MessageID: 400,
|
||||
MessageThreadID: 7, // in a Forum topic
|
||||
From: &telegramUser{ID: 1004, FirstName: "Dave"},
|
||||
Chat: telegramChat{ID: -7777, Type: "supergroup"},
|
||||
Document: &telegramDoc{
|
||||
FileID: "doc-123",
|
||||
FileName: "report.pdf",
|
||||
FileSize: 2048,
|
||||
},
|
||||
}
|
||||
|
||||
incoming := parseTelegramMessage(msg)
|
||||
if incoming == nil {
|
||||
t.Fatal("expected non-nil message")
|
||||
}
|
||||
|
||||
if incoming.ThreadID != "7" {
|
||||
t.Errorf("ThreadID = %q, want %q", incoming.ThreadID, "7")
|
||||
}
|
||||
if incoming.MessageType != im.MessageTypeFile {
|
||||
t.Errorf("MessageType = %q, want %q", incoming.MessageType, im.MessageTypeFile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUpdate_NilMessage(t *testing.T) {
|
||||
update := &telegramUpdate{UpdateID: 1, Message: nil}
|
||||
incoming := parseUpdate(update)
|
||||
if incoming != nil {
|
||||
t.Error("expected nil for nil update.Message")
|
||||
}
|
||||
}
|
||||
+26
-1
@@ -24,6 +24,7 @@ type IMChannel struct {
|
||||
OutputMode string `json:"output_mode" gorm:"type:varchar(20);not null;default:'stream'"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);default:''"`
|
||||
BotIdentity string `json:"bot_identity" gorm:"type:varchar(255);not null;default:'';uniqueIndex:idx_im_channels_bot_identity,where:deleted_at IS NULL AND bot_identity != ''"`
|
||||
SessionMode string `json:"session_mode" gorm:"type:varchar(20);not null;default:'user'"`
|
||||
Credentials types.JSON `json:"credentials" gorm:"type:jsonb;not null;default:'{}'"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
@@ -48,16 +49,39 @@ func (ch *IMChannel) BeforeCreate(tx *gorm.DB) error {
|
||||
if ch.OutputMode == "" {
|
||||
ch.OutputMode = "stream"
|
||||
}
|
||||
if ch.SessionMode == "" {
|
||||
ch.SessionMode = string(SessionModeUser)
|
||||
}
|
||||
if err := ch.validateSessionMode(); err != nil {
|
||||
return err
|
||||
}
|
||||
ch.BotIdentity = ch.computeBotIdentity()
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeforeSave ensures bot_identity is recomputed on every save (create + update).
|
||||
// BeforeSave ensures bot_identity is recomputed and session_mode is validated
|
||||
// on every save (create + update).
|
||||
func (ch *IMChannel) BeforeSave(tx *gorm.DB) error {
|
||||
if ch.SessionMode == "" {
|
||||
ch.SessionMode = string(SessionModeUser)
|
||||
}
|
||||
if err := ch.validateSessionMode(); err != nil {
|
||||
return err
|
||||
}
|
||||
ch.BotIdentity = ch.computeBotIdentity()
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateSessionMode checks that SessionMode holds a supported value.
|
||||
func (ch *IMChannel) validateSessionMode() error {
|
||||
switch SessionMode(ch.SessionMode) {
|
||||
case SessionModeUser, SessionModeThread:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid session_mode: %s", ch.SessionMode)
|
||||
}
|
||||
}
|
||||
|
||||
// computeBotIdentity derives a unique bot identity string from the channel's
|
||||
// platform, mode, and credentials. Returns "" if no identity can be extracted.
|
||||
func (ch *IMChannel) computeBotIdentity() string {
|
||||
@@ -123,6 +147,7 @@ type ChannelSession struct {
|
||||
Platform string `json:"platform" gorm:"type:varchar(20);not null"`
|
||||
UserID string `json:"user_id" gorm:"type:varchar(128);not null"`
|
||||
ChatID string `json:"chat_id" gorm:"type:varchar(128);not null;default:''"`
|
||||
ThreadID string `json:"thread_id" gorm:"type:varchar(128);not null;default:''"`
|
||||
SessionID string `json:"session_id" gorm:"type:varchar(36);not null;index"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
AgentID string `json:"agent_id" gorm:"type:varchar(36);default:''"`
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package im
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestValidateSessionMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
sessionMode string
|
||||
wantErr bool
|
||||
}{
|
||||
{"user mode", "user", false},
|
||||
{"thread mode", "thread", false},
|
||||
{"empty defaults to user in BeforeCreate", "", false},
|
||||
{"invalid mode", "invalid", true},
|
||||
{"random string", "foo", true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ch := &IMChannel{SessionMode: tt.sessionMode}
|
||||
err := ch.validateSessionMode()
|
||||
|
||||
if tt.sessionMode == "" {
|
||||
// empty is handled by BeforeCreate, not validateSessionMode
|
||||
// validateSessionMode treats empty as invalid
|
||||
if err == nil {
|
||||
t.Error("expected error for empty session_mode in validateSessionMode")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("validateSessionMode(%q) error = %v, wantErr %v", tt.sessionMode, err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIMChannelBeforeCreate_SessionModeDefault(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inputMode string
|
||||
expectedMode string
|
||||
}{
|
||||
{"empty defaults to user", "", "user"},
|
||||
{"user preserved", "user", "user"},
|
||||
{"thread preserved", "thread", "thread"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ch := &IMChannel{
|
||||
TenantID: 1,
|
||||
AgentID: "agent-1",
|
||||
Platform: "slack",
|
||||
SessionMode: tt.inputMode,
|
||||
Credentials: []byte("{}"),
|
||||
}
|
||||
err := ch.BeforeCreate(&gorm.DB{})
|
||||
if err != nil {
|
||||
t.Fatalf("BeforeCreate error: %v", err)
|
||||
}
|
||||
if ch.SessionMode != tt.expectedMode {
|
||||
t.Errorf("SessionMode = %q, want %q", ch.SessionMode, tt.expectedMode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIMChannelBeforeCreate_InvalidSessionMode(t *testing.T) {
|
||||
ch := &IMChannel{
|
||||
TenantID: 1,
|
||||
AgentID: "agent-1",
|
||||
Platform: "slack",
|
||||
SessionMode: "invalid",
|
||||
Credentials: []byte("{}"),
|
||||
}
|
||||
err := ch.BeforeCreate(&gorm.DB{})
|
||||
if err == nil {
|
||||
t.Error("expected error for invalid session_mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIMChannelBeforeSave_SessionModeValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
sessionMode string
|
||||
wantMode string
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty defaults to user", "", "user", false},
|
||||
{"user preserved", "user", "user", false},
|
||||
{"thread preserved", "thread", "thread", false},
|
||||
{"invalid rejected", "invalid", "", true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ch := &IMChannel{
|
||||
SessionMode: tt.sessionMode,
|
||||
Credentials: []byte("{}"),
|
||||
}
|
||||
err := ch.BeforeSave(&gorm.DB{})
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Error("expected error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ch.SessionMode != tt.wantMode {
|
||||
t.Errorf("SessionMode = %q, want %q", ch.SessionMode, tt.wantMode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionModeConstants(t *testing.T) {
|
||||
if SessionModeUser != "user" {
|
||||
t.Errorf("SessionModeUser = %q, want %q", SessionModeUser, "user")
|
||||
}
|
||||
if SessionModeThread != "thread" {
|
||||
t.Errorf("SessionModeThread = %q, want %q", SessionModeThread, "thread")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelSessionThreadIDField(t *testing.T) {
|
||||
cs := ChannelSession{
|
||||
Platform: "slack",
|
||||
UserID: "U123",
|
||||
ChatID: "C456",
|
||||
ThreadID: "1234567890.123456",
|
||||
}
|
||||
if cs.ThreadID != "1234567890.123456" {
|
||||
t.Errorf("ThreadID = %q, want %q", cs.ThreadID, "1234567890.123456")
|
||||
}
|
||||
|
||||
// empty ThreadID for user-mode sessions
|
||||
csUser := ChannelSession{
|
||||
Platform: "slack",
|
||||
UserID: "U123",
|
||||
ChatID: "C456",
|
||||
}
|
||||
if csUser.ThreadID != "" {
|
||||
t.Errorf("ThreadID = %q, want empty", csUser.ThreadID)
|
||||
}
|
||||
}
|
||||
@@ -25,11 +25,11 @@ type ProviderSpec struct {
|
||||
// chatProviderSpecs is the ordered list of provider specs.
|
||||
// Order matters: more specific specs (with ModelMatcher) should come before generic ones.
|
||||
var chatProviderSpecs = []ProviderSpec{
|
||||
// Qwen3 (must be before generic Aliyun — only matches Qwen3 models)
|
||||
// Aliyun Qwen Thinking Models (must be before generic Aliyun)
|
||||
{
|
||||
Provider: provider.ProviderAliyun,
|
||||
ModelMatcher: func(name string) bool { return provider.IsQwen3Model(name) },
|
||||
RequestCustomizer: qwen3RequestCustomizer,
|
||||
ModelMatcher: func(name string) bool { return provider.IsQwenThinkingModel(name) },
|
||||
RequestCustomizer: qwenThinkingRequestCustomizer,
|
||||
},
|
||||
// LKEAP
|
||||
{
|
||||
@@ -53,8 +53,8 @@ var chatProviderSpecs = []ProviderSpec{
|
||||
},
|
||||
// NVIDIA
|
||||
{
|
||||
Provider: provider.ProviderNvidia,
|
||||
EndpointCustomizer: nvidiaEndpointCustomizer,
|
||||
Provider: provider.ProviderNvidia,
|
||||
RequestCustomizer: genericRequestCustomizer,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -95,12 +95,12 @@ type ThinkingChatCompletionRequest struct {
|
||||
|
||||
// --- Customizer functions ---
|
||||
|
||||
// qwen3RequestCustomizer 自定义 Qwen3 请求
|
||||
// Qwen3 模型在非流式请求时需要显式禁用 thinking
|
||||
func qwen3RequestCustomizer(
|
||||
req *openai.ChatCompletionRequest, _ *ChatOptions, isStream bool,
|
||||
// qwenThinkingRequestCustomizer 自定义 Qwen 系列(阿里云)模型的思考请求
|
||||
func qwenThinkingRequestCustomizer(
|
||||
req *openai.ChatCompletionRequest, opts *ChatOptions, isStream bool,
|
||||
) (any, bool) {
|
||||
if !isStream {
|
||||
// Qwen3 模型在非流式请求时需要显式禁用 thinking
|
||||
qwenReq := QwenChatCompletionRequest{
|
||||
ChatCompletionRequest: *req,
|
||||
}
|
||||
@@ -108,7 +108,19 @@ func qwen3RequestCustomizer(
|
||||
qwenReq.EnableThinking = &enableThinking
|
||||
return qwenReq, true
|
||||
}
|
||||
return nil, false
|
||||
|
||||
// 流式请求:根据 opts.Thinking 启用思考
|
||||
qwenReq := QwenChatCompletionRequest{
|
||||
ChatCompletionRequest: *req,
|
||||
}
|
||||
thinking := false
|
||||
if opts != nil && opts.Thinking != nil {
|
||||
thinking = *opts.Thinking
|
||||
}
|
||||
qwenReq.EnableThinking = &thinking
|
||||
|
||||
// 必须返回 true 以使用 raw HTTP,否则 SDK 会过滤掉 enable_thinking 字段
|
||||
return qwenReq, true
|
||||
}
|
||||
|
||||
// lkeapRequestCustomizer 自定义 LKEAP 请求
|
||||
@@ -183,9 +195,3 @@ func volcengineRequestCustomizer(
|
||||
|
||||
return vcReq, true
|
||||
}
|
||||
|
||||
// nvidiaEndpointCustomizer 自定义 NVIDIA 请求地址
|
||||
// NVIDIA 模型使用 BaseURL 作为完整请求地址
|
||||
func nvidiaEndpointCustomizer(baseURL string, _ string, _ bool) string {
|
||||
return baseURL
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
// Uses SSRFSafeDialContext to prevent DNS rebinding attacks at the connection layer.
|
||||
var rawHTTPClient = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: secutils.SSRFSafeDialContext,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
|
||||
@@ -54,10 +54,14 @@ func (p *AliyunProvider) ValidateConfig(config *Config) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsQwen3Model 检查模型名是否为 Qwen3 模型
|
||||
// Qwen3 模型需要特殊处理 enable_thinking 参数
|
||||
func IsQwen3Model(modelName string) bool {
|
||||
return strings.HasPrefix(modelName, "qwen3-")
|
||||
// IsQwenThinkingModel 检查模型名是否为支持思维链的 Qwen 模型
|
||||
// 支持思维链的模型需要特殊处理 enable_thinking 参数
|
||||
func IsQwenThinkingModel(modelName string) bool {
|
||||
lowerName := strings.ToLower(modelName)
|
||||
return strings.HasPrefix(lowerName, "qwen3") ||
|
||||
strings.HasPrefix(lowerName, "qwen-plus") ||
|
||||
strings.HasPrefix(lowerName, "qwen-max") ||
|
||||
strings.HasPrefix(lowerName, "qwen-turbo")
|
||||
}
|
||||
|
||||
// IsDeepSeekModel 检查模型名是否为 DeepSeek 模型
|
||||
|
||||
@@ -8,9 +8,7 @@ import (
|
||||
|
||||
const (
|
||||
// NvidiaChatBaseURL NVIDIA Chat 的默认 BaseURL
|
||||
NvidiaChatBaseURL = "https://integrate.api.nvidia.com/v1/chat/completions"
|
||||
// NvidiaVLMBaseURL NVIDIA VLM 的默认 BaseURL
|
||||
NvidiaVLMBaseURL = "https://integrate.api.nvidia.com/v1"
|
||||
NvidiaChatBaseURL = "https://integrate.api.nvidia.com/v1"
|
||||
// NvidiaRerankBaseURL NVIDIA Rerank 的默认 BaseURL
|
||||
NvidiaRerankBaseURL = "https://ai.api.nvidia.com/v1/retrieval/nvidia/reranking"
|
||||
)
|
||||
@@ -32,7 +30,7 @@ func (p *NvidiaProvider) Info() ProviderInfo {
|
||||
types.ModelTypeKnowledgeQA: NvidiaChatBaseURL,
|
||||
types.ModelTypeEmbedding: NvidiaChatBaseURL,
|
||||
types.ModelTypeRerank: NvidiaRerankBaseURL,
|
||||
types.ModelTypeVLLM: NvidiaVLMBaseURL,
|
||||
types.ModelTypeVLLM: NvidiaChatBaseURL,
|
||||
},
|
||||
ModelTypes: []types.ModelType{
|
||||
types.ModelTypeKnowledgeQA,
|
||||
|
||||
@@ -54,6 +54,10 @@ type AgentConfig struct {
|
||||
// The agent compresses older messages to stay within this limit,
|
||||
// preserving tool_call/tool_result pairs.
|
||||
MaxContextTokens int `json:"max_context_tokens,omitempty"`
|
||||
|
||||
// Whether to execute independent tool calls in parallel (default: false).
|
||||
// When enabled and the LLM returns multiple tool calls, they run concurrently via errgroup.
|
||||
ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
|
||||
}
|
||||
|
||||
// SessionAgentConfig represents session-level agent configuration
|
||||
|
||||
@@ -47,7 +47,8 @@ const (
|
||||
ModelSourceSiliconFlow ModelSource = "siliconflow" // SiliconFlow model
|
||||
ModelSourceJina ModelSource = "jina" // Jina AI model
|
||||
ModelSourceOpenRouter ModelSource = "openrouter" // OpenRouter model
|
||||
ModelSourceNovita ModelSource = "novita" // Novita AI model
|
||||
ModelSourceNvidia ModelSource = "nvidia" // NVIDIA model
|
||||
ModelSourceNovita ModelSource = "novita" // Novita AI model
|
||||
)
|
||||
|
||||
// EmbeddingParameters represents the embedding parameters for a model
|
||||
@@ -61,9 +62,9 @@ type ModelParameters struct {
|
||||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
InterfaceType string `yaml:"interface_type" json:"interface_type"`
|
||||
EmbeddingParameters EmbeddingParameters `yaml:"embedding_parameters" json:"embedding_parameters"`
|
||||
ParameterSize string `yaml:"parameter_size" json:"parameter_size"` // Ollama model parameter size (e.g., "7B", "13B", "70B")
|
||||
Provider string `yaml:"provider" json:"provider"` // Provider identifier: openai, aliyun, zhipu, generic
|
||||
ExtraConfig map[string]string `yaml:"extra_config" json:"extra_config"` // Provider-specific configuration
|
||||
ParameterSize string `yaml:"parameter_size" json:"parameter_size"` // Ollama model parameter size (e.g., "7B", "13B", "70B")
|
||||
Provider string `yaml:"provider" json:"provider"` // Provider identifier: openai, aliyun, zhipu, generic
|
||||
ExtraConfig map[string]string `yaml:"extra_config" json:"extra_config"` // Provider-specific configuration
|
||||
SupportsVision bool `yaml:"supports_vision" json:"supports_vision"` // Whether the model accepts image/multimodal input
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/net/http/httpproxy"
|
||||
)
|
||||
|
||||
// XSS 防护相关正则表达式
|
||||
@@ -781,7 +783,7 @@ func SSRFSafeDialContext(ctx context.Context, network, addr string) (net.Conn, e
|
||||
|
||||
// Whitelisted hosts bypass all dial-time SSRF checks, consistent with
|
||||
// ValidateURLForSSRF which skips IsSSRFSafeURL for whitelisted hosts.
|
||||
if IsSSRFWhitelisted(host) {
|
||||
if IsSystemProxy(addr) || IsSSRFWhitelisted(host) {
|
||||
dialer := &net.Dialer{
|
||||
Timeout: 30 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
@@ -978,3 +980,22 @@ func ValidateURLForSSRF(rawURL string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsSystemProxy 判断是否为系统代理
|
||||
func IsSystemProxy(host string) bool {
|
||||
proxyCfg := httpproxy.FromEnvironment()
|
||||
for _, proxyUrl := range []string{
|
||||
proxyCfg.HTTPProxy,
|
||||
proxyCfg.HTTPSProxy,
|
||||
} {
|
||||
if proxyUrl == "" {
|
||||
continue
|
||||
}
|
||||
if parse, err := url.Parse(proxyUrl); err == nil {
|
||||
if parse.Host == host {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user