主人 2026-10-03 拍板「注释一律中文」;本模块按长期分批协议(一个模块一次派工)执行。 注释行数 1329 → 1329 逐行 1:1(含中文 33 → 1304);行尾注释 5 条一并译。 校验:机械校验(非注释改动行)= 空;独立 Go AST 程序(剥注释复渲)证明 44/44 文件代码全等; 全树 go test ./... 58 包 ok / 0 FAIL;交叉编译绿。 gofmt:capacity_loop_test.go / flow.go 改动前即未格式化,按铁律保留原样未动。
125 lines
5.2 KiB
Go
125 lines
5.2 KiB
Go
package loop
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
|
||
"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/model"
|
||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||
)
|
||
|
||
// Run 驱动 agent 循环:每轮组装一份全新的模型可见上下文
|
||
// (从当前会话重新注入相关记忆,上下文超出配置预算时
|
||
// 可选地压缩更早的轮次),然后运行至多
|
||
// MaxRounds 个 step。每个 step 运行模型(配置了 OnStream 时
|
||
// 流式),所有被请求的工具调用在每次调用的超时下执行,
|
||
// 并以 RoleTool 消息回灌,使模型能继续。
|
||
// 每一步都持久化一个 checkpoint,每一步都作为
|
||
// state_transition span 追踪(每次调用带一个 llm_call 子 span 与
|
||
// tool_call span),且当 turn 落定时记忆 Extractor 在该
|
||
// turn 的对话上运行(design/03 §1:LLM extractor 跑在后台
|
||
// goroutine 上,因此提取绝不延迟回复),错误记录日志
|
||
// 而非致命。
|
||
//
|
||
// 当 turn 带着 Result 落定时,OnTurnEnd 钩子对该
|
||
// turn 调用一次(绝不按步调用),其情绪标签记录在 Result.Mood 上,
|
||
// 使循环外围的分层能推进人格状态并标记持久化的回复。
|
||
//
|
||
// 它返回最终答案;预算耗尽而无最终答案时,返回带
|
||
// StopReasonMaxRounds 的部分 Result。step 错误用 %w 包装,
|
||
// 使调用方能以 errors.Is 分类它们。
|
||
func (l *Loop) Run(ctx context.Context, sessionID string, messages []model.Message) (*Result, error) {
|
||
if ctx == nil {
|
||
ctx = context.Background()
|
||
}
|
||
if l.agent == nil && len(l.agents) == 0 {
|
||
return nil, fmt.Errorf("loop: run: %w", ErrNilAgent)
|
||
}
|
||
|
||
// 以 quiet 播种该 Run 的 capacity 累加器,使状态能跨多步
|
||
// 工具循环演进(quiet→awake→full);nil/被禁用的判定器
|
||
// 使其不被使用。它作用域限于本次 Run,因此并发 run 绝不共享。
|
||
// 会话 id 搭同一个 context,使 capacity_awaken 的发出能
|
||
// 定向到产出它的会话(design/14 §5)。
|
||
ctx = withCapState(ctx, &capStateAccum{state: capacity.StateQuiet})
|
||
ctx = withLoopSession(ctx, sessionID)
|
||
|
||
// 恢复被中断的 run(design §1 durable execution):该会话有
|
||
// 可恢复的 checkpoint 时,重建其上下文并从下一步继续,
|
||
// 而不是从全新对话重启。不同的
|
||
// sessionID —— 或已完成 run 留下的 checkpoint —— 落到
|
||
// 全新开始(LoadLatest 未命中,或 stop reason 不可恢复)。
|
||
msgs, startStep, _ := l.loadCheckpoint(ctx, sessionID, messages)
|
||
msgs = l.resolveImages(ctx, msgs)
|
||
toolState := &toolLoopState{prevFP: make(map[string]bool)}
|
||
res := &Result{}
|
||
// 分支 Run(子代理)把其 span 并入父会话的实时
|
||
// 图;只有所属的 Run 开始与结束轮次。没有它,子代理
|
||
// 会重置前端唯一的 flowGraph,并让父级自身的节点出现断档。
|
||
if _, isBranch := flowBranch(ctx); l.flow != nil && !isBranch {
|
||
l.flow.StartRound(sessionID, lastUserText(msgs))
|
||
defer func() { l.flow.EndRound(sessionID, res.Text) }()
|
||
}
|
||
for step := startStep; step <= l.maxRounds; step++ {
|
||
if err := ctx.Err(); err != nil {
|
||
return nil, fmt.Errorf("loop: run: step %d: %w", step, err)
|
||
}
|
||
|
||
// 会话超出上下文预算时压缩更早的轮次,
|
||
// 然后为本轮组装模型可见上下文(全新记忆
|
||
// 注入 + transform 钩子),使每一步都看到最新上下文。
|
||
msgs = l.compactIfNeeded(ctx, msgs)
|
||
view := l.assembleContext(ctx, msgs, step)
|
||
|
||
rc, roundSpan := l.span(ctx, "loop.step", trace.SpanKindStateTransition)
|
||
outcome, err := l.step(rc, sessionID, view)
|
||
if err != nil {
|
||
l.spanProp(roundSpan, "error", err.Error())
|
||
l.finishSpan(roundSpan, trace.SpanStatusError)
|
||
return nil, fmt.Errorf("loop: run: step %d: %w", step, err)
|
||
}
|
||
l.spanProp(roundSpan, "step", step)
|
||
l.spanProp(roundSpan, "stop_reason", outcome.stopReason)
|
||
l.finishSpan(roundSpan, trace.SpanStatusOK)
|
||
|
||
res.Steps = step
|
||
if outcome.final {
|
||
res.Text = outcome.text
|
||
res.StopReason = outcome.stopReason
|
||
l.saveCheckpoint(ctx, sessionID, step, msgs, outcome.stopReason)
|
||
l.extractMemoryAsync(ctx, msgs, step)
|
||
l.settleTurn(ctx, sessionID, msgs, res)
|
||
return res, nil
|
||
}
|
||
|
||
batch, err := l.runToolCalls(rc, msgs, outcome.toolCalls, toolState)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("loop: run: step %d: tools: %w", step, err)
|
||
}
|
||
msgs = batch.messages
|
||
res.ToolCallsExecuted += batch.executed
|
||
l.saveCheckpoint(ctx, sessionID, step, msgs, agent.StopReasonToolCalls)
|
||
|
||
// 关键工具循环安全网(或终止钩子)不等真正的最终答案
|
||
// 就停止本轮。
|
||
if batch.terminate {
|
||
res.Text = criticalToolLoopTerminalReason
|
||
res.StopReason = StopReasonToolLoopTerminated
|
||
l.saveCheckpoint(ctx, sessionID, step, msgs, StopReasonToolLoopTerminated)
|
||
l.extractMemoryAsync(ctx, msgs, step)
|
||
l.settleTurn(ctx, sessionID, msgs, res)
|
||
return res, nil
|
||
}
|
||
}
|
||
|
||
// 预算耗尽而无最终答案。
|
||
res.Steps = l.maxRounds
|
||
res.StopReason = StopReasonMaxRounds
|
||
l.saveCheckpoint(ctx, sessionID, l.maxRounds, msgs, StopReasonMaxRounds)
|
||
l.extractMemoryAsync(ctx, msgs, l.maxRounds)
|
||
l.settleTurn(ctx, sessionID, msgs, res)
|
||
return res, nil
|
||
}
|