feat(session,runtime): 多角色并存—按会话选角(迁移0011 + 按回合解析 + agent池 + 提取器修正)
按 DevDocs/design/22 批次 1 后端(§2/§3/§4.1-4.5/§4.7/§5 验收 1-6)。
- 迁移 0011:chat_sessions.persona_id + chat_messages.persona_id(均 DEFAULT '',无回填 → 升级零风险);同步包内幂等 DDL;**真实库升级验证**(拷贝 data/cyrene.db 到临时目录跑 MigrateUp:既有 1 会话/109 消息 persona 仍为 '',原库未被触碰)
- history:SessionMeta/Message 加 PersonaID + SetSessionPersona;ListSessions/List/scan/Append 带上
- runtime:SessionEnv.PersonaID + loop.personaFor(ctx) 替换固定 l.personaID(memory/request/turn)+ **agent 池**(Options.Agents,按角色取 instructions,未命中回落)+ **提取器不再把 persona 烤死在构造期**(多角色下记忆不再永远记在 cyrene 名下)+ **thinking 旋钮改为按会话角色解析**(否则角色 Y 会用角色 X 的预算/展示)
- gateway:会话 DTO/POST/PATCH 支持 personaId;ws/rest/voice 的 OwnerEnv 硬编改为**按会话解析角色**(actor 元数据语义不变);admin memories 搜索去掉硬编 cyrene
- Docs/api-client v0.42;**两处有意的行为收紧**已写明:POST /sessions body 非法 JSON → 400(原先完全忽略 body;空/null/{} 仍 201);POST /admin/memories/search 省略 personaId 且无默认角色 → 400(原先默认查 cyrene)
- 测试:design/22 §5 验收 1-6(记忆隔离/提示词首条 system/情绪按角色/提取 persona 归属/迁移兼容)+ 进程内 e2e(断言 adapter 收到的 model.Request.Messages[0] 即该角色的 systemPrompt)
- **已知未做(留批次 2 / 待确认)**:① IM 与渠道级未做 → **§7-3「owner 私聊镜像随主会话角色」尚未生效**;② 请求级覆盖未实现(本批只做会话级);③ **§7-5 的「上下文发送角色标记」只完成存储+DTO 半边**——消息 persona 已落库且 DTO 已带,但模型上下文不从 chat_messages 重建,「第 N 条是谁说的」尚未进上下文(需确认是否属批次 2);④「切角色重建摘要」当前是空操作(压缩未接线);⑤ thinking 旋钮仅在流式路径生效(非流式 agent.RunStep 不带,A 批次既有性质)
- 验收:go build/vet/test 全绿 + linux/amd64 与 darwin/arm64 交叉编译(既有 flake 本轮未触发;同批 session_orchestrator.go 一度 501 行 → 抽出 session_tail.go)
This commit is contained in:
1 parent
66a96d2f93
commit
0624d9ee36
46 files changed
+1908
-259
No files matched your search
@@ -53,7 +53,16 @@ func (s *Server) adminMemorySearch(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
personaID := strings.TrimSpace(req.PersonaID)
|
||||
if personaID == "" {
|
||||
personaID = "cyrene"
|
||||
// Fall back to the library's default role rather than a hardcoded id, so the
|
||||
// admin search follows a renamed/replaced default (design/22 §4.5). No default
|
||||
// registered means there is nothing to search: answer honestly instead of
|
||||
// querying an id that cannot match.
|
||||
personaID = s.defaultPersonaID()
|
||||
if personaID == "" {
|
||||
s.auditClaims(r, "memory.search", "error")
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "personaId is required (no default persona configured)"))
|
||||
return
|
||||
}
|
||||
}
|
||||
topK := req.TopK
|
||||
if topK <= 0 {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -32,6 +34,12 @@ type historySessionSummary struct {
|
||||
// cursor is session-scoped and single-owner: reading on any one end clears the
|
||||
// badge for every end of the account.
|
||||
UnreadCount int `json:"unreadCount"`
|
||||
// PersonaID is the role this session belongs to (design/22 §2/§4.5). It is the
|
||||
// single source of truth for which role answers in the conversation, and the
|
||||
// client uses it to render the role's name/avatar for the active session.
|
||||
// Omitted when empty, and empty means "inherit the global default role", so an
|
||||
// old client that ignores the field keeps showing the default role's visuals.
|
||||
PersonaID string `json:"personaId,omitempty"`
|
||||
}
|
||||
|
||||
// historyLastMessage is the wire shape of the last-message preview in a session summary.
|
||||
@@ -64,7 +72,13 @@ type historyMessage struct {
|
||||
// source that produced the message (e.g. "kook:3bef..."). It is blank for
|
||||
// Web-originated messages.
|
||||
AdapterID string `json:"adapterId,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
// PersonaID is the role that SPOKE this message (design/22 §7-5). A session may
|
||||
// switch roles while keeping its context, so the authoring role is stored and
|
||||
// returned per message and the client renders the bubble with that role's
|
||||
// name/avatar. Omitted when empty, and empty means "the global default role" —
|
||||
// the pre-multi-character rows read exactly as before.
|
||||
PersonaID string `json:"personaId,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
}
|
||||
|
||||
// handleHistorySessions returns the main session first, then every sub session (oldest
|
||||
@@ -84,6 +98,7 @@ func (s *Server) handleHistorySessions(w http.ResponseWriter, r *http.Request) {
|
||||
Title: m.Title,
|
||||
CreatedAt: m.CreatedAt,
|
||||
Pinned: m.Pinned,
|
||||
PersonaID: m.PersonaID,
|
||||
LastMessage: toHistoryLastMessage(m.LastMessage),
|
||||
UnreadCount: m.UnreadCount,
|
||||
})
|
||||
@@ -100,8 +115,21 @@ func toHistoryLastMessage(m *history.MessageSummary) *historyLastMessage {
|
||||
return &historyLastMessage{Role: m.Role, Content: m.Content, CreatedAt: m.CreatedAt}
|
||||
}
|
||||
|
||||
// createSubSessionRequest is the POST /api/v1/sessions body. The body itself is
|
||||
// optional (a client that just wants a plain session sends none), and personaId is
|
||||
// the optional role the new session is bound to (design/22 §4.5). It is the
|
||||
// "seed the new session's role" half of the design's precedence: an explicit role
|
||||
// here becomes the session-level binding (the single source of truth), while
|
||||
// omitting it leaves persona_id = '' so the session inherits the global default.
|
||||
type createSubSessionRequest struct {
|
||||
PersonaID string `json:"personaId"`
|
||||
}
|
||||
|
||||
// handleCreateSubSession creates a new sub session and returns its sessionId. It is a
|
||||
// user-side write, so it is owner/admin-gated like /api/v1/chat.
|
||||
// user-side write, so it is owner/admin-gated like /api/v1/chat. An optional
|
||||
// {"personaId":"..."} body binds the new session to that role; an unknown id is
|
||||
// rejected with 400 rather than creating a session that would silently answer as
|
||||
// the default role.
|
||||
func (s *Server) handleCreateSubSession(w http.ResponseWriter, r *http.Request) {
|
||||
if s.history == nil {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
@@ -111,13 +139,30 @@ func (s *Server) handleCreateSubSession(w http.ResponseWriter, r *http.Request)
|
||||
if claims, ok := auth.ClaimsFromContext(r.Context()); ok {
|
||||
ownerID = claims.Sub
|
||||
}
|
||||
id, err := s.history.NewSubSession(r.Context(), ownerID)
|
||||
var req createSubSessionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
||||
return
|
||||
}
|
||||
personaID := strings.TrimSpace(req.PersonaID)
|
||||
if !s.requireKnownPersona(w, personaID) {
|
||||
return
|
||||
}
|
||||
id, err := s.newSubSession(r.Context(), ownerID, personaID)
|
||||
if err != nil {
|
||||
if errors.Is(err, errPersonaBindingUnsupported) {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话角色绑定需要支持 personaId 的 HistoryStore", HTTPCode: http.StatusNotImplemented})
|
||||
return
|
||||
}
|
||||
s.log.Error("history create sub session", "err", err)
|
||||
writeError(w, apperr.Wrap(apperr.ErrInternal, "session_failed", "failed to create session"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"sessionId": id})
|
||||
resp := map[string]any{"sessionId": id}
|
||||
if personaID != "" {
|
||||
resp["personaId"] = personaID
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
// handleListMessages returns a page of messages for a session with cursor pagination.
|
||||
@@ -345,18 +390,19 @@ func (s *Server) handleDeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
// toHistoryMessage maps a stored history.Message to its wire shape.
|
||||
func toHistoryMessage(m history.Message) historyMessage {
|
||||
return historyMessage{
|
||||
ID: m.ID,
|
||||
SessionID: m.SessionID,
|
||||
Role: m.Role,
|
||||
Content: m.Content,
|
||||
Mode: m.Mode,
|
||||
Mood: m.Mood,
|
||||
Image: m.Image,
|
||||
Thinking: m.Thinking,
|
||||
ID: m.ID,
|
||||
SessionID: m.SessionID,
|
||||
Role: m.Role,
|
||||
Content: m.Content,
|
||||
Mode: m.Mode,
|
||||
Mood: m.Mood,
|
||||
Image: m.Image,
|
||||
Thinking: m.Thinking,
|
||||
Platform: m.Platform,
|
||||
DeviceID: m.DeviceID,
|
||||
SenderName: m.SenderName,
|
||||
AdapterID: m.AdapterID,
|
||||
PersonaID: m.PersonaID,
|
||||
CreatedAt: m.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -399,8 +399,8 @@ func TestPersistUserMessageNamesSession(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("new sub: %v", err)
|
||||
}
|
||||
o.persistUserMessages(ctx, sub, []model.Message{model.TextMessage(model.RoleUser, "帮我规划一次旅行")}, "web:test", "chat")
|
||||
o.persistUserMessages(ctx, sub, []model.Message{model.TextMessage(model.RoleUser, "第二句话")}, "web:test", "chat")
|
||||
o.persistUserMessages(ctx, sub, []model.Message{model.TextMessage(model.RoleUser, "帮我规划一次旅行")}, "web:test", "chat", "cyrene")
|
||||
o.persistUserMessages(ctx, sub, []model.Message{model.TextMessage(model.RoleUser, "第二句话")}, "web:test", "chat", "cyrene")
|
||||
|
||||
metas, err := st.ListSessions(ctx)
|
||||
if err != nil {
|
||||
@@ -417,7 +417,7 @@ func TestPersistUserMessageNamesSession(t *testing.T) {
|
||||
}
|
||||
|
||||
// The main session is named from its first Web user message too.
|
||||
o.persistUserMessages(ctx, history.MainSessionID, []model.Message{model.TextMessage(model.RoleUser, " 今天\n天气如何 ")}, "web:test", "chat")
|
||||
o.persistUserMessages(ctx, history.MainSessionID, []model.Message{model.TextMessage(model.RoleUser, " 今天\n天气如何 ")}, "web:test", "chat", "cyrene")
|
||||
metas, err = st.ListSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("list sessions again: %v", err)
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/auth"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/db"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/persona/loader"
|
||||
personareg "git.yeij.top/AskaEth/Cyrene_v2/internal/persona/registry"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/agent"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/loop"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
)
|
||||
|
||||
// This file covers the gateway half of design/22 (多角色并存 + 按会话选角): the REST
|
||||
// contract for binding a session to a role, and the resolver that turns a
|
||||
// sessionID into the loop environment the turn runs under. The chain asserted end to
|
||||
// end is: sessionID → chat_sessions.persona_id → turnEnvResolver → loop.SessionEnv →
|
||||
// per-role agent (system prompt), so a regression at any hop shows up as the wrong
|
||||
// role answering.
|
||||
|
||||
// personaAdapter records every request the loop built, so a test can assert which
|
||||
// role's system prompt actually reached the model.
|
||||
type personaAdapter struct {
|
||||
reqs []model.Request
|
||||
}
|
||||
|
||||
func (p *personaAdapter) Name() string { return "persona-test" }
|
||||
|
||||
func (p *personaAdapter) Chat(_ context.Context, req model.Request, _ model.Options) (model.Response, error) {
|
||||
p.reqs = append(p.reqs, req)
|
||||
return model.Response{Content: "好呀"}, nil
|
||||
}
|
||||
|
||||
func (p *personaAdapter) ChatStream(ctx context.Context, req model.Request, _ func(model.StreamEvent)) (model.Response, error) {
|
||||
return p.Chat(ctx, req, model.Options{})
|
||||
}
|
||||
|
||||
// personaTestRegistry registers two roles (one default) so the gateway can validate
|
||||
// personaId values and resolve the default role.
|
||||
func personaTestRegistry(t *testing.T) *personareg.Registry {
|
||||
t.Helper()
|
||||
reg := personareg.New()
|
||||
for _, p := range []*loader.Persona{
|
||||
{ID: "xilian", Name: "昔涟"},
|
||||
{ID: "yuki", Name: "由纪"},
|
||||
} {
|
||||
if err := reg.RegisterPersona(p); err != nil {
|
||||
t.Fatalf("RegisterPersona(%s): %v", p.ID, err)
|
||||
}
|
||||
}
|
||||
if err := reg.RegisterCharacter(&personareg.Character{ID: "xilian", Name: "昔涟", Default: true, PersonaID: "xilian"}); err != nil {
|
||||
t.Fatalf("RegisterCharacter(xilian): %v", err)
|
||||
}
|
||||
if err := reg.RegisterCharacter(&personareg.Character{ID: "yuki", Name: "由纪", PersonaID: "yuki"}); err != nil {
|
||||
t.Fatalf("RegisterCharacter(yuki): %v", err)
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
// personaTestStore opens an in-memory chat-history store.
|
||||
func personaTestStore(t *testing.T) *history.Store {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
conn, err := db.Open(ctx, ":memory:", testLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("db.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
st, err := history.NewStore(ctx, conn, testLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("history.NewStore: %v", err)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// gatewayAgentFor builds the per-role agent the composition root would build: the
|
||||
// same adapter, a role-specific instruction string.
|
||||
func gatewayAgentFor(t *testing.T, instructions string, ad model.Adapter) *agent.Agent {
|
||||
t.Helper()
|
||||
ag, err := agent.New(instructions, nil, nil, agent.WithModel(ad, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("agent.New(%q): %v", instructions, err)
|
||||
}
|
||||
return ag
|
||||
}
|
||||
|
||||
// TestChatTurnAnswersAsTheBoundRole is design/22 acceptance 3 seen from the process
|
||||
// boundary: a sub session created and bound to role Y answers as Y (the first system
|
||||
// message is Y's prompt and the persisted messages carry Y), and once the session is
|
||||
// rebound to "inherit the default" the next turn answers as the default role again.
|
||||
func TestChatTurnAnswersAsTheBoundRole(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
st := personaTestStore(t)
|
||||
reg := personaTestRegistry(t)
|
||||
sub, err := st.NewSubSessionFor(ctx, "owner", "yuki")
|
||||
if err != nil {
|
||||
t.Fatalf("NewSubSessionFor: %v", err)
|
||||
}
|
||||
|
||||
ad := &personaAdapter{}
|
||||
xilian := gatewayAgentFor(t, "你是昔涟。", ad)
|
||||
yuki := gatewayAgentFor(t, "你是由纪。", ad)
|
||||
l := loop.New(loop.Options{
|
||||
Agent: xilian,
|
||||
Agents: map[string]*agent.Agent{"xilian": xilian, "yuki": yuki},
|
||||
PersonaID: "xilian",
|
||||
})
|
||||
_, ts, jwt := buildEnv(t, cfgDefault(), Deps{History: st, Personas: reg, Loop: l})
|
||||
tok := signAny(t, jwt, "acct", auth.RoleOwner)
|
||||
|
||||
resp, body := doReq(t, http.MethodPost, ts.URL+"/api/v1/chat", map[string]any{"sessionId": sub, "text": "你好呀"}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("chat status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
if len(ad.reqs) == 0 {
|
||||
t.Fatal("the model adapter saw no request")
|
||||
}
|
||||
if got := firstSystemText(ad.reqs[len(ad.reqs)-1]); got != "你是由纪。" {
|
||||
t.Fatalf("bound session prompt = %q, want role Y's prompt", got)
|
||||
}
|
||||
|
||||
// The orchestrator files both the user turn and the reply under the turn's role,
|
||||
// which is what makes the stored transcript readable role-by-role (design/22 §7-5).
|
||||
msgs, err := st.List(ctx, sub, 0, 10, "")
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(msgs) != 2 {
|
||||
t.Fatalf("persisted %d messages, want 2 (user + assistant)", len(msgs))
|
||||
}
|
||||
for _, m := range msgs {
|
||||
if m.PersonaID != "yuki" {
|
||||
t.Fatalf("%s message persona_id = %q, want yuki", m.Role, m.PersonaID)
|
||||
}
|
||||
}
|
||||
|
||||
// Unbind the role: the session inherits the global default, so the next turn is
|
||||
// the default role's again.
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+sub, map[string]any{"personaId": ""}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("unbind status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
resp, body = doReq(t, http.MethodPost, ts.URL+"/api/v1/chat", map[string]any{"sessionId": sub, "text": "再说一句"}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("second chat status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
if got := firstSystemText(ad.reqs[len(ad.reqs)-1]); got != "你是昔涟。" {
|
||||
t.Fatalf("unbound session prompt = %q, want the default role's prompt", got)
|
||||
}
|
||||
}
|
||||
|
||||
// firstSystemText returns the text of the first system message of req.
|
||||
func firstSystemText(req model.Request) string {
|
||||
for _, m := range req.Messages {
|
||||
if m.Role != model.RoleSystem {
|
||||
continue
|
||||
}
|
||||
text := ""
|
||||
for _, part := range m.Content {
|
||||
text += part.Text
|
||||
}
|
||||
return text
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// TestSessionPersonaHTTPContract covers the REST contract of design/22 §4.5: create
|
||||
// with a personaId binds it, the session list reports it, PATCH rebinds and clears
|
||||
// it, an unknown personaId is rejected (400) instead of binding a role that cannot
|
||||
// answer, and a PATCH with none of title/pinned/personaId is still a 400.
|
||||
func TestSessionPersonaHTTPContract(t *testing.T) {
|
||||
t.Parallel()
|
||||
st := personaTestStore(t)
|
||||
reg := personaTestRegistry(t)
|
||||
_, ts, jwt := buildEnv(t, cfgDefault(), Deps{History: st, Personas: reg})
|
||||
tok := signAny(t, jwt, "acct", auth.RoleOwner)
|
||||
|
||||
resp, body := doReq(t, http.MethodPost, ts.URL+"/api/v1/sessions", map[string]any{"personaId": "yuki"}, tok)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, want 201 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var created struct {
|
||||
SessionID string `json:"sessionId"`
|
||||
PersonaID string `json:"personaId"`
|
||||
}
|
||||
if err := json.Unmarshal(decodeBody(t, body)["data"], &created); err != nil {
|
||||
t.Fatalf("decode create: %v (body=%s)", err, body)
|
||||
}
|
||||
if created.PersonaID != "yuki" {
|
||||
t.Fatalf("create echoed personaId = %q, want yuki", created.PersonaID)
|
||||
}
|
||||
|
||||
// The session list surfaces the binding (the client renders the active role from it).
|
||||
var sessions []historySessionSummary
|
||||
_, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions", nil, tok)
|
||||
decodeDataSlice(t, body, &sessions)
|
||||
found := ""
|
||||
for _, s := range sessions {
|
||||
if s.ID == created.SessionID {
|
||||
found = s.PersonaID
|
||||
}
|
||||
}
|
||||
if found != "yuki" {
|
||||
t.Fatalf("listed persona_id = %q, want yuki (sessions=%+v)", found, sessions)
|
||||
}
|
||||
|
||||
// An unknown role is refused rather than silently ignored.
|
||||
resp, body = doReq(t, http.MethodPost, ts.URL+"/api/v1/sessions", map[string]any{"personaId": "nobody"}, tok)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("create with unknown personaId status = %d, want 400 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": "nobody"}, tok)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("patch with unknown personaId status = %d, want 400 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// A body with none of the supported fields stays a 400.
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{}, tok)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("empty patch status = %d, want 400 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// Rebind to the other role, then clear the binding; both echo only the changed field.
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": "xilian"}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("rebind status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
if got := personaBindingOf(t, st, created.SessionID); got != "xilian" {
|
||||
t.Fatalf("after rebind persona_id = %q, want xilian", got)
|
||||
}
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": ""}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("unbind status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
if got := personaBindingOf(t, st, created.SessionID); got != "" {
|
||||
t.Fatalf("after unbind persona_id = %q, want '' (inherit the default)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// personaBindingOf reads a session's bound role straight from the store, so the test
|
||||
// asserts the persisted state rather than only the response echo.
|
||||
func personaBindingOf(t *testing.T, st *history.Store, sessionID string) string {
|
||||
t.Helper()
|
||||
personaID, err := st.SessionPersona(context.Background(), sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("SessionPersona(%s): %v", sessionID, err)
|
||||
}
|
||||
return personaID
|
||||
}
|
||||
|
||||
// TestTurnEnvResolver covers the resolver itself (design/22 §4.5): the session's
|
||||
// binding wins, an unknown/unbound session yields "" (so the loop falls back to the
|
||||
// global default), and the identity/memory fields stay the owner-full ones — the
|
||||
// role never changes what a turn is allowed to do.
|
||||
func TestTurnEnvResolver(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
st := personaTestStore(t)
|
||||
bound, err := st.NewSubSessionFor(ctx, "owner", "yuki")
|
||||
if err != nil {
|
||||
t.Fatalf("NewSubSessionFor: %v", err)
|
||||
}
|
||||
|
||||
r := turnEnvResolver{history: st, personas: personaTestRegistry(t), log: testLogger()}
|
||||
|
||||
env := r.owner(ctx, bound)
|
||||
if env.PersonaID != "yuki" {
|
||||
t.Fatalf("bound session env persona = %q, want yuki", env.PersonaID)
|
||||
}
|
||||
if env.ActorEnv != loop.OwnerEnv().ActorEnv || !env.MemWritable {
|
||||
t.Fatalf("resolver changed the identity lane: %+v", env)
|
||||
}
|
||||
|
||||
unbound, err := st.NewSubSession(ctx, "owner")
|
||||
if err != nil {
|
||||
t.Fatalf("NewSubSession: %v", err)
|
||||
}
|
||||
if got := r.owner(ctx, unbound).PersonaID; got != "" {
|
||||
t.Fatalf("unbound session env persona = %q, want '' (inherit the default)", got)
|
||||
}
|
||||
if got := r.owner(ctx, "sess-unknown").PersonaID; got != "" {
|
||||
t.Fatalf("unknown session env persona = %q, want '' (inherit the default)", got)
|
||||
}
|
||||
|
||||
// A gateway without a history store cannot resolve a binding and must not fail.
|
||||
bare := turnEnvResolver{log: testLogger()}
|
||||
if got := bare.owner(ctx, "web").PersonaID; got != "" {
|
||||
t.Fatalf("no-store env persona = %q, want ''", got)
|
||||
}
|
||||
if !bare.owner(ctx, "web").MemWritable {
|
||||
t.Fatal("no-store env lost the owner memory lane")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultPersonaIDFromRegistry locks the admin fallback design/22 §4.5 asks for:
|
||||
// the default role is read from the library's default character instead of a
|
||||
// hardcoded "cyrene", and an unwired registry reports none.
|
||||
func TestDefaultPersonaIDFromRegistry(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv, _, _ := buildEnv(t, cfgDefault(), Deps{Personas: personaTestRegistry(t)})
|
||||
if got := srv.defaultPersonaID(); got != "xilian" {
|
||||
t.Fatalf("defaultPersonaID = %q, want xilian (the default character's persona)", got)
|
||||
}
|
||||
bare, _, _ := buildEnv(t, cfgDefault(), Deps{})
|
||||
if got := bare.defaultPersonaID(); got != "" {
|
||||
t.Fatalf("defaultPersonaID without a registry = %q, want ''", got)
|
||||
}
|
||||
}
|
||||
@@ -19,12 +19,15 @@ import (
|
||||
// broadcast their outcome over the WS hub (message_edited / message_deleted, see
|
||||
// ws_hub.go) so the account's other browsers stay in sync without a manual re-read.
|
||||
|
||||
// patchSessionRequest is the PATCH /api/v1/sessions/{id} body. Both fields are pointers
|
||||
// so an absent field is distinguishable from an explicit zero value: title renames the
|
||||
// session (A4), pinned sets/unets the pin (D5), and at least one must be present.
|
||||
// patchSessionRequest is the PATCH /api/v1/sessions/{id} body. All fields are
|
||||
// pointers so an absent field is distinguishable from an explicit zero value:
|
||||
// title renames the session (A4), pinned sets/unets the pin (D5), personaId
|
||||
// rebinds the session's role (design/22 §4.5, an explicit "" clears the binding
|
||||
// back to "inherit the global default"), and at least one must be present.
|
||||
type patchSessionRequest struct {
|
||||
Title *string `json:"title"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
Title *string `json:"title"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
PersonaID *string `json:"personaId"`
|
||||
}
|
||||
|
||||
// maxSessionTitleRunes bounds a client-supplied session title so a display row never
|
||||
@@ -32,12 +35,16 @@ type patchSessionRequest struct {
|
||||
// the title (project red line).
|
||||
const maxSessionTitleRunes = 80
|
||||
|
||||
// handlePatchSession updates a persistent session's display metadata: its title (A4)
|
||||
// and/or its pinned flag (D5). Both are display/order-only, so unlike DELETE they are
|
||||
// allowed on the fixed main session. A request carrying neither field answers 400, as
|
||||
// do an empty/whitespace or over-long title; an unknown session id answers 404. It is
|
||||
// owner/admin-gated like the other history writes. The response echoes only the fields
|
||||
// that were changed, so a title-only PATCH keeps its pre-D5 {id,title} shape.
|
||||
// handlePatchSession updates a persistent session's display metadata — its title
|
||||
// (A4), its pinned flag (D5) — and/or its role binding (design/22 §4.5). All three
|
||||
// are metadata: unlike DELETE they are allowed on the fixed main session. A request
|
||||
// carrying none of the fields answers 400, as do an empty/whitespace or over-long
|
||||
// title and an unknown personaId; an unknown session id answers 404. Rebinding a
|
||||
// role does not touch the stored conversation — the messages keep the role that
|
||||
// spoke them (design/22 §7-5) — it only changes which role answers from the next
|
||||
// turn on. It is owner/admin-gated like the other history writes. The response
|
||||
// echoes only the fields that were changed, so a title-only PATCH keeps its pre-D5
|
||||
// {id,title} shape.
|
||||
func (s *Server) handlePatchSession(w http.ResponseWriter, r *http.Request) {
|
||||
if s.history == nil {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
@@ -53,8 +60,8 @@ func (s *Server) handlePatchSession(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
||||
return
|
||||
}
|
||||
if req.Title == nil && req.Pinned == nil {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title or pinned is required"))
|
||||
if req.Title == nil && req.Pinned == nil && req.PersonaID == nil {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title, pinned or personaId is required"))
|
||||
return
|
||||
}
|
||||
resp := map[string]any{"id": id}
|
||||
@@ -81,16 +88,43 @@ func (s *Server) handlePatchSession(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
resp["pinned"] = *req.Pinned
|
||||
}
|
||||
if req.PersonaID != nil {
|
||||
personaID := strings.TrimSpace(*req.PersonaID)
|
||||
if !s.requireKnownPersona(w, personaID) {
|
||||
return
|
||||
}
|
||||
if err := s.setSessionPersona(r.Context(), id, personaID); err != nil {
|
||||
s.writeSessionPatchError(w, err, id, "set session persona")
|
||||
return
|
||||
}
|
||||
resp["personaId"] = personaID
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// writeSessionPatchError maps a RenameSession/SetPinned failure to its response:
|
||||
// ErrSessionNotFound → 404, anything else → 500 (logged under op).
|
||||
// setSessionPersona rebinds a session's role through the store's optional
|
||||
// role-writer. A store without it answers 501 rather than reporting a binding that
|
||||
// was never written.
|
||||
func (s *Server) setSessionPersona(ctx context.Context, sessionID, personaID string) error {
|
||||
writer, ok := s.history.(sessionPersonaWriter)
|
||||
if !ok {
|
||||
return errPersonaBindingUnsupported
|
||||
}
|
||||
return writer.SetSessionPersona(ctx, sessionID, personaID)
|
||||
}
|
||||
|
||||
// writeSessionPatchError maps a RenameSession/SetPinned/SetSessionPersona failure to
|
||||
// its response: ErrSessionNotFound → 404, a store that cannot bind roles → 501,
|
||||
// anything else → 500 (logged under op).
|
||||
func (s *Server) writeSessionPatchError(w http.ResponseWriter, err error, id, op string) {
|
||||
if errors.Is(err, history.ErrSessionNotFound) {
|
||||
writeError(w, apperr.Wrap(apperr.ErrNotFound, "not_found", "session %q not found", id))
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errPersonaBindingUnsupported) {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话角色绑定需要支持 personaId 的 HistoryStore", HTTPCode: http.StatusNotImplemented})
|
||||
return
|
||||
}
|
||||
s.log.Error(op, "err", err, "session", id)
|
||||
writeError(w, apperr.Wrap(apperr.ErrInternal, "session_failed", "failed to update session"))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
apperr "git.yeij.top/AskaEth/Cyrene_v2/internal/errors"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/loop"
|
||||
)
|
||||
|
||||
// errPersonaBindingUnsupported is returned by newSubSession when a caller asks for
|
||||
// a role-bound session but the injected history store cannot bind roles. The
|
||||
// handler maps it to 501 rather than pretending the binding landed.
|
||||
var errPersonaBindingUnsupported = errors.New("gateway: history store does not support session persona binding")
|
||||
|
||||
// This file owns the gateway's turn-environment resolution (DevDocs/design/22
|
||||
// §2/§4.5): which role answers, expressed as the loop.SessionEnv the turn runs
|
||||
// under.
|
||||
//
|
||||
// Precedence (design/22 §2, top down):
|
||||
// 1. request-level override — NOT implemented in this batch (batch 1 exposes the
|
||||
// session-level binding; a per-request override is additive and unpersisted);
|
||||
// 2. session-level binding — chat_sessions.persona_id, resolved here;
|
||||
// 3. channel-level mapping — batch 2 (channels.json / channel_sessions);
|
||||
// 4. global default — expressed as PersonaID == "", which the loop resolves to its
|
||||
// configured default role (Options.PersonaID). That is what makes every
|
||||
// pre-existing session behave exactly as before.
|
||||
//
|
||||
// The env's OTHER fields are untouched: ActorEnv and MemWritable still come from
|
||||
// loop.OwnerEnv() for these owner-facing Web/voice paths. That is the identity red
|
||||
// line — who may do what is decided by the channel actor metadata (here: a JWT
|
||||
// owner), never by the role being played. Persona selection only changes the
|
||||
// prompt, the memory namespace, the emotion machine and the thinking budget.
|
||||
|
||||
// sessionPersonaReader is the optional narrower view of HistoryStore used to read a
|
||||
// session's bound role. *history.Store implements it; a store that does not (a test
|
||||
// fake, or a store predating design/22) simply yields "" — the global default — so
|
||||
// the gateway keeps working.
|
||||
type sessionPersonaReader interface {
|
||||
SessionPersona(ctx context.Context, sessionID string) (string, error)
|
||||
}
|
||||
|
||||
// sessionPersonaWriter is the optional narrower view of HistoryStore used to rebind
|
||||
// a session's role (PATCH /sessions/{id}, design/22 §4.5). *history.Store
|
||||
// implements it; a store without it answers 501 on a persona write rather than
|
||||
// pretending the binding landed.
|
||||
type sessionPersonaWriter interface {
|
||||
SetSessionPersona(ctx context.Context, sessionID, personaID string) error
|
||||
}
|
||||
|
||||
// subSessionCreator is the optional narrower view of HistoryStore used to create a
|
||||
// session already bound to a role (POST /sessions {personaId}, design/22 §4.5).
|
||||
// *history.Store implements it; a store without it can only create an unbound
|
||||
// session, so a request that explicitly asks for a role is refused with 501.
|
||||
type subSessionCreator interface {
|
||||
NewSubSessionFor(ctx context.Context, ownerID, personaID string) (string, error)
|
||||
}
|
||||
|
||||
// turnEnvResolver builds the loop session environment for one turn. It holds the
|
||||
// two read-only dependencies the resolution needs, so both the HTTP/WS handlers
|
||||
// and the hub resolve roles through the same code path (design/22 §4.5: one
|
||||
// resolver, not a hardcoded loop.OwnerEnv() per entry point).
|
||||
type turnEnvResolver struct {
|
||||
history HistoryStore
|
||||
personas PersonaStore
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// owner returns the per-turn environment for one owner-facing turn of sessionID:
|
||||
// the full-access owner env (identity unchanged) plus the session's bound role.
|
||||
// A blank role means "inherit the global default"; the loop performs that final
|
||||
// fallback, so the gateway never has to know the default role's id.
|
||||
func (t turnEnvResolver) owner(ctx context.Context, sessionID string) loop.SessionEnv {
|
||||
env := loop.OwnerEnv()
|
||||
env.PersonaID = t.sessionPersona(ctx, sessionID)
|
||||
return env
|
||||
}
|
||||
|
||||
// sessionPersona returns the role bound to sessionID, or "" when the session
|
||||
// inherits the global default. An unknown session, a store without the reader, or
|
||||
// a read error all degrade to "" (the default) rather than failing the turn: a
|
||||
// chat must never be blocked by a metadata lookup, and the fallback is the
|
||||
// pre-multi-character behavior.
|
||||
func (t turnEnvResolver) sessionPersona(ctx context.Context, sessionID string) string {
|
||||
if t.history == nil || sessionID == "" {
|
||||
return ""
|
||||
}
|
||||
reader, ok := t.history.(sessionPersonaReader)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
personaID, err := reader.SessionPersona(ctx, sessionID)
|
||||
if err != nil {
|
||||
if t.log != nil && !errors.Is(err, history.ErrSessionNotFound) {
|
||||
t.log.Debug("session persona read", "err", err, "session", sessionID)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return personaID
|
||||
}
|
||||
|
||||
// defaultPersonaID returns the persona id of the library's default character, or
|
||||
// "" when no persona store is wired or no character is marked default. It is the
|
||||
// gateway-side view of owner.yaml:defaultPersona used where a role id is needed
|
||||
// without a session (the admin memory search fallback, design/22 §4.5).
|
||||
func (s *Server) defaultPersonaID() string {
|
||||
if s.personas == nil {
|
||||
return ""
|
||||
}
|
||||
for _, c := range s.personas.List() {
|
||||
if c.Default && c.PersonaID != "" {
|
||||
return c.PersonaID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// requireKnownPersona rejects a personaId the registry does not know, answering
|
||||
// 400 and returning false. An empty id is always allowed (it means "inherit the
|
||||
// global default"), and a gateway without a persona store cannot validate, so the
|
||||
// binding is accepted there and simply resolves as an unknown role later.
|
||||
func (s *Server) requireKnownPersona(w http.ResponseWriter, personaID string) bool {
|
||||
if personaID == "" || s.personas == nil {
|
||||
return true
|
||||
}
|
||||
if _, ok := s.personas.Persona(personaID); !ok {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "unknown personaId %q", personaID))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// newSubSession creates a sub session bound to personaID, using the role-aware
|
||||
// creator when the store provides one. A store without it can only create an
|
||||
// unbound session, so an explicit role request is refused (501) instead of
|
||||
// silently dropping the binding.
|
||||
func (s *Server) newSubSession(ctx context.Context, ownerID, personaID string) (string, error) {
|
||||
creator, ok := s.history.(subSessionCreator)
|
||||
if !ok {
|
||||
if personaID != "" {
|
||||
return "", errPersonaBindingUnsupported
|
||||
}
|
||||
return s.history.NewSubSession(ctx, ownerID)
|
||||
}
|
||||
return creator.NewSubSessionFor(ctx, ownerID, personaID)
|
||||
}
|
||||
@@ -161,10 +161,12 @@ func (s *Server) handleChat(w http.ResponseWriter, r *http.Request) {
|
||||
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.
|
||||
// it binds the full-access env: memory read+write, unchanged behavior. The role
|
||||
// comes from the session's binding (design/22 §4.5).
|
||||
msgs := userChatMessages(req.Text, req.Image)
|
||||
env := s.envResolver.owner(r.Context(), req.SessionID)
|
||||
if s.hub.orchestrator != nil {
|
||||
sr, res := s.hub.orchestrator.SubmitSync(withMode(withDeviceID(r.Context(), req.DeviceID), req.Mode), req.SessionID, msgs, loop.OwnerEnv())
|
||||
sr, res := s.hub.orchestrator.SubmitSync(withMode(withDeviceID(r.Context(), req.DeviceID), req.Mode), req.SessionID, msgs, env)
|
||||
if !sr.Accepted {
|
||||
if sr.PendingFull {
|
||||
writeError(w, apperr.Wrap(apperr.ErrConflict, "chat_busy", "会话正忙,待处理消息已满"))
|
||||
@@ -189,7 +191,7 @@ func (s *Server) handleChat(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// 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)
|
||||
res, err := s.runner.Run(loop.WithSessionEnv(r.Context(), env), 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"))
|
||||
|
||||
@@ -84,8 +84,11 @@ type Server struct {
|
||||
// (best-effort). See Deps.OwnerRegistrar.
|
||||
ownerRegistrar OwnerRegistrar
|
||||
webhooks map[string]http.Handler
|
||||
log *slog.Logger
|
||||
hub *hub
|
||||
// envResolver resolves the per-turn loop environment (its role) for a session.
|
||||
// See persona_env.go / design/22 §4.5.
|
||||
envResolver turnEnvResolver
|
||||
log *slog.Logger
|
||||
hub *hub
|
||||
}
|
||||
|
||||
// New validates cfg and deps and returns a ready Server. Auth is required; the
|
||||
@@ -128,6 +131,10 @@ func New(cfg *config.Config, deps Deps) (*Server, error) {
|
||||
dataDir: deps.DataDir,
|
||||
log: sourcedLog(deps.Log),
|
||||
}
|
||||
// One role resolver shared by the Server handlers and the hub, so every
|
||||
// owner-facing entry point (REST, WS, voice) resolves the session's role the
|
||||
// same way (design/22 §4.5) instead of each hardcoding loop.OwnerEnv().
|
||||
s.envResolver = turnEnvResolver{history: deps.History, personas: deps.Personas, log: s.log}
|
||||
s.hub = newHub(s)
|
||||
s.hub.orchestrator = newOrchestrator(s)
|
||||
s.hub.start()
|
||||
|
||||
@@ -128,11 +128,12 @@ type sessionState struct {
|
||||
}
|
||||
|
||||
// pendingMsg is one queued user turn. It carries its own env so a resume runs
|
||||
// under the same memory-isolation boundary the message arrived with, plus the
|
||||
// client deviceID of the originating turn (design/16 §4.5) so the resumed
|
||||
// assistant reply is tagged with the same client that sent the message, and the
|
||||
// turn's behavior mode (design/16 §5.1) so the resumed reply is persisted under
|
||||
// the same mode as the user message that started it.
|
||||
// under the same memory-isolation boundary — and, since design/22, the same role
|
||||
// (env.PersonaID) — the message arrived with, plus the client deviceID of the
|
||||
// originating turn (design/16 §4.5) so the resumed assistant reply is tagged with
|
||||
// the same client that sent the message, and the turn's behavior mode (design/16
|
||||
// §5.1) so the resumed reply is persisted under the same mode as the user message
|
||||
// that started it.
|
||||
type pendingMsg struct {
|
||||
messages []model.Message
|
||||
env loop.SessionEnv
|
||||
@@ -234,7 +235,7 @@ func (o *Orchestrator) submitInternal(ctx context.Context, sessionID string, mes
|
||||
depth := len(st.pending)
|
||||
mode := st.mode
|
||||
o.mu.Unlock()
|
||||
o.persistUserMessages(ctx, sessionID, messages, deviceID, msgMode)
|
||||
o.persistUserMessages(ctx, sessionID, messages, deviceID, msgMode, env.PersonaID)
|
||||
o.emitState(sessionID, EventPendingAck, map[string]any{"sessionId": sessionID, "mode": mode, "queueDepth": depth})
|
||||
return SubmitResult{Accepted: true, Pending: true, QueueDepth: depth}, nil
|
||||
}
|
||||
@@ -248,14 +249,14 @@ func (o *Orchestrator) submitInternal(ctx context.Context, sessionID string, mes
|
||||
o.mu.Unlock()
|
||||
|
||||
o.emitState(sessionID, EventSessionBusy, map[string]any{"sessionId": sessionID, "mode": ModeThinking})
|
||||
o.persistUserMessages(ctx, sessionID, messages, deviceID, msgMode)
|
||||
o.persistUserMessages(ctx, sessionID, messages, deviceID, msgMode, env.PersonaID)
|
||||
|
||||
if sync {
|
||||
res, err := o.run(runCtx, sessionID, messages, env)
|
||||
if err != nil {
|
||||
o.log.Error("orchestrator turn", "err", err, "session", sessionID)
|
||||
}
|
||||
_ = o.completeTurn(sessionID, gen, res, err, deviceID, msgMode)
|
||||
_ = o.completeTurn(sessionID, gen, res, err, deviceID, msgMode, env.PersonaID)
|
||||
return SubmitResult{Accepted: true, Immediate: true, Err: err}, res
|
||||
}
|
||||
|
||||
@@ -266,14 +267,16 @@ func (o *Orchestrator) submitInternal(ctx context.Context, sessionID string, mes
|
||||
// goTurn runs a single turn on a background goroutine and, when it finishes,
|
||||
// hands the outcome to completeTurn so the orchestrator can resume the queue.
|
||||
// deviceID tags the persistent assistant reply with the client that sent the turn
|
||||
// (design/16 §4.5) and mode with the turn's behavior mode (design/16 §5.1).
|
||||
// (design/16 §4.5), mode with the turn's behavior mode (design/16 §5.1) and env is
|
||||
// the turn's resolved role/isolation environment (design/22 §4.5), so the reply is
|
||||
// filed under the role that produced it.
|
||||
func (o *Orchestrator) goTurn(sessionID string, gen uint64, messages []model.Message, env loop.SessionEnv, ctx context.Context, cancel context.CancelFunc, deviceID, mode string) {
|
||||
defer cancel()
|
||||
res, err := o.run(ctx, sessionID, messages, env)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
o.log.Error("orchestrator turn", "err", err, "session", sessionID)
|
||||
}
|
||||
_ = o.completeTurn(sessionID, gen, res, err, deviceID, mode)
|
||||
_ = o.completeTurn(sessionID, gen, res, err, deviceID, mode, env.PersonaID)
|
||||
}
|
||||
|
||||
// completeTurn runs after a turn settles (either it finished, errored, or was
|
||||
@@ -282,10 +285,11 @@ func (o *Orchestrator) goTurn(sessionID string, gen uint64, messages []model.Mes
|
||||
// message "remembers" the prior context instead of starting from a blank slate
|
||||
// (design/15 §2.2: incremental, not full replay). A stale generation (an
|
||||
// interrupt or a newer top-level turn superseded this one) is a no-op.
|
||||
// deviceID is the originating turn's client id and mode its behavior mode, both
|
||||
// used to tag the persisted reply (design/16 §4.5, §5.1).
|
||||
func (o *Orchestrator) completeTurn(sessionID string, gen uint64, res *loop.Result, runErr error, deviceID, mode string) error {
|
||||
o.persistAssistantReply(sessionID, res, deviceID, mode)
|
||||
// deviceID is the originating turn's client id, mode its behavior mode and
|
||||
// personaID the role it spoke as, all used to tag the persisted reply
|
||||
// (design/16 §4.5, §5.1; design/22 §7-5).
|
||||
func (o *Orchestrator) completeTurn(sessionID string, gen uint64, res *loop.Result, runErr error, deviceID, mode, personaID string) error {
|
||||
o.persistAssistantReply(sessionID, res, deviceID, mode, personaID)
|
||||
o.mu.Lock()
|
||||
st := o.states[sessionID]
|
||||
if st == nil || st.gen != gen {
|
||||
@@ -458,40 +462,3 @@ func deviceIDFrom(ctx context.Context) string {
|
||||
v, _ := ctx.Value(deviceIDContextKey{}).(string)
|
||||
return v
|
||||
}
|
||||
|
||||
// boundedTail returns a fresh copy of the last maxTail messages, so continuation
|
||||
// stays incremental and bounded (design/15 §2.2, §4) and never aliases the input
|
||||
// slice or another state's tail.
|
||||
func (o *Orchestrator) boundedTail(msgs []model.Message) []model.Message {
|
||||
if len(msgs) <= o.maxTail {
|
||||
return append([]model.Message(nil), msgs...)
|
||||
}
|
||||
out := make([]model.Message, o.maxTail)
|
||||
copy(out, msgs[len(msgs)-o.maxTail:])
|
||||
return out
|
||||
}
|
||||
|
||||
// messagesEmpty reports whether a turn carries no usable text or image, so the
|
||||
// orchestrator does not mark a session busy on a vacuous message.
|
||||
func (o *Orchestrator) messagesEmpty(msgs []model.Message) bool {
|
||||
for _, m := range msgs {
|
||||
for _, c := range m.Content {
|
||||
if c.Type == model.ContentTypeText && c.Text != "" {
|
||||
return false
|
||||
}
|
||||
if c.Type == model.ContentTypeImage && c.ImageURL != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// concatMessages returns a new slice combining a and b (never reusing a or b
|
||||
// backing arrays) so the continuation tail is safe to hand to a concurrent run.
|
||||
func concatMessages(a []model.Message, b ...model.Message) []model.Message {
|
||||
out := make([]model.Message, 0, len(a)+len(b))
|
||||
out = append(out, a...)
|
||||
out = append(out, b...)
|
||||
return out
|
||||
}
|
||||
@@ -49,11 +49,13 @@ func modeFrom(ctx context.Context) string {
|
||||
// history store so the raw user stream is durable before the turn resolves, then
|
||||
// notifies the transport so every browser of the same account can append it
|
||||
// without a manual refresh (design/16 §3.3, §4.2). deviceID tags the message with
|
||||
// the sending client (design/16 §4.5) and mode is the behavior mode the turn was
|
||||
// sent in (design/16 §5.1), falling back to modeChat when empty. It is a no-op
|
||||
// when no history store is wired. Rejected turns (empty, pending-full) never
|
||||
// reach it, so nothing vacuous is persisted.
|
||||
func (o *Orchestrator) persistUserMessages(ctx context.Context, sessionID string, messages []model.Message, deviceID, mode string) {
|
||||
// the sending client (design/16 §4.5), mode is the behavior mode the turn was
|
||||
// sent in (design/16 §5.1), falling back to modeChat when empty, and personaID is
|
||||
// the role the turn speaks as (design/22 §7-5) — the role of the moment, so a
|
||||
// session that later switches roles keeps an accurate "who said this" stream. It
|
||||
// is a no-op when no history store is wired. Rejected turns (empty, pending-full)
|
||||
// never reach it, so nothing vacuous is persisted.
|
||||
func (o *Orchestrator) persistUserMessages(ctx context.Context, sessionID string, messages []model.Message, deviceID, mode, personaID string) {
|
||||
if o.history == nil {
|
||||
return
|
||||
}
|
||||
@@ -65,7 +67,7 @@ func (o *Orchestrator) persistUserMessages(ctx context.Context, sessionID string
|
||||
if text == "" && image == "" {
|
||||
continue
|
||||
}
|
||||
full, err := o.history.AppendFull(ctx, history.Message{SessionID: sessionID, Role: history.RoleUser, Content: text, Image: image, DeviceID: deviceID, Mode: modeOrDefault(mode)})
|
||||
full, err := o.history.AppendFull(ctx, history.Message{SessionID: sessionID, Role: history.RoleUser, Content: text, Image: image, DeviceID: deviceID, Mode: modeOrDefault(mode), PersonaID: personaID})
|
||||
if err != nil {
|
||||
o.log.Error("orchestrator persist user", "err", err, "session", sessionID, "device_id", deviceID)
|
||||
continue
|
||||
@@ -76,19 +78,20 @@ func (o *Orchestrator) persistUserMessages(ctx context.Context, sessionID string
|
||||
|
||||
// persistAssistantReply writes the final assistant text of a settled turn to the
|
||||
// history store, then notifies the transport (design/16 §3.3, §4.2). deviceID tags
|
||||
// the reply with the client that sent the turn (design/16 §4.5) and mode is the
|
||||
// the reply with the client that sent the turn (design/16 §4.5), mode is the
|
||||
// behavior mode of that turn (design/16 §5.1), falling back to modeChat when
|
||||
// empty. Mood is the persona's mood for that turn (design/01 §2 情绪状态机), taken
|
||||
// off the loop result, so the stored/DTO/`message_persisted` mood is real data
|
||||
// rather than a permanently empty column; a turn with no mood tracking stores an
|
||||
// empty mood. It is a no-op when no history store is wired or the turn produced no
|
||||
// text (interrupted/errored turns leave res nil). The write runs under a fresh
|
||||
// empty, and personaID is the role that produced the reply (design/22 §7-5). Mood
|
||||
// is the persona's mood for that turn (design/01 §2 情绪状态机), taken off the loop
|
||||
// result, so the stored/DTO/`message_persisted` mood is real data rather than a
|
||||
// permanently empty column; a turn with no mood tracking stores an empty mood. It
|
||||
// is a no-op when no history store is wired or the turn produced no text
|
||||
// (interrupted/errored turns leave res nil). The write runs under a fresh
|
||||
// background context so a canceled turn context never aborts it.
|
||||
func (o *Orchestrator) persistAssistantReply(sessionID string, res *loop.Result, deviceID, mode string) {
|
||||
func (o *Orchestrator) persistAssistantReply(sessionID string, res *loop.Result, deviceID, mode, personaID string) {
|
||||
if o.history == nil || res == nil || res.Text == "" {
|
||||
return
|
||||
}
|
||||
full, err := o.history.AppendFull(context.Background(), history.Message{SessionID: sessionID, Role: history.RoleAssistant, Content: res.Text, Mood: res.Mood, DeviceID: deviceID, Mode: modeOrDefault(mode)})
|
||||
full, err := o.history.AppendFull(context.Background(), history.Message{SessionID: sessionID, Role: history.RoleAssistant, Content: res.Text, Mood: res.Mood, DeviceID: deviceID, Mode: modeOrDefault(mode), PersonaID: personaID})
|
||||
if err != nil {
|
||||
o.log.Error("orchestrator persist assistant", "err", err, "session", sessionID, "device_id", deviceID)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package gateway
|
||||
|
||||
import "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
|
||||
// This file owns the conversation-tail helpers of the session orchestrator
|
||||
// (design/15 §2.2/§4): the bounded window that continuation resumes from and the
|
||||
// emptiness check that keeps a vacuous turn from marking a session busy. They are
|
||||
// pure functions over []model.Message, kept apart from the state machine so the
|
||||
// orchestrator file stays small.
|
||||
|
||||
// boundedTail returns a fresh copy of the last maxTail messages, so continuation
|
||||
// stays incremental and bounded (design/15 §2.2, §4) and never aliases the input
|
||||
// slice or another state's tail.
|
||||
func (o *Orchestrator) boundedTail(msgs []model.Message) []model.Message {
|
||||
if len(msgs) <= o.maxTail {
|
||||
return append([]model.Message(nil), msgs...)
|
||||
}
|
||||
out := make([]model.Message, o.maxTail)
|
||||
copy(out, msgs[len(msgs)-o.maxTail:])
|
||||
return out
|
||||
}
|
||||
|
||||
// messagesEmpty reports whether a turn carries no usable text or image, so the
|
||||
// orchestrator does not mark a session busy on a vacuous message.
|
||||
func (o *Orchestrator) messagesEmpty(msgs []model.Message) bool {
|
||||
for _, m := range msgs {
|
||||
for _, c := range m.Content {
|
||||
if c.Type == model.ContentTypeText && c.Text != "" {
|
||||
return false
|
||||
}
|
||||
if c.Type == model.ContentTypeImage && c.ImageURL != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// concatMessages returns a new slice combining a and b (never reusing a or b
|
||||
// backing arrays) so the continuation tail is safe to hand to a concurrent run.
|
||||
func concatMessages(a []model.Message, b ...model.Message) []model.Message {
|
||||
out := make([]model.Message, 0, len(a)+len(b))
|
||||
out = append(out, a...)
|
||||
out = append(out, b...)
|
||||
return out
|
||||
}
|
||||
@@ -156,8 +156,10 @@ func (h *hub) runVoiceTurn(c *wsConn, req voiceInputRequest) {
|
||||
return
|
||||
}
|
||||
// The Web main session is the owner's private conversation, so it binds the
|
||||
// full-access env: memory read+write, unchanged behavior.
|
||||
res, err := h.runner.Run(loop.WithSessionEnv(ctx, loop.OwnerEnv()), req.SessionID, []model.Message{model.TextMessage(model.RoleUser, transcript)})
|
||||
// full-access env: memory read+write, unchanged behavior. The role comes from the
|
||||
// session's binding (design/22 §4.5).
|
||||
env := h.envResolver.owner(ctx, req.SessionID)
|
||||
res, err := h.runner.Run(loop.WithSessionEnv(ctx, env), req.SessionID, []model.Message{model.TextMessage(model.RoleUser, transcript)})
|
||||
if err != nil {
|
||||
h.log.Warn("voice chat run", "err", err, "session", req.SessionID)
|
||||
h.voiceError(c, "voice chat failed")
|
||||
|
||||
@@ -60,12 +60,15 @@ type hub struct {
|
||||
streaming bool
|
||||
orchestrator *Orchestrator
|
||||
history HistoryStore
|
||||
log *slog.Logger
|
||||
upgrader websocket.Upgrader
|
||||
origins map[string]bool
|
||||
allowAll bool
|
||||
cancel context.CancelFunc
|
||||
streamSeq atomic.Uint64
|
||||
// envResolver resolves each turn's role (design/22 §4.5); it mirrors the
|
||||
// server's resolver so the WS path and the REST path never diverge.
|
||||
envResolver turnEnvResolver
|
||||
log *slog.Logger
|
||||
upgrader websocket.Upgrader
|
||||
origins map[string]bool
|
||||
allowAll bool
|
||||
cancel context.CancelFunc
|
||||
streamSeq atomic.Uint64
|
||||
}
|
||||
|
||||
// newHub builds a hub bound to the server's dependencies.
|
||||
@@ -80,6 +83,7 @@ func newHub(s *Server) *hub {
|
||||
voice: s.voice,
|
||||
streaming: s.streaming,
|
||||
history: s.history,
|
||||
envResolver: s.envResolver,
|
||||
log: s.log,
|
||||
origins: origins,
|
||||
allowAll: allowAll,
|
||||
|
||||
@@ -58,17 +58,21 @@ func (h *hub) streamChat(ctx context.Context, payload any) {
|
||||
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.
|
||||
// it binds the full-access env: memory read+write, unchanged behavior. The role
|
||||
// comes from the session's binding (design/22 §4.5): a session switched to role Y
|
||||
// answers as Y on the next turn, while an unbound/existing session keeps
|
||||
// resolving to the global default.
|
||||
msgs := userChatMessages(req.Text, req.Image)
|
||||
// Thread the client's deviceID and behavior mode into the orchestrator via ctx
|
||||
// so both the persisted user turn and the assistant reply are tagged
|
||||
// (design/16 §4.5, §5.1).
|
||||
ctx = withMode(withDeviceID(ctx, req.DeviceID), req.Mode)
|
||||
env := h.envResolver.owner(ctx, req.SessionID)
|
||||
if h.orchestrator != nil {
|
||||
_ = h.orchestrator.Submit(ctx, req.SessionID, msgs, loop.OwnerEnv())
|
||||
_ = h.orchestrator.Submit(ctx, req.SessionID, msgs, env)
|
||||
return
|
||||
}
|
||||
_, _ = h.runTurn(ctx, req.SessionID, msgs, loop.OwnerEnv())
|
||||
_, _ = h.runTurn(ctx, req.SessionID, msgs, env)
|
||||
}
|
||||
|
||||
// runTurn executes one agent turn and broadcasts its output stream. It is the
|
||||
|
||||
Reference in new issue
Block a user