Files
Cyrene_v2/internal/services/backthink/push.go
T
Aska 3e4efa0e41
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat(backthink): 主动推送每次只发一个平台——决策渠道/最近活跃优先,平台含微信
主动推送目标不再取第一个白名单渠道(kook),也不再双目标 web+kook;改为每次只发一个平台,范围=全部已连接白名单渠道(含微信 weixin-ilink)。

backthink/push.go: pusher 单目标路由——web hint 一次 pushActive;im/auto/实体平台 hint 一次性 pushIM (msgs 置哨兵/实体平台),无 IM sink 时诚实降级 pushActive;保留 PushGate 降频与成功 RecordPush。
channelbridge/proactive.go: proactiveTarget 三级选择——①决策 [渠道:xxx] 实体平台且白名单+已连接优先;②最近活跃(主会话最近20条 newest-first 找白名单+已连接平台,web 会话自动跳过);③回退 NextConnectedAccount 用旋转游标避免永远 kook。微信不再排除、可被选中;决策 hint 指定非白名单渠道回退(不报错)。Bridge 新增 proactiveCursor 字段(mu 保护)。
context.go: guidancePrompt 描述改为每次挑一个合适渠道(含微信)。
测试: 决策优先/最近活跃/微信可选中/无信号回退旋转/单目标 等,go build/vet/test 全绿 + windows/darwin 交叉编译。stash@{0} 保留被取代的'web+kook双目标'WIP以备回滚。
2026-09-08 13:34:22 +08:00

332 lines
13 KiB
Go

package backthink
import (
"context"
"fmt"
"log/slog"
"strings"
"sync"
"time"
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/session"
)
// Route identifies how a proactive message was actually delivered, for the
// monitor panel and the push result record.
type Route string
const (
// RouteNone means no push was attempted or no target was available.
RouteNone Route = "none"
// RouteRateLimited means the push was refused by the rate limiter.
RouteRateLimited Route = "rate_limited"
// RouteActiveClient means the message went to an active web/native client.
RouteActiveClient Route = "active_client"
// RouteIMBridge means the message fell back to the IM bridge.
RouteIMBridge Route = "im_bridge"
)
// Channel-hint tokens recognized by the push router. They come from the
// conclusion's [渠道:...] marker (parseProactive) and select where a proactive
// message is delivered. An empty/unknown hint is treated as auto. A concrete
// platform id (kook/telegram/...) is a value other than these three.
const (
channelAuto = "auto"
channelIM = "im"
channelWeb = "web"
// defaultProactivePlatform is the Platform the outbound proactive message
// carries when the conclusion names no specific channel.
defaultProactivePlatform = "cyrene-backthink"
)
// String returns the route as a plain label.
func (r Route) String() string { return string(r) }
// PushResult is the outcome of one proactive push attempt, recorded with each
// thinking pass (design/12 §4).
type PushResult struct {
// Pushed reports whether the message was delivered.
Pushed bool
// Route is the delivery route taken.
Route Route
// Detail is a short human-readable note (e.g. client count, decision reason).
Detail string
// Err is the underlying error text when delivery failed, or that of the
// provider that decided not to push.
Err string
}
// String returns a concise summary for logs.
func (p PushResult) String() string {
if p.Err != "" {
return fmt.Sprintf("pushed=%v route=%s detail=%q err=%q", p.Pushed, p.Route, p.Detail, p.Err)
}
return fmt.Sprintf("pushed=%v route=%s detail=%q", p.Pushed, p.Route, p.Detail)
}
// ActiveClient delivers a proactive message to every currently active web/native
// client and reports how many received it. It is the preferred push target. The
// gateway WebSocket hub implements this in production; tests inject a mock.
type ActiveClient interface {
// SendProactive pushes msg to each active client and returns the number of
// clients that accepted it.
SendProactive(ctx context.Context, msg adapter.UnifiedMessage) (int, error)
}
// IMAdapter is the IM bridge fallback: it pushes a proactive message over an IM
// channel. Every adapter.PlatformAdapter satisfies this subset, so the service
// depends on the narrow interface rather than the concrete adapter type.
type IMAdapter interface {
// SendProactive pushes msg to the owner's IM channel.
SendProactive(ctx context.Context, msg adapter.UnifiedMessage) error
}
// PushGate decides whether a proactive push may proceed right now, applying the
// rate limits of design/11 §6 plus a per-flavor limit and a post-push cooldown. It
// is a seam over channel/session's ProactivePolicy/RateLimiter so the service can
// be tested with a mock.
type PushGate interface {
// Allow reports whether a proactive push of the given kind may be sent now.
Allow(ctx context.Context, kind PushKind) bool
// RecordPush notes a successful delivery so the cooldown/per-kind windows
// start from a real successful push, not a merely-attempted one.
RecordPush(kind PushKind)
}
// PushRequest carries one proactive push attempt: the outbound message plus the
// channel target the autonomous conclusion asked for (design/20 §2 P2).
// ChannelHint is the lowercased [渠道:...] token: ""/auto pick the default (the
// owner mandate: ONE channel, chosen by her / her most recent platform / the
// whitelist default); "web" targets the active client; "im" targets the IM bridge;
// a concrete platform id (kook/telegram/weixin-ilink/...) targets the IM bridge
// with the message tagged for that platform.
type PushRequest struct {
// Message is the normalized outbound proactive message.
Message adapter.UnifiedMessage
// ChannelHint is the requested target channel, "" when she did not choose one.
ChannelHint string
}
// Pusher delivers a proactive message to ONE target channel. It is bounded by the
// rate gate and honors the channel hint the autonomous conclusion selected: "web"
// goes to the active client, everything else goes over the IM bridge a single time,
// where the bridge picks the one channel (her choice → her most recent platform →
// whitelist default, WeChat included).
type Pusher interface {
// Push delivers req to a single target channel, per the channel hint. It never
// blocks on a slow target.
Push(ctx context.Context, req PushRequest) PushResult
}
// pusher is the concrete Pusher: it consults the gate, then routes the message to
// exactly one target — the active client for a "web" hint, otherwise the IM bridge.
type pusher struct {
active ActiveClient
im IMAdapter
gate PushGate
log *slog.Logger
}
// newPusher builds a Pusher from the optional active-client sink, IM sink and
// rate gate. Any of them may be nil; a nil target simply makes that route
// unavailable.
func newPusher(active ActiveClient, im IMAdapter, gate PushGate, log *slog.Logger) *pusher {
return &pusher{active: active, im: im, gate: gate, log: log}
}
// Push implements Pusher: it applies the rate gate, then routes the message to a
// single target. A "web" hint reaches the active web/native client; every other
// hint ("im", "auto", or a concrete platform) goes over the IM bridge once, where
// the bridge selects one owner channel (her [渠道:...] choice, then the platform she
// used most recently, then the whitelist default). The IM bridge is primary, so a
// push never fans out to several channels. When no IM sink is wired the active
// client is the honest fallback, so the owner is still reached rather than the
// message being dropped.
func (p *pusher) Push(ctx context.Context, req PushRequest) PushResult {
if err := ctx.Err(); err != nil {
return PushResult{Pushed: false, Route: RouteNone, Err: err.Error()}
}
kind := classifyPush(req.Message.Content)
if p.gate != nil && !p.gate.Allow(ctx, kind) {
p.log.Warn("backthink push rate limited", "kind", kind.String())
return PushResult{Pushed: false, Route: RouteRateLimited, Detail: "proactive push rate limited"}
}
hint := normalizeChannelHint(req.ChannelHint)
msg := req.Message
var res PushResult
if hint == channelWeb {
res = p.pushActive(ctx, msg)
} else {
// "im"/"auto"/a concrete platform all travel over the IM bridge once. A
// generic hint hands the sentinel platform so the bridge falls through to its
// recent-active / default selection; a concrete hint is honored when the
// channel is whitelisted and connected.
if hint == channelIM || hint == channelAuto {
msg.Platform = defaultProactivePlatform
} else {
msg.Platform = hint
}
res = p.pushIM(ctx, msg)
if !res.Pushed {
res = p.pushActive(ctx, msg)
}
}
// Only a real delivery advances the cooldown/per-kind windows, so an
// attempted-but-failed push does not suppress a later genuine one.
if res.Pushed && p.gate != nil {
p.gate.RecordPush(kind)
}
return annotateHint(res, req.ChannelHint)
}
// pushActive delivers only to the active web/native client.
func (p *pusher) pushActive(ctx context.Context, msg adapter.UnifiedMessage) PushResult {
if p.active != nil {
n, err := p.active.SendProactive(ctx, msg)
if err != nil {
p.log.Warn("backthink active client push failed", "error", err)
} else if n > 0 {
return PushResult{Pushed: true, Route: RouteActiveClient, Detail: fmt.Sprintf("delivered to %d active client(s)", n)}
}
}
return PushResult{Pushed: false, Route: RouteNone, Detail: "no active client"}
}
// pushIM delivers only to the IM bridge.
func (p *pusher) pushIM(ctx context.Context, msg adapter.UnifiedMessage) PushResult {
if p.im == nil {
return PushResult{Pushed: false, Route: RouteNone, Detail: "no IM target"}
}
if err := p.im.SendProactive(ctx, msg); err != nil {
p.log.Warn("backthink IM push failed", "error", err)
return PushResult{Pushed: false, Route: RouteIMBridge, Err: err.Error()}
}
return PushResult{Pushed: true, Route: RouteIMBridge, Detail: "delivered via IM bridge"}
}
// normalizeChannelHint lowercases and trims a channel hint, mapping synonyms to
// the canonical route tokens (auto/im/web); anything else is a concrete platform
// id (kook/telegram/...). Unknown/blank maps to auto.
func normalizeChannelHint(hint string) string {
switch strings.ToLower(strings.TrimSpace(hint)) {
case "", "auto":
return channelAuto
case "im", "bridge":
return channelIM
case "web", "frontend", "active":
return channelWeb
default:
return strings.ToLower(strings.TrimSpace(hint))
}
}
// isSpecificChannel reports whether hint names a concrete platform rather than a
// routing keyword (auto/im/web).
func isSpecificChannel(hint string) bool {
return hint != channelAuto && hint != channelIM && hint != channelWeb
}
// annotateHint appends the requested channel hint to the push result detail so
// the record/panel surfaces which channel she chose, even when the route fell
// back. Blank/auto hints add nothing.
func annotateHint(res PushResult, hint string) PushResult {
h := strings.ToLower(strings.TrimSpace(hint))
if h == "" || h == channelAuto {
return res
}
tag := "channel_hint=" + h
if res.Detail == "" {
res.Detail = tag
} else {
res.Detail = res.Detail + ", " + tag
}
return res
}
// rateGate is the production PushGate: a sliding-window counter over
// session.RateLimiter (design/11 §6 anti-spam rule) combined with a post-push
// cooldown and a per-flavor (问候/提醒/分享/关心) window so the owner is never
// spammed with the same style (design/12 §6 策略二).
type rateGate struct {
log *slog.Logger
limiter *session.RateLimiter
cooldown time.Duration
kindWindow time.Duration
now func() time.Time
mu sync.Mutex
lastPushTime time.Time
lastKind map[PushKind]time.Time
}
// newRateGate builds a gate that allows at most limit pushes within window, keeps
// pushes cooldown apart after a success, and limits each PushKind to one push per
// kindWindow. A non-positive limit or window yields an always-allow limiter (no
// rate rule); a non-positive cooldown or kindWindow disables that specific guard.
func newRateGate(limit int, window, cooldown, kindWindow time.Duration, log *slog.Logger) *rateGate {
return &rateGate{
log: log,
limiter: session.NewRateLimiter(limit, window),
cooldown: cooldown,
kindWindow: kindWindow,
now: time.Now,
lastKind: make(map[PushKind]time.Time),
}
}
// Allow implements PushGate. A canceled context denies (fail closed). It refuses
// when the last successful push is inside the cooldown, or when the same flavor
// was delivered within kindWindow, before consulting the sliding-window limiter.
func (g *rateGate) Allow(ctx context.Context, kind PushKind) bool {
if err := ctx.Err(); err != nil {
return false
}
now := g.now()
g.mu.Lock()
defer g.mu.Unlock()
if !g.lastPushTime.IsZero() && now.Sub(g.lastPushTime) < g.cooldown {
return false
}
if lt, ok := g.lastKind[kind]; ok && now.Sub(lt) < g.kindWindow {
return false
}
return g.limiter.Allow()
}
// RecordPush implements PushGate: it stamps the last successful push time and the
// per-flavor last time so the cooldown and kind window start from a real delivery.
func (g *rateGate) RecordPush(kind PushKind) {
now := g.now()
g.mu.Lock()
defer g.mu.Unlock()
g.lastPushTime = now
g.lastKind[kind] = now
}
// buildProactiveMessage assembles the normalized outbound message carrying a
// think conclusion's clean body. It tags the platform with the requested channel
// when the conclusion names a concrete platform, otherwise the default backthink
// platform. The concrete active-client and IM adapters apply their own
// routing/targeting to the owner (red line: owner only).
//
// The body is run through stripInternalMarkers as a final guard so a structured
// decision/channel marker that survived parsing can never reach the user-facing
// message (only our logs/records may carry it).
func (b *Backthink) buildProactiveMessage(message, channelHint string) adapter.UnifiedMessage {
platform := defaultProactivePlatform
if h := normalizeChannelHint(channelHint); isSpecificChannel(h) {
platform = h
}
return adapter.UnifiedMessage{
Platform: platform,
ChannelType: adapter.ChannelDirect,
Content: stripInternalMarkers(message),
ContentType: adapter.ContentText,
Sender: adapter.Actor{Role: adapter.RoleSystem, DisplayName: "Cyrene"},
Timestamp: b.now(),
}
}