批次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 行。
228 lines
7.3 KiB
Go
228 lines
7.3 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/auth"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/session"
|
|
apperr "git.yeij.top/AskaEth/Cyrene_v2/internal/errors"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
|
)
|
|
|
|
// tokenTTL is how long an issued JWT remains valid.
|
|
const tokenTTL = 24 * time.Hour
|
|
|
|
// PersonaSummary is the wire shape of a persona in REST/admin list responses.
|
|
type PersonaSummary struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Character string `json:"character"`
|
|
IsDefault bool `json:"isDefault"`
|
|
Mode string `json:"mode"`
|
|
MemoryNS string `json:"memoryNamespace"`
|
|
}
|
|
|
|
// MemorySummary is the wire shape of a memory entry in the admin list response.
|
|
type MemorySummary struct {
|
|
ID string `json:"id"`
|
|
Scope string `json:"scope"`
|
|
Text string `json:"text"`
|
|
}
|
|
|
|
// SessionSummary is the wire shape of a channel session in list responses.
|
|
type SessionSummary struct {
|
|
Platform string `json:"platform"`
|
|
ChannelID string `json:"channelId"`
|
|
SessionID string `json:"sessionId"`
|
|
ActorRole string `json:"actorRole"`
|
|
Owner bool `json:"owner"`
|
|
IsGroup bool `json:"isGroup"`
|
|
MemWrite bool `json:"memWritable"`
|
|
}
|
|
|
|
// loginRequest is the POST /api/v1/auth/login body.
|
|
type loginRequest struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
// loginResponse is the login success payload.
|
|
type loginResponse struct {
|
|
Token string `json:"token"`
|
|
ExpiresAt int64 `json:"expiresAt"`
|
|
Role string `json:"role"`
|
|
}
|
|
|
|
// chatRequest is the POST /api/v1/chat body. When Stream is true the gateway
|
|
// triggers streaming over the WebSocket channel and returns immediately. Image is
|
|
// an optional base64 data: URI or http(s) URL attached for the vision path; the
|
|
// loop routes it through the vision/OCR tool or the main model (design/06 §0).
|
|
type chatRequest struct {
|
|
SessionID string `json:"sessionId"`
|
|
Text string `json:"text"`
|
|
Image string `json:"image,omitempty"`
|
|
Stream bool `json:"stream"`
|
|
}
|
|
|
|
// chatResponse is the synchronous chat reply payload.
|
|
type chatResponse struct {
|
|
Reply string `json:"reply"`
|
|
Steps int `json:"steps"`
|
|
StopReason string `json:"stopReason"`
|
|
}
|
|
|
|
// handleHealth reports liveness. It is unauthenticated because it is a probe.
|
|
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
|
|
}
|
|
|
|
// handleLogin exchanges the admin username/password for a signed JWT.
|
|
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var req loginRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
|
return
|
|
}
|
|
cfg := s.cfg.Auth
|
|
if req.Username != cfg.AdminUser || req.Password != cfg.AdminPass {
|
|
writeError(w, apperr.Wrap(apperr.ErrUnauthorized, "unauthorized", "invalid username or password"))
|
|
return
|
|
}
|
|
token, err := s.auth.Sign(req.Username, auth.RoleOwner, tokenTTL)
|
|
if err != nil {
|
|
s.log.Error("login sign", "err", err)
|
|
writeError(w, apperr.Wrap(apperr.ErrInternal, "login_failed", "could not sign token"))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, loginResponse{
|
|
Token: token,
|
|
ExpiresAt: time.Now().Add(tokenTTL).Unix(),
|
|
Role: string(auth.RoleOwner),
|
|
})
|
|
}
|
|
|
|
// handleChat runs one synchronous agent turn (or triggers streaming).
|
|
func (s *Server) handleChat(w http.ResponseWriter, r *http.Request) {
|
|
var req chatRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
|
return
|
|
}
|
|
if strings.TrimSpace(req.Text) == "" && strings.TrimSpace(req.Image) == "" {
|
|
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "text or image is required"))
|
|
return
|
|
}
|
|
if req.Stream {
|
|
s.publishChatStream(r.Context(), req.SessionID, req.Text, req.Image)
|
|
writeJSON(w, http.StatusOK, map[string]any{"stream": true})
|
|
return
|
|
}
|
|
if s.runner == nil {
|
|
writeError(w, apperr.Wrap(apperr.ErrInternal, "chat_unavailable", "chat service is not configured"))
|
|
return
|
|
}
|
|
if req.SessionID == "" {
|
|
req.SessionID = "web"
|
|
}
|
|
res, err := s.runner.Run(r.Context(), req.SessionID, userChatMessages(req.Text, req.Image))
|
|
if err != nil {
|
|
s.log.Error("chat run", "err", err, "session", req.SessionID)
|
|
writeError(w, apperr.Wrap(apperr.ErrInternal, "chat_failed", "chat failed"))
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, chatResponse{Reply: res.Text, Steps: res.Steps, StopReason: res.StopReason})
|
|
}
|
|
|
|
// handleListSessions returns the known sessions (or [] when no store is wired).
|
|
func (s *Server) handleListSessions(w http.ResponseWriter, r *http.Request) {
|
|
out := make([]SessionSummary, 0)
|
|
if s.sessions != nil {
|
|
list, err := s.sessions.List(r.Context())
|
|
if err != nil {
|
|
s.log.Error("list sessions", "err", err)
|
|
writeError(w, apperr.Wrap(apperr.ErrInternal, "sessions_failed", "failed to list sessions"))
|
|
return
|
|
}
|
|
for _, sess := range list {
|
|
out = append(out, summaryOfSession(sess))
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, out)
|
|
}
|
|
|
|
// handleListPersonas returns the personas (or [] when no store is wired).
|
|
func (s *Server) handleListPersonas(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, s.collectPersonas())
|
|
}
|
|
|
|
// collectPersonas returns a non-nil persona slice from the configured store.
|
|
func (s *Server) collectPersonas() []PersonaSummary {
|
|
out := make([]PersonaSummary, 0)
|
|
if s.personas == nil {
|
|
return out
|
|
}
|
|
for _, c := range s.personas.List() {
|
|
id := c.PersonaID
|
|
if id == "" {
|
|
id = c.ID
|
|
}
|
|
out = append(out, PersonaSummary{
|
|
ID: id,
|
|
Name: c.Name,
|
|
Character: c.Name,
|
|
IsDefault: c.Default,
|
|
Mode: firstMode(c.Modes),
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
// firstMode returns the first declared behavior mode, or "" when none are set.
|
|
func firstMode(modes []string) string {
|
|
if len(modes) == 0 {
|
|
return ""
|
|
}
|
|
return modes[0]
|
|
}
|
|
|
|
// userChatMessages builds the user turn for a chat / stream request. When image is
|
|
// present the turn becomes an image message (with optional text); otherwise a
|
|
// plain text message. An empty text with an image yields an image-only turn.
|
|
func userChatMessages(text, image string) []model.Message {
|
|
if strings.TrimSpace(image) != "" {
|
|
return []model.Message{model.ImageMessage(model.RoleUser, text, image)}
|
|
}
|
|
return []model.Message{model.TextMessage(model.RoleUser, text)}
|
|
}
|
|
|
|
// summaryOfSession maps a session.Session to its wire shape.
|
|
func summaryOfSession(sess session.Session) SessionSummary {
|
|
return SessionSummary{
|
|
Platform: sess.Platform,
|
|
ChannelID: sess.ChannelID,
|
|
SessionID: sess.SessionID,
|
|
ActorRole: string(sess.ActorRole),
|
|
Owner: sess.Owner,
|
|
IsGroup: sess.IsGroup,
|
|
MemWrite: sess.MemWritable,
|
|
}
|
|
}
|
|
|
|
// writeJSON encodes v as the {data: v} envelope with the given status.
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": v})
|
|
}
|
|
|
|
// writeError encodes err as the {error:{code,message}} envelope with the status
|
|
// resolved by apperr.HTTPStatus.
|
|
func writeError(w http.ResponseWriter, err error) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(apperr.HTTPStatus(err))
|
|
_ = json.NewEncoder(w).Encode(apperr.ToJSON(err))
|
|
}
|