feat(im): enhance message handling and formatting for Feishu compatibility

- Updated the message streaming logic to handle <think> blocks more effectively, ensuring proper formatting for Feishu.
- Introduced a new transformThinkBlocks function to convert <think> content into Feishu-compatible markdown blockquotes.
- Improved the handling of tool call events to prevent duplicate processing and ensure correct message formatting.
- Enhanced documentation for permission configuration in the IM channel setup.
This commit is contained in:
wizardchen
2026-03-18 20:12:49 +08:00
committed by lyingbug
parent 3de78dc3e8
commit 2a63b58deb
3 changed files with 153 additions and 14 deletions
+74 -1
View File
@@ -581,6 +581,8 @@ func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage)
}
// SendStreamChunk accumulates content and pushes it to the card element.
// Content containing <think>...</think> blocks is transformed into
// Feishu-compatible markdown blockquotes before sending.
func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
if content == "" {
return nil
@@ -595,7 +597,7 @@ func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMess
state.mu.Lock()
state.content.WriteString(content)
fullContent := state.content.String()
fullContent := transformThinkBlocks(state.content.String())
seq := state.nextSeq()
state.mu.Unlock()
@@ -607,6 +609,77 @@ func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMess
return a.cardkitUpdateElement(ctx, accessToken, streamID, streamingElementID, fullContent, seq)
}
// transformThinkBlocks converts <think>...</think> blocks into Feishu-compatible
// markdown blockquotes. Handles both complete blocks and in-progress blocks
// (where </think> has not yet arrived during streaming).
//
// Output format (matching the OpenClaw Feishu convention):
//
// > 💭 **思考过程**
// > thinking line 1
// > thinking line 2
//
// ---
//
// answer text
func transformThinkBlocks(content string) string {
const (
openTag = "<think>"
closeTag = "</think>"
)
openIdx := strings.Index(content, openTag)
if openIdx < 0 {
return content
}
before := content[:openIdx]
after := content[openIdx+len(openTag):]
closeIdx := strings.Index(after, closeTag)
thinkClosed := closeIdx >= 0
var thinkContent, rest string
if thinkClosed {
thinkContent = after[:closeIdx]
rest = after[closeIdx+len(closeTag):]
} else {
thinkContent = after
}
thinkContent = strings.TrimSpace(thinkContent)
var result strings.Builder
result.WriteString(before)
if thinkContent == "" {
if !thinkClosed {
result.WriteString("> 💭 **思考中...**\n")
return result.String()
}
result.WriteString(strings.TrimLeft(rest, "\n"))
return result.String()
}
// Render each line as a blockquote
result.WriteString("> 💭 **思考过程**\n")
for _, line := range strings.Split(thinkContent, "\n") {
result.WriteString("> ")
result.WriteString(line)
result.WriteString("\n")
}
if thinkClosed {
rest = strings.TrimLeft(rest, "\n")
if rest != "" {
result.WriteString("\n---\n\n")
result.WriteString(rest)
}
}
return result.String()
}
// EndStream disables streaming_mode and cleans up state.
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
feishuStreamsMu.Lock()
+45 -8
View File
@@ -566,15 +566,43 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
closeOnce sync.Once
thinkBlockOpen bool // whether we've opened a <think> block (agent pipeline)
answerStarted bool // whether the final answer stream has begun
// seenToolCalls deduplicates EventAgentToolCall events.
// The engine emits tool calls twice: once during streaming (pending)
// and once at execution time. We only show the first occurrence.
seenToolCalls = make(map[string]bool)
// lastCharNewline tracks whether the most recently written character
// (across flush boundaries) was '\n'. This lets ensureNewlineBefore
// work correctly even after buf has been Reset by a flush.
lastCharNewline = true
)
closeDone := func() { closeOnce.Do(func() { close(done) }) }
// bufWrite appends s to buf and updates lastCharNewline. Must hold bufMu.
bufWrite := func(s string) {
if s == "" {
return
}
buf.WriteString(s)
lastCharNewline = s[len(s)-1] == '\n'
}
// ensureNewlineBefore guarantees a '\n' exists before the next write,
// even if the previous content was already flushed. Must hold bufMu.
ensureNewlineBefore := func() {
if !lastCharNewline {
buf.WriteByte('\n')
lastCharNewline = true
}
}
// ensureThinkOpen opens a <think> block if not already open.
// Used for agent pipeline to wrap thinking + tool calls. Must hold bufMu.
ensureThinkOpen := func() {
if !thinkBlockOpen {
thinkBlockOpen = true
buf.WriteString("<think>\n")
bufWrite("<think>\n")
}
}
@@ -593,10 +621,10 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
if thinkBlockOpen && !answerStarted {
answerStarted = true
buf.WriteString("\n</think>\n\n")
bufWrite("\n</think>\n\n")
}
buf.WriteString(data.Content)
bufWrite(data.Content)
bufMu.Unlock()
if data.Done {
@@ -626,12 +654,14 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
}
bufMu.Lock()
ensureThinkOpen()
buf.WriteString(data.Content)
bufWrite(data.Content)
bufMu.Unlock()
return nil
})
// Subscribe to agent tool call events — write status line into <think> block
// Subscribe to agent tool call events — write status line into <think> block.
// The engine may emit this event twice per tool call (once during streaming,
// once at execution), so we deduplicate by ToolCallID.
eventBus.On(event.EventAgentToolCall, func(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentToolCallData)
if !ok {
@@ -641,10 +671,16 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
return nil
}
bufMu.Lock()
if seenToolCalls[data.ToolCallID] {
bufMu.Unlock()
return nil
}
seenToolCalls[data.ToolCallID] = true
ensureThinkOpen()
buf.WriteString(formatToolCallStart(data.ToolName))
ensureNewlineBefore()
bufWrite(formatToolCallStart(data.ToolName))
bufMu.Unlock()
logger.Debugf(ctx, "[IM] Tool call streamed to IM: tool=%s", data.ToolName)
logger.Debugf(ctx, "[IM] Tool call streamed to IM: tool=%s id=%s", data.ToolName, data.ToolCallID)
return nil
})
@@ -658,7 +694,8 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage,
return nil
}
bufMu.Lock()
buf.WriteString(formatToolCallResult(data.ToolName, data.Success, data.Output))
ensureNewlineBefore()
bufWrite(formatToolCallResult(data.ToolName, data.Success, data.Output))
bufMu.Unlock()
logger.Debugf(ctx, "[IM] Tool result streamed to IM: tool=%s success=%v duration=%dms",
data.ToolName, data.Success, data.Duration)