【capacity 唤醒式核心(77)】internal/runtime/capacity:(Decider L1启发式+L2上下文+人格覆盖→三态静息/唤醒/全能→允许工具集+capacity_awaken事件)。loop 外围允许集过滤(不硬阻断=能力≠边界红线)。config 加 Capacity(Enabled/MinConfidence/ToolSets)。wire buildCapacity 接入 loop。 【L4 记忆驱动意图(80)】recall.go:从记忆召回用户习惯(搞一下xx=办事)→唤醒L1/L2漏掉/升置信;群聊陌生人不读owner习惯(隔离红线);RecordIntent闭环(判定写回记忆越用越准);默认保守静息。 【会话消息编排(78)】gateway/session_orchestrator.go:每会话(模式/pending有界5/tail上下文尾巴20);Submit非阻塞(idle立即/busy入队ack/满拒绝);完成回调按序续接(tail+新消息合并增量注入非全量重放);Interrupt中断;REST 202/409+WS session_busy/pending_ack事件;不重造任务引擎复用loop。 【前端集成(79)】ws.ts 加 capacity_awaken/session_busy/pending_ack 解析;store 加 awakenState/sessionBusy;TopBar/ChatShell 加唤醒态徽标+忙态提示(不阻塞输入框);状态组件 status.tsx;Miuix风格。 【管理面板写CRUD(81)】20个写端点(POST/PUT/DELETE /admin/*,owner+审计落库):personas(真持久化YAML)/users apikey(签发掩码+撤销)/iot控制(真下发)/automations(建/触发/删)/llm(test真调用+临时)/channels(connect/close/身份测试actor白名单)/plugins(卸载)/memories(search真检索)/sessions(export)。无存储如实501不伪造。拆4文件满足≤500红线。前端9模块接真写。 【wire收口】buildCapacity接入loop+OnCapacity事件;server.go newOrchestrator接hub。 实机验证:iot ac.living control 200 真实改变 on:true;observability/metrics 200、health ok;全仓 build/vet/test 47包绿+前端tsc/vite。
101 lines
3.9 KiB
Go
101 lines
3.9 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.
|
|
ctx = withCapState(ctx, &capStateAccum{state: capacity.StateQuiet})
|
|
|
|
msgs := l.resolveImages(ctx, messages)
|
|
toolState := &toolLoopState{prevFP: make(map[string]bool)}
|
|
res := &Result{}
|
|
for step := 1; 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
|
|
}
|