feat(emotion): A1 情绪系统接线 + refactor: 拆分 channelbridge.go
A1 情绪接线: - loop 回合边界钩子(TurnEnd/OnTurnEnd/settleTurn, Result.Mood); 每轮一次非每步 - persona/emotion: React(valence五档) + Machine.Move(BFS最短合法路径一步) + Observer(observe/decay/好感度,仅变化才emit); 好感度步长读角色配置(cyrene delta=10, 0..700) - 落库 Mood(web session_persist.res.Mood + IM channelbridge/persist; user消息不带mood); WS mood事件(BroadcastMood,仅变化); per-persona隔离; 群聊/陌生人只读不写不发 - cmd/cyrene/emotion.go 生产接线 + wire.go 注入 loop.Options.OnTurnEnd - 22 测试(状态机被loop调用/Mood非空落库/mood帧shape/只变化才发/群聊只读) + 真二进制冒烟 - Docs: api-client v0.32 §3.7 情绪事件 + 开源对照清单(companion 应用对照) - 诚实: 本机无LLM凭据→未活体验证'模型返回后完整轮次'一环 拆分 channelbridge.go 816→257(纯搬移零逻辑): connect/inbound/outbound/blacklist/helpers.go; A1 的 IM mood 调用点落在新 inbound.go, 故与本提交同批 回滚 6 个 gofmt 顺手格式化文件(capacity_loop_test/flow/source_test/findchannel_test/admin_channels_platform_test/history) 缩 diff, 含 history.go 注释被转弯引号
This commit is contained in:
1 parent
610b330025
commit
1a85de555d
27 files changed
+1946
-594
No files matched your search
@@ -73,6 +73,10 @@ type Result struct {
|
||||
// ToolCallsExecuted is the number of tool calls the loop invoked, including
|
||||
// those that failed.
|
||||
ToolCallsExecuted int
|
||||
// Mood is the persona's mood label for this turn, as returned by the
|
||||
// OnTurnEnd hook ("" when no hook is wired). The persistence layer carries it
|
||||
// onto the assistant message (design/16 §3.3).
|
||||
Mood string
|
||||
}
|
||||
|
||||
// Loop is the default agent execution engine. It is configured once via New and
|
||||
@@ -80,32 +84,33 @@ type Result struct {
|
||||
// dispatcher, stores, recorder, tracer) are themselves concurrency-safe, which
|
||||
// they are by contract. Run keeps all loop state on the stack.
|
||||
type Loop struct {
|
||||
agent *agent.Agent
|
||||
tools *tool.Dispatcher
|
||||
capacity *capacity.Decider
|
||||
onCapacity func(capacity.Event)
|
||||
memory *memory.Store
|
||||
retriever *memory.Retriever
|
||||
working *memory.WorkingMemory
|
||||
extractor memory.Extractor
|
||||
checkpoint checkpointStore
|
||||
tracer *trace.Tracer
|
||||
flow *FlowPublisher
|
||||
guards *guardrail.Pipeline
|
||||
personaID string
|
||||
timeLocation *time.Location
|
||||
timeZoneName string
|
||||
maxRounds int
|
||||
toolExec string
|
||||
toolParallelism int
|
||||
hooks ToolLoopHooks
|
||||
onStream func(model.StreamEvent)
|
||||
onAudit func(AuditEvent)
|
||||
maxContextTokens int
|
||||
compactor Compactor
|
||||
transformContext func(context.Context, []model.Message, int) []model.Message
|
||||
imageResolver ImageResolver
|
||||
log *slog.Logger
|
||||
agent *agent.Agent
|
||||
tools *tool.Dispatcher
|
||||
capacity *capacity.Decider
|
||||
onCapacity func(capacity.Event)
|
||||
memory *memory.Store
|
||||
retriever *memory.Retriever
|
||||
working *memory.WorkingMemory
|
||||
extractor memory.Extractor
|
||||
checkpoint checkpointStore
|
||||
tracer *trace.Tracer
|
||||
flow *FlowPublisher
|
||||
guards *guardrail.Pipeline
|
||||
personaID string
|
||||
timeLocation *time.Location
|
||||
timeZoneName string
|
||||
maxRounds int
|
||||
toolExec string
|
||||
toolParallelism int
|
||||
hooks ToolLoopHooks
|
||||
onStream func(model.StreamEvent)
|
||||
onAudit func(AuditEvent)
|
||||
onTurnEnd TurnEndHook
|
||||
maxContextTokens int
|
||||
compactor Compactor
|
||||
transformContext func(context.Context, []model.Message, int) []model.Message
|
||||
imageResolver ImageResolver
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// New builds a Loop from opts, applying defaults. A non-positive MaxRounds
|
||||
@@ -153,6 +158,7 @@ func New(opts Options) *Loop {
|
||||
hooks: opts.Hooks,
|
||||
onStream: opts.OnStream,
|
||||
onAudit: opts.OnAudit,
|
||||
onTurnEnd: opts.OnTurnEnd,
|
||||
maxContextTokens: opts.MaxContextTokens,
|
||||
compactor: compactor,
|
||||
transformContext: opts.TransformContext,
|
||||
|
||||
@@ -43,6 +43,13 @@ type Options struct {
|
||||
// small "xx 工具在群聊被拒" note. Nil = the rejection is still fed back to the
|
||||
// model as a soft not_allowed result, just not recorded to an external sink.
|
||||
OnAudit func(AuditEvent)
|
||||
// OnTurnEnd, when non-nil, is called once per settled turn (a Run that
|
||||
// returned a Result) with the turn's user/assistant text and the persona the
|
||||
// loop is bound to, so a caller can advance state that follows the persona —
|
||||
// the emotion machine and affection curve of design/01 §2. Its return value
|
||||
// is recorded on Result.Mood and carried to the persisted assistant message.
|
||||
// Nil = the loop reports nothing and Result.Mood stays empty.
|
||||
OnTurnEnd TurnEndHook
|
||||
// Memory is the long-term memory store used to persist extracted items.
|
||||
Memory *memory.Store
|
||||
// Retriever injects relevant memories into the context, re-evaluated every
|
||||
|
||||
@@ -21,6 +21,10 @@ import (
|
||||
// invocation), and after each step the memory Extractor runs with errors logged
|
||||
// rather than fatal.
|
||||
//
|
||||
// When a turn settles with a Result, the OnTurnEnd hook is called once for that
|
||||
// turn (never per step) and its mood label is recorded on Result.Mood, so the
|
||||
// layers around the loop can advance persona state and tag the persisted reply.
|
||||
//
|
||||
// It returns the final answer, or a partial Result with StopReasonMaxRounds when
|
||||
// the budget is exhausted without a final answer. Step errors are wrapped with %w
|
||||
// so callers can classify them with errors.Is.
|
||||
@@ -81,6 +85,7 @@ func (l *Loop) Run(ctx context.Context, sessionID string, messages []model.Messa
|
||||
res.StopReason = outcome.stopReason
|
||||
l.saveCheckpoint(ctx, sessionID, step, msgs, outcome.stopReason)
|
||||
l.extractMemory(ctx, msgs, step)
|
||||
l.settleTurn(ctx, sessionID, msgs, res)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
@@ -100,6 +105,7 @@ func (l *Loop) Run(ctx context.Context, sessionID string, messages []model.Messa
|
||||
res.StopReason = StopReasonToolLoopTerminated
|
||||
l.saveCheckpoint(ctx, sessionID, step, msgs, StopReasonToolLoopTerminated)
|
||||
l.extractMemory(ctx, msgs, step)
|
||||
l.settleTurn(ctx, sessionID, msgs, res)
|
||||
return res, nil
|
||||
}
|
||||
}
|
||||
@@ -109,5 +115,6 @@ func (l *Loop) Run(ctx context.Context, sessionID string, messages []model.Messa
|
||||
res.StopReason = StopReasonMaxRounds
|
||||
l.saveCheckpoint(ctx, sessionID, l.maxRounds, msgs, StopReasonMaxRounds)
|
||||
l.extractMemory(ctx, msgs, l.maxRounds)
|
||||
l.settleTurn(ctx, sessionID, msgs, res)
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
)
|
||||
|
||||
// This file owns the loop's turn boundary: the point where one user turn has
|
||||
// settled (a Run produced a Result) and the state that follows the persona —
|
||||
// emotion and affection, design/01 §2 — is advanced outside the loop. The loop
|
||||
// itself stays persona- and emotion-agnostic (design/16 §3.3: the engine
|
||||
// generates text; state and persistence belong to the layers around it), so it
|
||||
// only reports the turn and records the mood label the hook hands back.
|
||||
|
||||
// TurnEnd describes one settled turn to the loop's OnTurnEnd hook. It carries
|
||||
// everything an observer needs without the loop knowing what the observer does.
|
||||
type TurnEnd struct {
|
||||
// SessionID is the conversation the turn belonged to.
|
||||
SessionID string
|
||||
// PersonaID is the persona the loop is bound to (Options.PersonaID), so the
|
||||
// observer stays persona-scoped (design/01 §2).
|
||||
PersonaID string
|
||||
// UserText is the latest user message of the turn ("" when the turn carried
|
||||
// no user text, e.g. a resumed tool round).
|
||||
UserText string
|
||||
// AssistantText is the turn's final assistant text.
|
||||
AssistantText string
|
||||
// StopReason classifies how the turn ended.
|
||||
StopReason string
|
||||
// Steps is the number of model steps the turn took.
|
||||
Steps int
|
||||
// Env is the conversation's resolved isolation environment (owner / group /
|
||||
// stranger), so a hook can keep a restricted conversation read-only.
|
||||
Env SessionEnv
|
||||
}
|
||||
|
||||
// TurnEndHook observes a settled turn and returns the persona's mood label for
|
||||
// it ("" when the caller tracks no emotion). It runs once per settled turn — not
|
||||
// once per model step — so a multi-step tool turn applies its effect exactly
|
||||
// once. It must not block: it runs on the Run path after the answer is complete,
|
||||
// and its return value is carried on Result.Mood to the persistence layer.
|
||||
type TurnEndHook func(TurnEnd) string
|
||||
|
||||
// settleTurn reports a settled turn to the hook (when wired) and records the
|
||||
// returned mood label on the result, so the persisted assistant message carries
|
||||
// the turn's mood (design/16 §3.3). The conversation environment travels on ctx,
|
||||
// so a group/stranger turn reaches the hook as restricted.
|
||||
func (l *Loop) settleTurn(ctx context.Context, sessionID string, msgs []model.Message, res *Result) {
|
||||
if l.onTurnEnd == nil {
|
||||
return
|
||||
}
|
||||
res.Mood = l.onTurnEnd(TurnEnd{
|
||||
SessionID: sessionID,
|
||||
PersonaID: l.personaID,
|
||||
UserText: lastUserText(msgs),
|
||||
AssistantText: res.Text,
|
||||
StopReason: res.StopReason,
|
||||
Steps: res.Steps,
|
||||
Env: sessionEnvFrom(ctx),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/agent"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
)
|
||||
|
||||
// TestRunCallsOnTurnEndOnce locks the turn boundary: a settled turn is reported
|
||||
// exactly once — with the turn's own user text, the persona the loop is bound to
|
||||
// and the answer — and the label the hook returns is recorded on Result.Mood so
|
||||
// the persistence layer can tag the assistant message.
|
||||
func TestRunCallsOnTurnEndOnce(t *testing.T) {
|
||||
t.Parallel()
|
||||
ad := &mockAdapter{chat: []mgResp{{resp: model.Response{Content: "在的呀♪"}}}}
|
||||
a := newTestAgent(t, ad, nil)
|
||||
|
||||
var ends []TurnEnd
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
PersonaID: "cyrene",
|
||||
OnTurnEnd: func(end TurnEnd) string {
|
||||
ends = append(ends, end)
|
||||
return "happy"
|
||||
},
|
||||
})
|
||||
|
||||
res, err := l.Run(context.Background(), "web", []model.Message{model.TextMessage(model.RoleUser, "今天谢谢你")})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(ends) != 1 {
|
||||
t.Fatalf("OnTurnEnd calls = %d, want 1", len(ends))
|
||||
}
|
||||
got := ends[0]
|
||||
if got.SessionID != "web" || got.PersonaID != "cyrene" {
|
||||
t.Fatalf("TurnEnd = %+v, want session web / persona cyrene", got)
|
||||
}
|
||||
if got.UserText != "今天谢谢你" {
|
||||
t.Fatalf("TurnEnd.UserText = %q, want the user turn text", got.UserText)
|
||||
}
|
||||
if got.AssistantText != "在的呀♪" {
|
||||
t.Fatalf("TurnEnd.AssistantText = %q, want the final answer", got.AssistantText)
|
||||
}
|
||||
if got.StopReason != agent.StopReasonStop || got.Steps != 1 {
|
||||
t.Fatalf("TurnEnd stop/steps = %q/%d, want stop/1", got.StopReason, got.Steps)
|
||||
}
|
||||
if !got.Env.MemWritable {
|
||||
t.Fatalf("TurnEnd.Env = %+v, want the owner lane by default", got.Env)
|
||||
}
|
||||
if res.Mood != "happy" {
|
||||
t.Fatalf("Result.Mood = %q, want the hook's label", res.Mood)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunPassesRestrictedEnvToTurnEnd locks that the conversation's isolation
|
||||
// environment reaches the hook, so a group/stranger turn can be kept read-only.
|
||||
func TestRunPassesRestrictedEnvToTurnEnd(t *testing.T) {
|
||||
t.Parallel()
|
||||
ad := &mockAdapter{chat: []mgResp{{resp: model.Response{Content: "好的"}}}}
|
||||
a := newTestAgent(t, ad, nil)
|
||||
|
||||
var got TurnEnd
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
OnTurnEnd: func(end TurnEnd) string {
|
||||
got = end
|
||||
return ""
|
||||
},
|
||||
})
|
||||
env := SessionEnv{ActorEnv: "group_member", MemWritable: false}
|
||||
ctx := WithSessionEnv(context.Background(), env)
|
||||
if _, err := l.Run(ctx, "sess-group", []model.Message{model.TextMessage(model.RoleUser, "你好")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if !got.Env.Restricted() || got.Env != env {
|
||||
t.Fatalf("TurnEnd.Env = %+v, want the restricted env", got.Env)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTurnEndOnceForMultiStepTurn locks "once per turn, not per step": a
|
||||
// tool-loop turn (model → tool call → final answer) reports its boundary once,
|
||||
// and the reported user text stays the turn's user message rather than a
|
||||
// fed-back tool result.
|
||||
func TestRunTurnEndOnceForMultiStepTurn(t *testing.T) {
|
||||
t.Parallel()
|
||||
call := `{"tool_calls":[{"name":"echo","args":{"q":"hi"}}]}`
|
||||
ad := &mockAdapter{chat: []mgResp{
|
||||
{resp: model.Response{Content: call}},
|
||||
{resp: model.Response{Content: "Echoed!"}},
|
||||
}}
|
||||
td := dispatcherWith(t, &mockTool{name: "echo", result: "hi"})
|
||||
a := newTestAgent(t, ad, td)
|
||||
|
||||
var ends []TurnEnd
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
PersonaID: "cyrene",
|
||||
OnTurnEnd: func(end TurnEnd) string {
|
||||
ends = append(ends, end)
|
||||
return "calm"
|
||||
},
|
||||
})
|
||||
|
||||
res, err := l.Run(context.Background(), "web", []model.Message{model.TextMessage(model.RoleUser, "echo this")})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(ends) != 1 {
|
||||
t.Fatalf("OnTurnEnd calls = %d, want 1 for a 2-step turn", len(ends))
|
||||
}
|
||||
if ends[0].UserText != "echo this" {
|
||||
t.Fatalf("TurnEnd.UserText = %q, want the turn's user text", ends[0].UserText)
|
||||
}
|
||||
if ends[0].AssistantText != "Echoed!" || ends[0].Steps != 2 {
|
||||
t.Fatalf("TurnEnd = %+v, want the final answer at 2 steps", ends[0])
|
||||
}
|
||||
if res.Mood != "calm" {
|
||||
t.Fatalf("Result.Mood = %q, want calm", res.Mood)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunNoTurnEndOnError locks that a failed turn is not reported: nothing
|
||||
// settled, so persona state must not advance.
|
||||
func TestRunNoTurnEndOnError(t *testing.T) {
|
||||
t.Parallel()
|
||||
ad := &mockAdapter{chat: []mgResp{{err: errors.New("model down")}}}
|
||||
a := newTestAgent(t, ad, nil)
|
||||
|
||||
calls := 0
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
OnTurnEnd: func(TurnEnd) string { calls++; return "happy" },
|
||||
})
|
||||
if _, err := l.Run(context.Background(), "web", []model.Message{model.TextMessage(model.RoleUser, "我爱你")}); err == nil {
|
||||
t.Fatal("Run: want an error")
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("OnTurnEnd calls = %d, want 0 on a failed turn", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunWithoutTurnEndHook locks the nil-tolerance: an unwired hook leaves the
|
||||
// mood empty and Run behaves exactly as before.
|
||||
func TestRunWithoutTurnEndHook(t *testing.T) {
|
||||
t.Parallel()
|
||||
ad := &mockAdapter{chat: []mgResp{{resp: model.Response{Content: "hi"}}}}
|
||||
l := New(Options{Agent: newTestAgent(t, ad, nil)})
|
||||
|
||||
res, err := l.Run(context.Background(), "web", []model.Message{model.TextMessage(model.RoleUser, "hi")})
|
||||
if err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if res.Mood != "" {
|
||||
t.Fatalf("Result.Mood = %q, want empty without a hook", res.Mood)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user