Files
Cyrene_v2/internal/services/automations/service.go
T
Aska 518bd0a230
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat: admin 端点补齐 + 视觉真推理 + 语音链路 + wire.go 收口(A+B+第3步)
批次A admin 端点(原本 404 变 200 真实数据):
- GET /admin/llm:读 s.cfg.LLM 组 openai+anthropic 两 provider(enabled=当前 Provider、multimodal=配 VisionModel),APIKey 不进 wire 零泄露。
- GET /admin/automations:*automations.Service.List()(reminders+event rules+cron schedules,cron 加只读登记)。
- GET /admin/users:cfg.AdminUser + *auth.APIKey.List()(密钥掩码);无用户存储,恒先返回当前 admin 账号。
- GET /admin/backthink:*backthink.Backthink.List(ctx,50)。均只读、owner/admin RBAC、{data} 信封。

批次B 视觉真推理 + 语音:
- rest.go chatRequest 加 Image?;流式 publishChatStream 带 image;userChatMessages 构造 ImageMessage(model.go:71)。
- loop/vision.go:ImageResolver 可注入(MVP 先看图再对话);run.go Run 开头 resolveImages,无 resolver 透传直交主模型。
- vision/resolver.go:MessageResolver 调 vision.Router.Route——KindMain 保留图片交主模型多模态、KindVisionTool/OCRTool 经 dispatcher.Invoke 折叠成 [图片内容] 文本、KindUnsupported 记日志保留原图不崩。
- gateway/voice.go:VoiceService 接口 + SetVoice 注入点 + handleVoiceInput(未注入回 error 不崩)+ runVoiceTurn 异步 STT→loop chat→TTS→定向 voice_output 帧。
- ws_hub/ws_route:voice_input 接 handleVoiceInput;前端 ws.ts decodeBase64/playVoiceAudio/case voice_output。

第3步 wire.go 收口(唯一碰 wire.go 的一步):
- Deps 补传 Automations:a.automation / Backthink:a.backthink / Users:auth.NewAPIKey(a.cfg.Auth)(*auth.APIKey 原生满足 UserStore,避免 admin 重复的复合类型)。
- gw.SetVoice(a.voice);loop.Options.Vision = vision.NewMessageResolver(router, info, dispatcher.Invoke)(router=NewRouter(WithVisionTool/WithOCRTool)、info=cfg.LLM.VisionModel)。

实机验证:四 admin 端点 200 真实数据(llm 双 provider 脱敏、users=admin,yeij0942,owner);WS 握手正常。go build/vet/test 全绿 + 前端 tsc。wire.go 557 行。
2026-09-06 18:54:05 +08:00

199 lines
5.3 KiB
Go

package automations
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
)
// Service composes the Scheduler (cron), the Engine (event rules) and the
// ReminderStore into a single automation engine with one lifecycle. It routes
// event rules to the Engine and cron rules to the Scheduler by Trigger kind.
type Service struct {
cfg Config
deps Deps
log *slog.Logger
sched *Scheduler
engine *Engine
remind *ReminderStore
mu sync.RWMutex
cronRules map[string]ScheduleID // rule id -> schedule id
cronMeta map[string]Rule // rule id -> cron rule (name/expression for listing)
}
// NewService builds an automation engine from cfg and deps. The bus in deps is
// required. It also resolves the AI pipeline used by AIAction construction.
func NewService(cfg Config, deps Deps) (*Service, error) {
if deps.Bus == nil {
return nil, fmt.Errorf("automations: new service: %w", ErrNilBus)
}
sched, err := New(cfg, deps)
if err != nil {
return nil, err
}
engine, err := NewEngine(cfg, deps)
if err != nil {
return nil, err
}
remind, err := NewReminder(cfg, deps)
if err != nil {
return nil, err
}
return &Service{
cfg: cfg,
deps: deps,
log: sourcedLog(deps.Log),
sched: sched,
engine: engine,
remind: remind,
cronRules: make(map[string]ScheduleID),
cronMeta: make(map[string]Rule),
}, nil
}
// Pipeline returns the service's resolved AI pipeline, or nil when neither a loop
// nor an agent is configured.
func (s *Service) Pipeline() Pipeline { return s.deps.pipeline() }
// Scheduler returns the underlying cron scheduler.
func (s *Service) Scheduler() *Scheduler { return s.sched }
// Engine returns the underlying event rule engine.
func (s *Service) Engine() *Engine { return s.engine }
// ReminderStore returns the underlying reminder store.
func (s *Service) ReminderStore() *ReminderStore { return s.remind }
// AddSchedule delegates to the Scheduler.
func (s *Service) AddSchedule(ctx context.Context, cronExpr string, action Action) (ScheduleID, error) {
return s.sched.AddSchedule(ctx, cronExpr, action)
}
// AddRule routes an event rule to the Engine and a cron rule to the Scheduler. A
// malformed rule returns an error wrapping ErrInvalidRule.
func (s *Service) AddRule(ctx context.Context, r Rule) error {
if !r.valid() {
return fmt.Errorf("automations: add rule %q: %w", r.ID, ErrInvalidRule)
}
switch r.Trigger {
case TriggerEvent:
return s.engine.AddEvent(ctx, r)
case TriggerCron:
id, err := s.sched.AddSchedule(ctx, r.Expression, r.Action)
if err != nil {
return err
}
s.mu.Lock()
s.cronRules[r.ID] = id
s.cronMeta[r.ID] = r
s.mu.Unlock()
return nil
default:
return fmt.Errorf("automations: add rule %q: %w", r.ID, ErrInvalidRule)
}
}
// RemoveRule removes an event or cron rule by id. It returns an error wrapping
// ErrNotFound when no such rule exists.
func (s *Service) RemoveRule(ctx context.Context, id string) error {
s.mu.Lock()
if schedID, ok := s.cronRules[id]; ok {
delete(s.cronRules, id)
delete(s.cronMeta, id)
s.mu.Unlock()
s.sched.RemoveSchedule(schedID)
return nil
}
s.mu.Unlock()
return s.engine.RemoveRule(ctx, id)
}
// AddReminder delegates to the ReminderStore.
func (s *Service) AddReminder(ctx context.Context, r Reminder) error {
return s.remind.Add(ctx, r)
}
// Reminders returns a sorted snapshot of registered reminders.
func (s *Service) Reminders() []Reminder { return s.remind.List() }
// List returns a read-only snapshot of every registered automation and reminder
// for the admin panel, composing the reminder store, the event rules and the
// cron schedules. It never mutates state and is safe for concurrent use. Cron
// entries' LastRun/NextRun are zero until the scheduler has run.
func (s *Service) List() []AutomationRecord {
out := make([]AutomationRecord, 0)
for _, r := range s.remind.List() {
at := r.At
out = append(out, AutomationRecord{
ID: r.ID,
Name: r.Message,
Kind: "reminder",
Enabled: true,
NextRun: at,
})
}
for _, r := range s.engine.Rules() {
out = append(out, AutomationRecord{
ID: r.ID,
Name: r.Name,
Kind: string(r.Trigger),
Enabled: true,
})
}
s.mu.RLock()
for id, rule := range s.cronMeta {
entry := s.sched.Entry(s.cronRules[id])
out = append(out, AutomationRecord{
ID: id,
Name: rule.Name,
Kind: string(rule.Trigger),
Cron: rule.Expression,
Enabled: true,
LastRun: entry.Prev,
NextRun: entry.Next,
})
}
s.mu.RUnlock()
return out
}
// CancelReminder delegates to the ReminderStore.
func (s *Service) CancelReminder(ctx context.Context, id string) error {
return s.remind.Cancel(ctx, id)
}
// Start starts the scheduler, the event engine and the reminder loop.
func (s *Service) Start(ctx context.Context) error {
if err := s.sched.Start(ctx); err != nil {
return err
}
if err := s.engine.Start(ctx); err != nil {
return err
}
return s.remind.Start(ctx)
}
// Stop stops the reminder loop, the event engine and the scheduler, collecting
// errors from each.
func (s *Service) Stop(ctx context.Context) error {
var errs []error
if err := s.remind.Stop(ctx); err != nil {
errs = append(errs, err)
}
if err := s.engine.Stop(ctx); err != nil {
errs = append(errs, err)
}
if err := s.sched.Stop(ctx); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}