Files
Cyrene_v2/internal/runtime/loop/run.go
T
AskaEth 153a9d6211
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat(runtime+admin): A2 LLM异步提取接线 + A4 Tracing接线 + A6通知后端聚合
A2 异步记忆提取:
- loop/memory.go: asyncExtractor接口(ExtractAsync)+extractMemoryAsync(60s超时,WithOutCancel,dispatch即返回,后台落库,失败仅Warn)+persistMemories共用
- run.go 三个回合落定点改异步提取; 删除run.go逐步提取(design/03'每轮后', 避免多轮工具N次LLM调用/重复写)
- cmd/cyrene/extractor.go buildMemoryExtractor: llmGroupUsable为真→LLMExtractor, 否则回落ManualExtractor(日志说明); keylessEndpoint放行loopback/私网

A4 可观测性 Tracing:
- cmd/cyrene/observability.go: newAppTraceWriter+traceFanout(多sink)+gatewaySpanSink(走gw.ObserveSpan,喂环形缓冲+LLM/subagent指标)
- wire.go 注入; 未改trace/gateway数据结构

A6 通知后端:
- internal/services/gateway/notifications.go(311行): GET /admin/notifications?type=&before=&limit= (adminAuth)
- 聚合已有源(obs.audit SQLite + s.backthink), createdAt倒序, id=source:id; 类型派生(channel/system/audit/backthink); 无新建表/无新Deps/wire零改动
- 诚实: backthink仅shouldPush计, 未注入源为空, 报错500, 未读游标后置
- 契约与前端Y一致: {id,type,title,body,source,createdAt}, before含游标(<=), type未知400
- Docs/api-client v0.33

全仓 build/vet/test绿(56包)+win/darwin/linux-arm64交叉编译绿; 新增测试(memory_async/extractor/observability/notifications)
2026-09-30 09:03:16 +08:00

122 lines
5.1 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 when the turn settles the memory Extractor runs over the
// turn's conversation (design/03 §1: the LLM extractor on a background
// goroutine, so extraction never delays the reply) with errors logged rather
// than fatal.
//
// When a turn settles with a Result, the OnTurnEnd hook is called once for that
// turn (never per step) and its mood label is recorded on Result.Mood, so the
// layers around the loop can advance persona state and tag the persisted reply.
//
// 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{}
if l.flow != nil {
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)
}
// 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.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)
// 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.extractMemoryAsync(ctx, msgs, step)
l.settleTurn(ctx, sessionID, msgs, res)
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.extractMemoryAsync(ctx, msgs, l.maxRounds)
l.settleTurn(ctx, sessionID, msgs, res)
return res, nil
}