群聊/陌生人查记忆只读不写、不泄露主人敏感;owner 默认行为完全不变。 - loop/sessionenv.go:SessionEnv 类型 + WithSessionEnv/sessionEnvFrom/OwnerEnv——每次 Run 携带会话 隔离上下文,经 context.Context 传递(不改 Run 签名、不存 Loop/Options 字段,避免 16 并发渠道 消息共享 Loop 的数据竞争;Chatter 接口与测试桩签名不变)。 - loop/memory.go 门控:injectMemory 读——MemWritable=true(owner)走原 Retriever.Inject 全量不变; false(群聊/陌生人)改 Retrieve 后只留 ScopeProject(人人可读)、剔除 ScopeUser(owner习惯私有)与 ScopePersona(角色日常=owner敏感),块首加「群聊隔离」标记,无项目记忆不注入;extractMemory 写 false 直接 return 跳过(不调用 extractor 不落库)。 - 渠道入站(Channelbridge)传真实会话 MemWritable/Env;Web/REST/WS/voice chat 绑 OwnerEnv(JWT=owner 行为不变);backthink/automations/orchestration 默认 owner 全量。 - 测试:memory_gating_test 6 用例(owner/群聊只读不写/陌生人受限/无项目记忆不注入/默认owner全量)全绿; loop/session/gateway 既有测试无回归。go build/vet/test 47 包全绿。 遗留:ScopeProject 过滤在 loop 内后处理实现(未改 memory 包),若后续允许可在 Retriever 加 scope 过滤选项消除与 Inject 模板的重复(2处)。
231 lines
7.5 KiB
Go
231 lines
7.5 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.
|
|
res, err := s.runner.Run(loop.WithSessionEnv(r.Context(), loop.OwnerEnv()), 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))
|
|
}
|