Files
Cyrene_v2/internal/services/gateway/rest.go
T
Aska 6dbb4a2e18
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat: 唤醒式架构批次——capacity/L4/会话编排/管理面板写CRUD/前端集成(77-81)
【capacity 唤醒式核心(77)】internal/runtime/capacity:(Decider L1启发式+L2上下文+人格覆盖→三态静息/唤醒/全能→允许工具集+capacity_awaken事件)。loop 外围允许集过滤(不硬阻断=能力≠边界红线)。config 加 Capacity(Enabled/MinConfidence/ToolSets)。wire buildCapacity 接入 loop。

【L4 记忆驱动意图(80)】recall.go:从记忆召回用户习惯(搞一下xx=办事)→唤醒L1/L2漏掉/升置信;群聊陌生人不读owner习惯(隔离红线);RecordIntent闭环(判定写回记忆越用越准);默认保守静息。

【会话消息编排(78)】gateway/session_orchestrator.go:每会话(模式/pending有界5/tail上下文尾巴20);Submit非阻塞(idle立即/busy入队ack/满拒绝);完成回调按序续接(tail+新消息合并增量注入非全量重放);Interrupt中断;REST 202/409+WS session_busy/pending_ack事件;不重造任务引擎复用loop。

【前端集成(79)】ws.ts 加 capacity_awaken/session_busy/pending_ack 解析;store 加 awakenState/sessionBusy;TopBar/ChatShell 加唤醒态徽标+忙态提示(不阻塞输入框);状态组件 status.tsx;Miuix风格。

【管理面板写CRUD(81)】20个写端点(POST/PUT/DELETE /admin/*,owner+审计落库):personas(真持久化YAML)/users apikey(签发掩码+撤销)/iot控制(真下发)/automations(建/触发/删)/llm(test真调用+临时)/channels(connect/close/身份测试actor白名单)/plugins(卸载)/memories(search真检索)/sessions(export)。无存储如实501不伪造。拆4文件满足≤500红线。前端9模块接真写。

【wire收口】buildCapacity接入loop+OnCapacity事件;server.go newOrchestrator接hub。

实机验证:iot ac.living control 200 真实改变 on:true;observability/metrics 200、health ok;全仓 build/vet/test 47包绿+前端tsc/vite。
2026-09-06 21:54:40 +08:00

258 lines
8.6 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/loop"
"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"
}
// The Web main session is the owner's private conversation (JWT = owner), so
// it binds the full-access env: memory read+write, unchanged behavior.
msgs := userChatMessages(req.Text, req.Image)
if s.hub.orchestrator != nil {
sr, res := s.hub.orchestrator.SubmitSync(r.Context(), req.SessionID, msgs, loop.OwnerEnv())
if !sr.Accepted {
if sr.PendingFull {
writeError(w, apperr.Wrap(apperr.ErrConflict, "chat_busy", "会话正忙,待处理消息已满"))
} else {
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "text or image is required"))
}
return
}
// A busy session returns a non-blocking ack (design/15 §2.1) instead of
// blocking the request on a turn that may run for a while.
if sr.Pending {
writeJSON(w, http.StatusAccepted, map[string]any{"queued": true, "queueDepth": sr.QueueDepth})
return
}
if sr.Err != nil {
s.log.Error("chat run", "err", sr.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})
return
}
// Legacy synchronous path when no orchestrator is wired (a hub built without
// one keeps the exact pre-design/15 reply contract).
res, err := s.runner.Run(loop.WithSessionEnv(r.Context(), loop.OwnerEnv()), req.SessionID, msgs)
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))
}