feat: enhance IM integration with streaming support and documentation
- add StreamSender interface and streaming output for WeCom/Feishu - refactor WeCom adapter into separate webhook and websocket files - add output_mode config for stream/full toggle per platform - add stream flush batching, dedup cleanup, and think-block filtering - improve context template to handle irrelevant retrieved info gracefully - add IM streaming integration tests - add IM integration documentation with quick start guide
This commit is contained in:
@@ -1,42 +0,0 @@
|
||||
package wecom
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// BotAdapter implements im.Adapter for WeCom intelligent bot (long connection mode).
|
||||
// It delegates SendReply to the WebSocket LongConnClient.
|
||||
// The webhook methods (VerifyCallback, ParseCallback, HandleURLVerification) are no-ops
|
||||
// since messages arrive via WebSocket, not HTTP.
|
||||
type BotAdapter struct {
|
||||
client *LongConnClient
|
||||
}
|
||||
|
||||
// NewBotAdapter creates an adapter backed by a WeCom long connection client.
|
||||
func NewBotAdapter(client *LongConnClient) *BotAdapter {
|
||||
return &BotAdapter{client: client}
|
||||
}
|
||||
|
||||
func (a *BotAdapter) Platform() im.Platform {
|
||||
return im.PlatformWeCom
|
||||
}
|
||||
|
||||
func (a *BotAdapter) VerifyCallback(c *gin.Context) error {
|
||||
return fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
|
||||
}
|
||||
|
||||
func (a *BotAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
return nil, fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
|
||||
}
|
||||
|
||||
func (a *BotAdapter) HandleURLVerification(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *BotAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
return a.client.SendReply(ctx, incoming, reply)
|
||||
}
|
||||
@@ -89,6 +89,12 @@ type LongConnClient struct {
|
||||
mu sync.Mutex
|
||||
closed atomic.Bool
|
||||
reqSeq atomic.Int64
|
||||
|
||||
// streamBufs tracks accumulated content per stream ID.
|
||||
// WeCom stream protocol is replace-based: each frame's content replaces
|
||||
// the previously displayed text, so we must send the full accumulated text.
|
||||
streamBufsMu sync.Mutex
|
||||
streamBufs map[string]*strings.Builder
|
||||
}
|
||||
|
||||
// NewLongConnClient creates a WeCom long connection client.
|
||||
@@ -175,6 +181,86 @@ func (c *LongConnClient) SendReply(ctx context.Context, incoming *im.IncomingMes
|
||||
return c.writeJSON(frame)
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
// Streaming support: send answer chunks over WebSocket in real-time
|
||||
// ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
// StartStream begins a streaming reply session.
|
||||
// Returns a stream ID that must be used in subsequent chunk/end calls.
|
||||
func (c *LongConnClient) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
|
||||
if _, ok := incoming.Extra["req_id"]; !ok {
|
||||
return "", fmt.Errorf("missing req_id in incoming message extra")
|
||||
}
|
||||
streamID := fmt.Sprintf("stream_%d", c.reqSeq.Add(1))
|
||||
|
||||
// Initialize the accumulation buffer for this stream
|
||||
c.streamBufsMu.Lock()
|
||||
if c.streamBufs == nil {
|
||||
c.streamBufs = make(map[string]*strings.Builder)
|
||||
}
|
||||
c.streamBufs[streamID] = &strings.Builder{}
|
||||
c.streamBufsMu.Unlock()
|
||||
|
||||
return streamID, nil
|
||||
}
|
||||
|
||||
// SendStreamChunk accumulates the content and sends the full text so far.
|
||||
// WeCom stream protocol is replace-based: each frame replaces the previous display.
|
||||
func (c *LongConnClient) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
|
||||
if content == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Accumulate
|
||||
c.streamBufsMu.Lock()
|
||||
buf, ok := c.streamBufs[streamID]
|
||||
if !ok {
|
||||
c.streamBufsMu.Unlock()
|
||||
return fmt.Errorf("unknown stream ID: %s", streamID)
|
||||
}
|
||||
buf.WriteString(content)
|
||||
fullContent := buf.String()
|
||||
c.streamBufsMu.Unlock()
|
||||
|
||||
return c.sendStreamFrame(incoming, streamID, fullContent, false)
|
||||
}
|
||||
|
||||
// EndStream sends the final frame with the full accumulated content and cleans up.
|
||||
func (c *LongConnClient) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
|
||||
c.streamBufsMu.Lock()
|
||||
buf, ok := c.streamBufs[streamID]
|
||||
var fullContent string
|
||||
if ok {
|
||||
fullContent = buf.String()
|
||||
delete(c.streamBufs, streamID)
|
||||
}
|
||||
c.streamBufsMu.Unlock()
|
||||
|
||||
return c.sendStreamFrame(incoming, streamID, fullContent, true)
|
||||
}
|
||||
|
||||
func (c *LongConnClient) sendStreamFrame(incoming *im.IncomingMessage, streamID, content string, finish bool) error {
|
||||
reqID := incoming.Extra["req_id"]
|
||||
|
||||
body := streamReplyBody{MsgType: "stream"}
|
||||
body.Stream.ID = streamID
|
||||
body.Stream.Finish = finish
|
||||
body.Stream.Content = content
|
||||
|
||||
bodyBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal stream body: %w", err)
|
||||
}
|
||||
|
||||
frame := wsFrame{
|
||||
Cmd: cmdResponse,
|
||||
Headers: map[string]string{"req_id": reqID},
|
||||
Body: bodyBytes,
|
||||
}
|
||||
|
||||
return c.writeJSON(frame)
|
||||
}
|
||||
|
||||
func (c *LongConnClient) connectAndRun(ctx context.Context) error {
|
||||
conn, _, err := ws.DefaultDialer.DialContext(ctx, wecomWSEndpoint, nil)
|
||||
if err != nil {
|
||||
|
||||
@@ -35,8 +35,9 @@ import (
|
||||
|
||||
var httpClient = &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
// Adapter implements im.Adapter for WeCom.
|
||||
type Adapter struct {
|
||||
// WebhookAdapter implements im.Adapter for WeCom in webhook (self-built app callback) mode.
|
||||
// Messages arrive via HTTP callback; replies are sent via the WeCom REST API.
|
||||
type WebhookAdapter struct {
|
||||
corpID string
|
||||
token string
|
||||
encodingAESKey string
|
||||
@@ -50,15 +51,15 @@ type Adapter struct {
|
||||
tokenExpAt time.Time
|
||||
}
|
||||
|
||||
// NewAdapter creates a new WeCom adapter.
|
||||
func NewAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID int) (*Adapter, error) {
|
||||
// NewWebhookAdapter creates a new WeCom webhook adapter.
|
||||
func NewWebhookAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID int) (*WebhookAdapter, error) {
|
||||
// Decode the AES key from base64
|
||||
aesKey, err := base64.StdEncoding.DecodeString(encodingAESKey + "=")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode encoding_aes_key: %w", err)
|
||||
}
|
||||
|
||||
return &Adapter{
|
||||
return &WebhookAdapter{
|
||||
corpID: corpID,
|
||||
token: token,
|
||||
encodingAESKey: encodingAESKey,
|
||||
@@ -69,12 +70,12 @@ func NewAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID i
|
||||
}
|
||||
|
||||
// Platform returns the platform identifier.
|
||||
func (a *Adapter) Platform() im.Platform {
|
||||
func (a *WebhookAdapter) Platform() im.Platform {
|
||||
return im.PlatformWeCom
|
||||
}
|
||||
|
||||
// VerifyCallback verifies the WeCom callback signature.
|
||||
func (a *Adapter) VerifyCallback(c *gin.Context) error {
|
||||
func (a *WebhookAdapter) VerifyCallback(c *gin.Context) error {
|
||||
timestamp := c.Query("timestamp")
|
||||
nonce := c.Query("nonce")
|
||||
msgSignature := c.Query("msg_signature")
|
||||
@@ -105,7 +106,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
|
||||
}
|
||||
|
||||
// HandleURLVerification handles the WeCom URL verification (GET request).
|
||||
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
func (a *WebhookAdapter) HandleURLVerification(c *gin.Context) bool {
|
||||
if c.Request.Method != http.MethodGet {
|
||||
return false
|
||||
}
|
||||
@@ -128,7 +129,7 @@ func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
|
||||
}
|
||||
|
||||
// ParseCallback parses a WeCom callback into a unified IncomingMessage.
|
||||
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
func (a *WebhookAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
bodyBytes, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read body: %w", err)
|
||||
@@ -181,7 +182,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
// SendReply sends a reply message via WeCom API.
|
||||
// For simplicity, this uses the "应用消息" API to proactively send messages.
|
||||
// A production implementation would integrate with the streaming callback model.
|
||||
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
func (a *WebhookAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
// Get access token
|
||||
accessToken, err := a.getAccessToken(ctx)
|
||||
if err != nil {
|
||||
@@ -235,7 +236,7 @@ func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, r
|
||||
|
||||
// getAccessToken retrieves the WeCom access token with caching.
|
||||
// WeCom tokens expire in 7200 seconds (2 hours); we cache with a safety margin.
|
||||
func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
|
||||
func (a *WebhookAdapter) getAccessToken(ctx context.Context) (string, error) {
|
||||
a.tokenMu.Lock()
|
||||
defer a.tokenMu.Unlock()
|
||||
|
||||
@@ -282,7 +283,7 @@ func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
|
||||
}
|
||||
|
||||
// verifySignature verifies the WeCom callback signature using constant-time comparison.
|
||||
func (a *Adapter) verifySignature(signature, timestamp, nonce, encrypt string) bool {
|
||||
func (a *WebhookAdapter) verifySignature(signature, timestamp, nonce, encrypt string) bool {
|
||||
parts := []string{a.token, timestamp, nonce, encrypt}
|
||||
sort.Strings(parts)
|
||||
combined := strings.Join(parts, "")
|
||||
@@ -295,7 +296,7 @@ func (a *Adapter) verifySignature(signature, timestamp, nonce, encrypt string) b
|
||||
}
|
||||
|
||||
// decrypt decrypts a WeCom AES-encrypted message.
|
||||
func (a *Adapter) decrypt(encrypted string) ([]byte, error) {
|
||||
func (a *WebhookAdapter) decrypt(encrypted string) ([]byte, error) {
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("base64 decode: %w", err)
|
||||
@@ -0,0 +1,62 @@
|
||||
package wecom
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/im"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Compile-time checks.
|
||||
var (
|
||||
_ im.Adapter = (*WSAdapter)(nil)
|
||||
_ im.StreamSender = (*WSAdapter)(nil)
|
||||
)
|
||||
|
||||
// WSAdapter implements im.Adapter and im.StreamSender for WeCom in WebSocket
|
||||
// (long connection) mode. It delegates to the WebSocket LongConnClient.
|
||||
// The webhook methods (VerifyCallback, ParseCallback, HandleURLVerification) are no-ops
|
||||
// since messages arrive via WebSocket, not HTTP.
|
||||
type WSAdapter struct {
|
||||
client *LongConnClient
|
||||
}
|
||||
|
||||
// NewWSAdapter creates an adapter backed by a WeCom long connection client.
|
||||
func NewWSAdapter(client *LongConnClient) *WSAdapter {
|
||||
return &WSAdapter{client: client}
|
||||
}
|
||||
|
||||
func (a *WSAdapter) Platform() im.Platform {
|
||||
return im.PlatformWeCom
|
||||
}
|
||||
|
||||
func (a *WSAdapter) VerifyCallback(c *gin.Context) error {
|
||||
return fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
|
||||
}
|
||||
|
||||
func (a *WSAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
|
||||
return nil, fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
|
||||
}
|
||||
|
||||
func (a *WSAdapter) HandleURLVerification(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *WSAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
|
||||
return a.client.SendReply(ctx, incoming, reply)
|
||||
}
|
||||
|
||||
// ── StreamSender implementation ──
|
||||
|
||||
func (a *WSAdapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
|
||||
return a.client.StartStream(ctx, incoming)
|
||||
}
|
||||
|
||||
func (a *WSAdapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
|
||||
return a.client.SendStreamChunk(ctx, incoming, streamID, content)
|
||||
}
|
||||
|
||||
func (a *WSAdapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
|
||||
return a.client.EndStream(ctx, incoming, streamID)
|
||||
}
|
||||
Reference in New Issue
Block a user