Files
Cyrene_v2/internal/runtime/loop/loop.go
T
Aska 35cb2d3942
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat(loop): Top5#4 工具循环增强(对齐 OpenClaw agent-loop)——重复检测/并行串行/钩子/errorKind/repair
- 重复调用安全网(critical-tool-loop):指纹=name+canonical JSON(args);批内重复第二次跳过回喂
  「duplicate call」;跨轮关键重复(同指纹重现)→首次 block+criticalSeen,再次连续重复→终止整轮
  StopReasonToolLoopTerminated(替代裸 8 轮针对同调用的硬截止)。
- 并行/串行混合:invokeParallel 默认并行,信号量(ToolParallelism 默认4)限并发,结果按调用索引
  写回按原序渲染;串行触发=Options.ToolExecution:sequential 或 SetToolExecutionMode(name,sequential)
  (对齐 OpenClaw「一个 sequential 标记→整组串行」);goroutine 不泄漏、ctx 取消快速返回。
- 工具钩子:ToolLoopHooks(BatchAdmit/CallAdmit/AfterCall/AfterOutcome) 经 Options.Hooks 注入,
  均 nil-tolerant;供后续敏感操作代审复用(design/11)。terminate 用 every 语义。
- status 分类:ToolError.Kind() 区分 argument-validation(JSON-Schema 失败)/execution;
  失败消息渲染 {kind,message} 让模型区分重发参数 vs 执行失败。
- tool-call-repair:LenientJSONUnmarshal 修 fence 包裹/尾逗号畸形;agent.extractToolCalls 与
  loop.decodeToolCalls 走它;不可修复退化为文本不崩整轮。意图调用未区分回喂提示(后置)。
- tool_execution_update:流式路径 emitToolExecution 发 StreamKindToolExecution(start/end/end:error)。

go build/vet/test 全绿(46包)。TestRun_MaxRounds 改每轮不同参(原同 echo 被安全网拦,预期新行为)。
-race 受宿主 TSan VMA 限制无法运行(与代码无关)。
2026-09-06 17:57:18 +08:00

151 lines
5.5 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 (
"errors"
"io"
"log/slog"
"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/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/persist"
"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 no *agent.Agent 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
}
// 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
tools *tool.Dispatcher
memory *memory.Store
retriever *memory.Retriever
working *memory.WorkingMemory
extractor memory.Extractor
checkpoint *persist.Store
tracer *trace.Tracer
guards *guardrail.Pipeline
personaID string
maxRounds int
toolExec string
toolParallelism int
hooks ToolLoopHooks
onStream func(model.StreamEvent)
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
}
return &Loop{
agent: opts.Agent,
tools: opts.Tools,
memory: opts.Memory,
retriever: opts.Retriever,
working: opts.WorkingMemory,
extractor: opts.Extractor,
checkpoint: opts.Checkpoint,
tracer: opts.Tracer,
guards: opts.Guards,
personaID: opts.PersonaID,
maxRounds: maxRounds,
toolExec: toolExec,
toolParallelism: toolParallelism,
hooks: opts.Hooks,
onStream: opts.OnStream,
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 agent.
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")
}