Files
Cyrene_v2/internal/runtime/agent/step.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

134 lines
4.9 KiB
Go

package agent
import (
"context"
"fmt"
"time"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/tool"
)
// Stop reasons carried by StepResult.StopReason, consumed by the loop (M2) to
// decide how to continue after a step.
const (
// StopReasonStop is a normal final answer with no tool calls.
StopReasonStop = "stop"
// StopReasonToolCalls means the assistant requested tool calls.
StopReasonToolCalls = "tool_calls"
// StopReasonGuardrailInput means the input guardrail blocked the request.
StopReasonGuardrailInput = "guardrail_input"
// StopReasonGuardrailOutput means the output guardrail blocked the response.
StopReasonGuardrailOutput = "guardrail_output"
)
// ToolCall is a single function call the assistant requested, decoded from a
// step. Args holds the tool arguments as a JSON object.
type ToolCall struct {
Name string `json:"name"`
Args map[string]any `json:"args"`
}
// StepResult is the outcome of a single agent step.
type StepResult struct {
// Final is true when the step produced a final answer (or was intercepted by
// a guardrail) and no tool execution is required.
Final bool
// Text is the assistant's final text, or the guardrail's block reason when
// Final is true.
Text string
// ToolCalls is non-empty when Final is false, listing the tool calls to run.
ToolCalls []ToolCall
// StopReason classifies how the step ended (see the StopReason* consts).
StopReason string
}
// RunStep executes one step of the agent loop. It assembles a model.Request from
// the agent's instructions prepended as a leading system message plus the
// conversation messages, runs input guardrails, calls the model adapter, runs
// output guardrails and decodes any tool calls. sessionID identifies the
// conversation for downstream tracing/telemetry and is currently carried without
// a sink; it is reserved for trace/persist (M2/M9).
//
// A final text answer yields Final=true with StopReason "stop"; a tool request
// yields Final=false with the decoded ToolCalls; a guardrail denial yields
// Final=true carrying the block reason. A nil adapter or a failed guardrail or
// model call returns a wrapped error.
func (a *Agent) RunStep(ctx context.Context, sessionID string, messages []model.Message) (*StepResult, error) {
req := a.buildRequest(messages)
if a.guards != nil {
verdict, err := a.guards.CheckInput(ctx, &req)
if err != nil {
return nil, fmt.Errorf("agent: check input: %w", err)
}
if verdict != nil && !verdict.Allow {
return &StepResult{Final: true, Text: verdict.Reason, StopReason: StopReasonGuardrailInput}, nil
}
}
if a.adapter == nil {
return nil, fmt.Errorf("agent: run step: %w", ErrNoAdapter)
}
start := time.Now()
resp, err := a.adapter.Chat(ctx, req, model.Options{})
if err != nil {
return nil, fmt.Errorf("agent: chat: %w", err)
}
if a.recorder != nil {
a.recorder(model.CallRecord{
Model: resp.Model,
Purpose: req.Purpose,
Tokens: resp.TotalTokens,
TookMs: time.Since(start).Milliseconds(),
})
}
if a.guards != nil {
verdict, err := a.guards.CheckOutput(ctx, &resp)
if err != nil {
return nil, fmt.Errorf("agent: check output: %w", err)
}
if verdict != nil && !verdict.Allow {
return &StepResult{Final: true, Text: verdict.Reason, StopReason: StopReasonGuardrailOutput}, nil
}
}
if calls, ok := extractToolCalls(resp); ok {
return &StepResult{Final: false, ToolCalls: calls, StopReason: StopReasonToolCalls}, nil
}
return &StepResult{Final: true, Text: resp.Content, StopReason: StopReasonStop}, nil
}
// extractToolCalls decodes tool calls from a model.Response. The current model
// layer does not parse provider tool_calls into a structured field, so the agent
// uses two conventions in priority order:
//
// 1. The normalized assistant-message placeholder: when resp.Message carries a
// ToolCallName it is a single call with no argument payload.
// 2. A JSON envelope in resp.Content of the form
// {"tool_calls":[{"name":"...","args":{...}}]}.
//
// It reports ok=true (with a non-empty slice) when a call is decoded, and
// ok=false otherwise.
func extractToolCalls(resp model.Response) ([]ToolCall, bool) {
if resp.Message.Role == model.RoleAssistant && resp.Message.ToolCallName != "" {
return []ToolCall{{Name: resp.Message.ToolCallName, Args: map[string]any{}}}, true
}
var payload struct {
ToolCalls []ToolCall `json:"tool_calls"`
}
// Lenient decode repairs common model-emitted malformations (code fences,
// trailing commas) so a slightly broken tool-call envelope does not silently
// turn into a text answer; an unrecoverable payload still yields ok=false and
// the round proceeds as text (the loop never crashes on a bad call).
if err := tool.LenientJSONUnmarshal([]byte(resp.Content), &payload); err != nil {
return nil, false
}
if len(payload.ToolCalls) == 0 {
return nil, false
}
return payload.ToolCalls, true
}