按 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)
196 lines
7.3 KiB
Go
196 lines
7.3 KiB
Go
// Package loop implements the default agent execution engine of the Cyrene v2
|
|
// runtime (DevDocs/design/04-运行时.md §1). It owns the loop that package agent
|
|
// deliberately leaves out: assemble context from memory, drive the model for up
|
|
// to MaxRounds steps, execute any requested tool calls under a per-invoke
|
|
// timeout, feed tool results back to the model, persist a checkpoint at every
|
|
// step, emit structured traces, deliver streamed deltas and run the
|
|
// memory-extraction hook.
|
|
//
|
|
// The loop is configured with injected dependencies rather than concrete wiring,
|
|
// so it stays leaf-testable with mocks (a mock adapter, mock guardrail and mock
|
|
// tool, plus real in-memory memory/persist stores and a buffered trace recorder).
|
|
package loop
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/agent"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/capacity"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/guardrail"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/memory"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/tool"
|
|
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
|
)
|
|
|
|
// Constants that bound the loop. These are compile-time so no magic number
|
|
// appears in the run path.
|
|
const (
|
|
// DefaultMaxRounds is the tool-loop upper bound used when Options.MaxRounds
|
|
// is non-positive. It matches the agent package's own default.
|
|
DefaultMaxRounds = 8
|
|
|
|
// StopReasonMaxRounds reports that the loop exhausted its round budget
|
|
// before reaching a final answer.
|
|
StopReasonMaxRounds = "max_rounds"
|
|
|
|
// StopReasonToolLoopTerminated reports that the critical-tool-loop safety net
|
|
// stopped the run after the same tool call was repeated identically across
|
|
// consecutive rounds.
|
|
StopReasonToolLoopTerminated = "tool_loop_terminated"
|
|
|
|
// DefaultToolParallelism caps how many tool calls run concurrently when the
|
|
// loop runs a batch in parallel mode and no explicit cap is configured.
|
|
DefaultToolParallelism = 4
|
|
)
|
|
|
|
// Sentinel errors returned by the Loop. Use errors.Is to test for them; they are
|
|
// returned directly or wrapped with %w so the underlying cause stays available.
|
|
var (
|
|
// ErrNilAgent is returned by Run when neither a default agent (Options.Agent)
|
|
// nor a per-role agent pool (Options.Agents) was configured.
|
|
ErrNilAgent = errors.New("loop: nil agent")
|
|
|
|
// ErrNoAdapter is returned by Run (streaming path) when the agent was built
|
|
// without a model Adapter.
|
|
ErrNoAdapter = errors.New("loop: no model adapter")
|
|
)
|
|
|
|
// Result is the outcome of a completed Run.
|
|
type Result struct {
|
|
// Text is the final assistant text, or empty when the loop exhausted its
|
|
// budget without a final answer.
|
|
Text string
|
|
// Steps is the number of model steps executed.
|
|
Steps int
|
|
// StopReason classifies how the loop ended: an agent StopReason* value or
|
|
// StopReasonMaxRounds.
|
|
StopReason string
|
|
// 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
|
|
// safe for concurrent Run calls as long as the injected dependencies (agent,
|
|
// 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
|
|
agents map[string]*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
|
|
personaKnobs func(personaID string) (LoopKnobs, bool)
|
|
timeLocation *time.Location
|
|
timeZoneName string
|
|
maxRounds int
|
|
toolExec string
|
|
toolParallelism int
|
|
hooks ToolLoopHooks
|
|
onStream func(model.StreamEvent)
|
|
thinking *model.Thinking
|
|
reasoningEffort string
|
|
thinkingShow *bool
|
|
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
|
|
// selects DefaultMaxRounds; a nil Log is replaced by a discard logger tagged with
|
|
// source "runtime/loop". Every dependency may be nil and is tolerated until the
|
|
// step that needs it (mirroring the run-time nil-tolerance of the underlying
|
|
// packages); Run returns ErrNilAgent when no agent is configured.
|
|
func New(opts Options) *Loop {
|
|
maxRounds := opts.MaxRounds
|
|
if maxRounds <= 0 {
|
|
maxRounds = DefaultMaxRounds
|
|
}
|
|
toolExec := opts.ToolExecution
|
|
if toolExec == "" {
|
|
toolExec = toolExecParallel
|
|
}
|
|
toolParallelism := opts.ToolParallelism
|
|
if toolParallelism <= 0 {
|
|
toolParallelism = DefaultToolParallelism
|
|
}
|
|
compactor := opts.Compactor
|
|
if compactor == nil {
|
|
compactor = defaultCompactor{}
|
|
}
|
|
timeLocation, timeZoneName := loadTimezone(opts.Timezone, sourcedLog(opts.Log))
|
|
return &Loop{
|
|
agent: opts.Agent,
|
|
agents: opts.Agents,
|
|
tools: opts.Tools,
|
|
capacity: opts.Capacity,
|
|
onCapacity: opts.OnCapacity,
|
|
memory: opts.Memory,
|
|
retriever: opts.Retriever,
|
|
working: opts.WorkingMemory,
|
|
extractor: opts.Extractor,
|
|
checkpoint: opts.Checkpoint,
|
|
tracer: opts.Tracer,
|
|
flow: opts.Flow,
|
|
guards: opts.Guards,
|
|
personaID: opts.PersonaID,
|
|
personaKnobs: opts.PersonaKnobs,
|
|
timeLocation: timeLocation,
|
|
timeZoneName: timeZoneName,
|
|
maxRounds: maxRounds,
|
|
toolExec: toolExec,
|
|
toolParallelism: toolParallelism,
|
|
hooks: opts.Hooks,
|
|
onStream: opts.OnStream,
|
|
thinking: opts.Thinking,
|
|
reasoningEffort: opts.ReasoningEffort,
|
|
thinkingShow: opts.ThinkingShowToUser,
|
|
onAudit: opts.OnAudit,
|
|
onTurnEnd: opts.OnTurnEnd,
|
|
maxContextTokens: opts.MaxContextTokens,
|
|
compactor: compactor,
|
|
transformContext: opts.TransformContext,
|
|
imageResolver: opts.Vision,
|
|
log: sourcedLog(opts.Log),
|
|
}
|
|
}
|
|
|
|
// MaxRounds returns the tool-loop upper bound configured for the loop.
|
|
func (l *Loop) MaxRounds() int { return l.maxRounds }
|
|
|
|
// Agent returns the injected default agent (Options.Agent). The per-role pool is
|
|
// reached through the turn's context, not this getter.
|
|
func (l *Loop) Agent() *agent.Agent { return l.agent }
|
|
|
|
// sourcedLog returns a logger tagged with the module source "runtime/loop",
|
|
// replacing a nil logger with a discard one so the loop can always log safely.
|
|
func sourcedLog(l *slog.Logger) *slog.Logger {
|
|
if l == nil {
|
|
l = slog.New(slog.NewTextHandler(io.Discard, nil))
|
|
}
|
|
return logger.WithSource(l, "runtime/loop")
|
|
}
|