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
+34 -5
View File
@@ -133,11 +133,40 @@ IM 渠道绑定到 Agent,一个 Agent 可接入多个 IM 渠道,所有配置
**第二步:开通权限与事件**
1. **添加应用能力**:在应用详情页 → **添加应用能力** → 添加 **机器人** 能力
2. **配置权限**:在 **权限管理** 中搜索并开通以下权限:
- `im:message` — 获取与发送单聊、群组消息(读写权限)
- `im:message.group_at_msg` — 接收群聊中 @ 机器人消息
- `im:chat` — 获取群组信息(只读权限,群聊场景需要)
- `cardkit:card` — 创建和更新卡片(**流式输出必需**)
2. **配置权限**:在 **权限管理** 中搜索并开通以下权限:你的应用 → 权限管理 → 批量导入,粘贴下面 JSON(原文内容不变):
{
"scopes": {
"tenant": [
"aily:file:read",
"aily:file:write",
"application:application.app_message_stats.overview:readonly",
"application:application:self_manage",
"application:bot.menu:write",
"cardkit:card:write",
"contact:user.employee_id:readonly",
"corehr:file:download",
"docs:document.content:read",
"event:ip_list",
"im:chat",
"im:chat.access_event.bot_p2p_chat:read",
"im:chat.members:bot_access",
"im:message",
"im:message.group_at_msg:readonly",
"im:message.group_msg",
"im:message.p2p_msg:readonly",
"im:message:readonly",
"im:message:send_as_bot",
"im:resource",
"sheets:spreadsheet",
"wiki:wiki:readonly"
],
"user": [
"aily:file:read",
"aily:file:write",
"im:chat.access_event.bot_p2p_chat:read"
]
}
}
3. **配置事件订阅**:
- 在 **事件与回调** → **事件配置** 中,选择请求方式为 **使用长连接接收事件**
- 添加事件 `im.message.receive_v1`(接收消息)
+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)