#1 工具布尔标记生效(agent-106, 安全红线): loop toolSchemas/runToolCalls 加 allow-set 安全门 restrictSchemas/applyToolSecurityGate——群聊/陌生人只暴露允许工具(默认关), 被拒not_allowed软提示+AuditEvent, owner全工具不变; 身份靠 ActorEnv(非提示词) #2 checkpoint 恢复(agent-109): run.go LoadLatest + resumableStopReason门控(只恢复in-flight工具循环,不出答案不续跑), 幂等不重放副作用, 新会话不误恢复; resume_test 4用例 #3 tool_result(agent-108, 协议层): Anthropic 原生tool_result块(tool_use_id/is_error)非user纯文本 + OpenAI tool消息补tool_call_id; Content加ToolCallID/IsError等; (loop接线层2处留待,见备注) #6 capacity_awaken推送(agent-107): onCapacity从只Debug改推WS hub(BroadcastCapacityAwaken, sessionId定向+payload对齐前端AwakenPayload) 管理面板移动端(agent-110): AdminApp 汉堡菜单+抽屉侧栏+标题truncate防换行, RBAC守卫不受影响 全仓 build/vet/test绿 + 前端build绿; 前端无涉差异已对齐 备注: #3 loop接线层2处(assistant工具轮append历史 + Message.ToolCallID/IsError)留给后续; #4代审/#5子代理触发/#7拆文件后置(主人说后三不急)
110 lines
4.5 KiB
Go
110 lines
4.5 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 drives the agent loop: assemble a fresh model-visible context every round
|
|
// (re-inject relevant memory from the current conversation, optionally compacting
|
|
// the older turns when the context exceeds the configured budget), then run up to
|
|
// MaxRounds steps. Each step runs the model (streaming through OnStream when
|
|
// configured) and any requested tool calls are executed under a per-invoke
|
|
// timeout and fed back as RoleTool messages so the model can continue.
|
|
// A checkpoint is persisted at every step, every step is traced as a
|
|
// state_transition span (with an llm_call child and tool_call spans for each
|
|
// invocation), and after each step the memory Extractor runs with errors logged
|
|
// rather than fatal.
|
|
//
|
|
// It returns the final answer, or a partial Result with StopReasonMaxRounds when
|
|
// the budget is exhausted without a final answer. Step errors are wrapped with %w
|
|
// so callers can classify them with 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 {
|
|
return nil, fmt.Errorf("loop: run: %w", ErrNilAgent)
|
|
}
|
|
|
|
// Seed the per-Run capacity accumulator at quiet so the state can progress
|
|
// (quiet→awake→full) across a multi-step tool loop; a nil/disabled decider
|
|
// leaves it unused. It is scoped to this Run, so concurrent runs never share.
|
|
// The session id rides the same context so a capacity_awaken emission can be
|
|
// targeted to the session that produced it (design/14 §5).
|
|
ctx = withCapState(ctx, &capStateAccum{state: capacity.StateQuiet})
|
|
ctx = withLoopSession(ctx, sessionID)
|
|
|
|
// Resume an interrupted run (design §1 durable execution): when the session
|
|
// has a resumable checkpoint, rebuild its context and continue at the next
|
|
// step rather than restarting from a fresh conversation. A different
|
|
// sessionID — or a checkpoint left by a completed run — falls through to a
|
|
// fresh start (LoadLatest misses, or the stop reason is not resumable).
|
|
msgs, startStep, _ := l.loadCheckpoint(ctx, sessionID, messages)
|
|
msgs = l.resolveImages(ctx, msgs)
|
|
toolState := &toolLoopState{prevFP: make(map[string]bool)}
|
|
res := &Result{}
|
|
for step := startStep; step <= l.maxRounds; step++ {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, fmt.Errorf("loop: run: step %d: %w", step, err)
|
|
}
|
|
|
|
// Compact older turns when the conversation exceeds the context budget,
|
|
// then assemble the model-visible context for this round (fresh memory
|
|
// injection + transform hook), so every step sees an up-to-date context.
|
|
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.extractMemory(ctx, msgs, step)
|
|
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)
|
|
l.extractMemory(ctx, msgs, step)
|
|
|
|
// The critical-tool-loop safety net (or a terminating hook) stops the
|
|
// round without waiting for a real final answer.
|
|
if batch.terminate {
|
|
res.Text = criticalToolLoopTerminalReason
|
|
res.StopReason = StopReasonToolLoopTerminated
|
|
l.saveCheckpoint(ctx, sessionID, step, msgs, StopReasonToolLoopTerminated)
|
|
l.extractMemory(ctx, msgs, step)
|
|
return res, nil
|
|
}
|
|
}
|
|
|
|
// Budget exhausted without a final answer.
|
|
res.Steps = l.maxRounds
|
|
res.StopReason = StopReasonMaxRounds
|
|
l.saveCheckpoint(ctx, sessionID, l.maxRounds, msgs, StopReasonMaxRounds)
|
|
l.extractMemory(ctx, msgs, l.maxRounds)
|
|
return res, nil
|
|
}
|