Files
Cyrene_v2/internal/runtime/tool/repair.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

114 lines
3.2 KiB
Go

package tool
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
)
// fencedJSONRe matches a code-fence wrapper some models emit around tool-call
// JSON, e.g. ```json {...} ```. The captured group is the inner JSON.
var fencedJSONRe = regexp.MustCompile("(?s)^[\\s`]*```(?:json)?[\\r\\n]*(.*?)[\\r\\n]*```\\s*$")
// LenientJSONUnmarshal unmarshals raw into dest, applying a few tolerant repairs
// for the malformed tool-call JSON models sometimes emit, before falling back to
// strict encoding/json. Repairs are applied in order:
//
// 1. strip a wrapping ```json code fence (and stray backticks);
// 2. trim surrounding whitespace;
// 3. strip trailing commas before `}` and `]`;
// 4. attempt the strict decode.
//
// The function reports the raw json.Unmarshal error (wrapped) when every repair
// fails, so a caller can fall back to treating the payload as plain text without
// crashing — the malformed call never aborts the round. Full repair (unquoted
// keys, single-quoted strings, smart quotes) is deliberately left for a later
// milestone; the load-bearing guarantee here is that a malformed envelope is
// recoverable or degrades to text rather than throwing.
func LenientJSONUnmarshal(raw []byte, dest any) error {
candidates := repairCandidates(raw)
var lastErr error
for _, c := range candidates {
if err := json.Unmarshal(c, dest); err == nil {
return nil
} else {
lastErr = err
}
}
return fmt.Errorf("tool: lenient json: %w", lastErr)
}
// repairCandidates returns the ordered list of byte slices to try, deduplicated:
// the raw input, the fenced-stripped input, and trailing-comma-stripped variants.
func repairCandidates(raw []byte) [][]byte {
out := [][]byte{nil}
seen := map[string]bool{}
push := func(b []byte) {
s := string(b)
if seen[s] {
return
}
seen[s] = true
out = append(out, b)
}
push(bytes.TrimSpace(raw))
clean := raw
if m := fencedJSONRe.FindSubmatch(raw); len(m) == 2 {
clean = bytes.TrimSpace(m[1])
push(clean)
}
clean = bytes.TrimSpace(clean)
push(bytes.TrimSpace(clean))
push(bytes.TrimSpace(stripTrailingCommas(clean)))
push(bytes.TrimSpace(stripTrailingCommas(bytes.TrimSpace(raw))))
return out
}
// stripTrailingCommas removes commas that sit immediately before a closing `}`
// or `]` (ignoring whitespace), the most common single-token repair for truncated
// model output such as `{"a":1,}`.
func stripTrailingCommas(b []byte) []byte {
if !bytes.ContainsAny(b, "}]") {
return b
}
// Scan for a comma run whose next non-whitespace byte is a closing bracket; a
// copy is built so the original bytes are never mutated.
out := make([]byte, 0, len(b))
skipComma := false
for i := 0; i < len(b); i++ {
if b[i] == ',' {
// Peek ahead past whitespace for a closing bracket.
j := i + 1
for j < len(b) && isJSONSpace(b[j]) {
j++
}
if j < len(b) && (b[j] == '}' || b[j] == ']') {
skipComma = true
}
}
if skipComma && isJSONSpace(b[i]) {
continue
}
if skipComma && b[i] == ',' {
skipComma = false
continue
}
out = append(out, b[i])
}
return out
}
// isJSONSpace reports whether b is JSON insignificant whitespace.
func isJSONSpace(b byte) bool {
switch b {
case ' ', '\t', '\r', '\n':
return true
default:
return false
}
}