feat: 唤醒式架构批次——capacity/L4/会话编排/管理面板写CRUD/前端集成(77-81)
【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。
This commit is contained in:
1 parent
e0a543cc37
commit
6dbb4a2e18
51 files changed
+5395
-287
No files matched your search
@@ -0,0 +1,32 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/capacity"
|
||||
)
|
||||
|
||||
// capStateKey is the context key for the per-Run capacity-state accumulator.
|
||||
type capStateKey struct{}
|
||||
|
||||
// capStateAccum holds the mutable capacity state for one Run so the state
|
||||
// progresses across a multi-step tool loop (quiet→awake→full) without leaking
|
||||
// between concurrent runs. It lives on the context seeded at the top of Run.
|
||||
type capStateAccum struct {
|
||||
state capacity.State
|
||||
}
|
||||
|
||||
// withCapState returns a context carrying acc.
|
||||
func withCapState(ctx context.Context, acc *capStateAccum) context.Context {
|
||||
return context.WithValue(ctx, capStateKey{}, acc)
|
||||
}
|
||||
|
||||
// capState returns the accumulator on ctx, or a fresh quiet one when none is
|
||||
// seeded (a defensive fallback for a caller that invokes toolSchemas outside
|
||||
// Run, where the state is not meant to persist).
|
||||
func capState(ctx context.Context) *capStateAccum {
|
||||
if acc, ok := ctx.Value(capStateKey{}).(*capStateAccum); ok {
|
||||
return acc
|
||||
}
|
||||
return &capStateAccum{state: capacity.StateQuiet}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/capability/restrict"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/capacity"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/memory"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
)
|
||||
|
||||
// seedL4Habit writes a canonical intent record memory (the closed-loop write-back
|
||||
// format produced by capacity.RecordIntent) recording that "搞一下这个部署" is a task
|
||||
// for persona-a.
|
||||
func seedL4Habit(t *testing.T, store *memory.Store) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, err := store.Add(ctx, memory.MemoryItem{
|
||||
PersonaID: "persona-a",
|
||||
Scope: memory.ScopeUser,
|
||||
Kind: memory.KindRelationship,
|
||||
Content: "intent:isTask=true;taskKind=ops;confidence=0.85;text=搞一下这个部署",
|
||||
}); err != nil {
|
||||
t.Fatalf("seed L4 habit memory: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoop_Capacity_L4_WakesOnLearnedHabit_OwnerEnv proves the L4 feed: with a
|
||||
// retrieved user habit recording that the phrase is a task, an otherwise-undecided
|
||||
// turn wakes in the owner-full env, and the model is advertised the awake tool set.
|
||||
func TestLoop_Capacity_L4_WakesOnLearnedHabit_OwnerEnv(t *testing.T) {
|
||||
t.Parallel()
|
||||
store := newTestMemoryStore(t)
|
||||
seedL4Habit(t, store)
|
||||
td := capacityToolSet(t)
|
||||
ad := &mockAdapter{stream: []mgResp{{resp: model.Response{Content: "好的"}}}}
|
||||
a := newTestAgent(t, ad, td)
|
||||
dec := capacity.New(capacity.Config{Enabled: true, MinConfidence: 0.6})
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
MaxRounds: 8,
|
||||
OnStream: func(model.StreamEvent) {},
|
||||
Capacity: dec,
|
||||
Retriever: memory.NewRetriever(store),
|
||||
PersonaID: "persona-a",
|
||||
})
|
||||
ctx := WithSessionEnv(context.Background(), OwnerEnv())
|
||||
if _, err := l.Run(ctx, "sess", []model.Message{model.TextMessage(model.RoleUser, "搞一下那个部署")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(ad.streamReqs) == 0 {
|
||||
t.Fatal("no streaming request captured")
|
||||
}
|
||||
set := toolSet(ad.streamReqs[0].Tools)
|
||||
// L4 read the learned habit → awake → web-search is advertised (awake set).
|
||||
if !hasAll(set, "terminal", "file", "web-search") {
|
||||
t.Fatalf("owner L4 tools = %v, want awake set incl web-search", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoop_Capacity_L4_RestrictedEnv_NoOwnerHabitRead proves the L4 isolation red
|
||||
// line: in a group/stranger context the loop passes no recall, so the decider falls
|
||||
// back to L1/L2 and the owner's habit memory is never used to wake the intent.
|
||||
func TestLoop_Capacity_L4_RestrictedEnv_NoOwnerHabitRead(t *testing.T) {
|
||||
t.Parallel()
|
||||
store := newTestMemoryStore(t)
|
||||
seedL4Habit(t, store)
|
||||
td := capacityToolSet(t)
|
||||
ad := &mockAdapter{stream: []mgResp{{resp: model.Response{Content: "好的"}}}}
|
||||
a := newTestAgent(t, ad, td)
|
||||
dec := capacity.New(capacity.Config{Enabled: true, MinConfidence: 0.6})
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
MaxRounds: 8,
|
||||
OnStream: func(model.StreamEvent) {},
|
||||
Capacity: dec,
|
||||
Retriever: memory.NewRetriever(store),
|
||||
PersonaID: "persona-a",
|
||||
})
|
||||
ctx := WithSessionEnv(context.Background(), SessionEnv{ActorEnv: restrict.ActorGroupMember, MemWritable: false})
|
||||
if _, err := l.Run(ctx, "sess", []model.Message{model.TextMessage(model.RoleUser, "搞一下那个部署")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(ad.streamReqs) == 0 {
|
||||
t.Fatal("no streaming request captured")
|
||||
}
|
||||
set := toolSet(ad.streamReqs[0].Tools)
|
||||
// Restricted env → L4 silent → undecided turn stays quiet → only quiet tools, no
|
||||
// web-search, no owner habit read.
|
||||
if !hasAll(set, "terminal", "file") {
|
||||
t.Fatalf("restricted tools = %v, want quiet set terminal+file", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
if set["web-search"] {
|
||||
t.Fatalf("restricted tools = %v, must NOT wake (owner habit not read)", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"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/tool"
|
||||
)
|
||||
|
||||
// capacityToolSet builds a dispatcher over the four representative tools used to
|
||||
// verify the allowed-set filter: two quiet tools, one awake-only, and one that is
|
||||
// never allowed in quiet/awake.
|
||||
func capacityToolSet(t *testing.T) *tool.Dispatcher {
|
||||
t.Helper()
|
||||
return dispatcherWith(t,
|
||||
&mockTool{name: "terminal"},
|
||||
&mockTool{name: "file"},
|
||||
&mockTool{name: "web-search"},
|
||||
&mockTool{name: "json"},
|
||||
)
|
||||
}
|
||||
|
||||
// toolNames returns the set of tool names advertised in specs. The registry
|
||||
// List iterates a map, so registration order is not preserved; compare with a
|
||||
// set (via toolSet) rather than a slice for order-independent assertions.
|
||||
func toolNames(specs []model.ToolSpec) []string {
|
||||
out := make([]string, 0, len(specs))
|
||||
for _, s := range specs {
|
||||
out = append(out, s.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func toolSet(specs []model.ToolSpec) map[string]bool {
|
||||
set := make(map[string]bool, len(specs))
|
||||
for _, s := range specs {
|
||||
set[s.Name] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func hasAll(set map[string]bool, names ...string) bool {
|
||||
for _, n := range names {
|
||||
if !set[n] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// TestLoop_Capacity_QuietHidesHeavierTools verifies that with an enabled capacity
|
||||
// decider a chitchat turn advertises only the quiet allowed set to the model
|
||||
// (terminal + file, not web-search/json) on the streaming path.
|
||||
func TestLoop_Capacity_QuietHidesHeavierTools(t *testing.T) {
|
||||
t.Parallel()
|
||||
td := capacityToolSet(t)
|
||||
ad := &mockAdapter{stream: []mgResp{{resp: model.Response{Content: "陪你"}}}}
|
||||
a := newTestAgent(t, ad, td)
|
||||
dec := capacity.New(capacity.Config{Enabled: true, MinConfidence: 0.6})
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
MaxRounds: 8,
|
||||
OnStream: func(model.StreamEvent) {},
|
||||
Capacity: dec,
|
||||
})
|
||||
if _, err := l.Run(context.Background(), "sess", []model.Message{model.TextMessage(model.RoleUser, "你好呀,抱抱你")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(ad.streamReqs) == 0 {
|
||||
t.Fatal("no streaming request captured")
|
||||
}
|
||||
set := toolSet(ad.streamReqs[0].Tools)
|
||||
if !hasAll(set, "terminal", "file") {
|
||||
t.Fatalf("quiet tools = %v, want to include terminal+file", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
if set["web-search"] || set["json"] {
|
||||
t.Fatalf("quiet tools = %v, want to exclude web-search/json", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoop_Capacity_WakeExposesWebSearch verifies a task turn exposes the awake
|
||||
// allowed set (adds web-search) to the model.
|
||||
func TestLoop_Capacity_WakeExposesWebSearch(t *testing.T) {
|
||||
t.Parallel()
|
||||
td := capacityToolSet(t)
|
||||
ad := &mockAdapter{stream: []mgResp{{resp: model.Response{Content: "好的,这就查"}}}}
|
||||
a := newTestAgent(t, ad, td)
|
||||
dec := capacity.New(capacity.Config{Enabled: true, MinConfidence: 0.6})
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
MaxRounds: 8,
|
||||
OnStream: func(model.StreamEvent) {},
|
||||
Capacity: dec,
|
||||
})
|
||||
if _, err := l.Run(context.Background(), "sess", []model.Message{model.TextMessage(model.RoleUser, "帮我查一下最近的天气")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
set := toolSet(ad.streamReqs[0].Tools)
|
||||
if !hasAll(set, "terminal", "file", "web-search") {
|
||||
t.Fatalf("awake tools = %v, want to include terminal+file+web-search", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
if set["json"] {
|
||||
t.Fatalf("awake tools = %v, want to exclude json", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoop_Capacity_NilKeepsAllTools verifies the pre-existing behavior: without
|
||||
// a capacity decider every registered tool is advertised (no filtering).
|
||||
func TestLoop_Capacity_NilKeepsAllTools(t *testing.T) {
|
||||
t.Parallel()
|
||||
td := capacityToolSet(t)
|
||||
ad := &mockAdapter{stream: []mgResp{{resp: model.Response{Content: "你好"}}}}
|
||||
a := newTestAgent(t, ad, td)
|
||||
l := New(Options{Agent: a, MaxRounds: 8, OnStream: func(model.StreamEvent) {}})
|
||||
if _, err := l.Run(context.Background(), "sess", []model.Message{model.TextMessage(model.RoleUser, "你好")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
set := toolSet(ad.streamReqs[0].Tools)
|
||||
if !hasAll(set, "terminal", "file", "web-search", "json") {
|
||||
t.Fatalf("nil capacity tools = %v, want all four", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
if len(set) != 4 {
|
||||
t.Fatalf("nil capacity tools = %v, want exactly four", toolNames(ad.streamReqs[0].Tools))
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoop_Capacity_EmitsAwakenEvent verifies a state change surfaces a
|
||||
// capacity_awaken event through the OnCapacity hook on the streaming path.
|
||||
func TestLoop_Capacity_EmitsAwakenEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
td := capacityToolSet(t)
|
||||
ad := &mockAdapter{stream: []mgResp{{resp: model.Response{Content: "查到了"}}}}
|
||||
a := newTestAgent(t, ad, td)
|
||||
dec := capacity.New(capacity.Config{Enabled: true, MinConfidence: 0.6})
|
||||
var got []capacity.Event
|
||||
l := New(Options{
|
||||
Agent: a,
|
||||
MaxRounds: 8,
|
||||
OnStream: func(model.StreamEvent) {},
|
||||
Capacity: dec,
|
||||
OnCapacity: func(ev capacity.Event) { got = append(got, ev) },
|
||||
})
|
||||
if _, err := l.Run(context.Background(), "sess", []model.Message{model.TextMessage(model.RoleUser, "帮我查一下最近的天气")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("capacity events = %d, want 1 (got %+v)", len(got), got)
|
||||
}
|
||||
ev := got[0]
|
||||
if ev.Type != capacity.EventAwaken || ev.FromState != capacity.StateQuiet || ev.ToState != capacity.StateAwake {
|
||||
t.Fatalf("event = %+v, want quiet→awake awaken", ev)
|
||||
}
|
||||
if ev.Tool != "web-search" {
|
||||
t.Fatalf("lit tool = %q, want web-search", ev.Tool)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
||||
"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/guardrail"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/memory"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
@@ -81,6 +82,8 @@ type Result struct {
|
||||
type Loop struct {
|
||||
agent *agent.Agent
|
||||
tools *tool.Dispatcher
|
||||
capacity *capacity.Decider
|
||||
onCapacity func(capacity.Event)
|
||||
memory *memory.Store
|
||||
retriever *memory.Retriever
|
||||
working *memory.WorkingMemory
|
||||
@@ -126,6 +129,8 @@ func New(opts Options) *Loop {
|
||||
return &Loop{
|
||||
agent: opts.Agent,
|
||||
tools: opts.Tools,
|
||||
capacity: opts.Capacity,
|
||||
onCapacity: opts.OnCapacity,
|
||||
memory: opts.Memory,
|
||||
retriever: opts.Retriever,
|
||||
working: opts.WorkingMemory,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"log/slog"
|
||||
|
||||
"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/guardrail"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/memory"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
@@ -26,6 +27,17 @@ type Options struct {
|
||||
// Tools is the tool dispatcher used to execute model-requested calls. When
|
||||
// nil the loop falls back to the agent's own dispatcher (if any).
|
||||
Tools *tool.Dispatcher
|
||||
// Capacity, when non-nil and enabled, filters the tool schemas advertised to
|
||||
// the model each round to the allowed set for the current capacity state
|
||||
// (design/14 唤醒式能力渐进 §4): the loop only exposes the allowed set to the
|
||||
// model — a view, not a hard boundary (Invoke is left unblocked so an
|
||||
// emergency call still works). Nil (the default) keeps the pre-existing
|
||||
// behavior: every registered tool is advertised.
|
||||
Capacity *capacity.Decider
|
||||
// OnCapacity, when non-nil, receives capacity_awaken transition events the
|
||||
// loop observes while deciding a round (design/14 §4), so a caller can
|
||||
// surface the "能力点亮" progression to the frontend. Nil = no-op.
|
||||
OnCapacity func(capacity.Event)
|
||||
// Memory is the long-term memory store used to persist extracted items.
|
||||
Memory *memory.Store
|
||||
// Retriever injects relevant memories into the context, re-evaluated every
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"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/tool"
|
||||
)
|
||||
@@ -9,14 +12,14 @@ import (
|
||||
// buildRequest assembles a model.Request from the agent's public surface,
|
||||
// mirroring agent.buildRequest so the streaming path behaves identically to
|
||||
// RunStep (leading instruction message, tool schemas, model routing).
|
||||
func (l *Loop) buildRequest(messages []model.Message) model.Request {
|
||||
func (l *Loop) buildRequest(ctx context.Context, messages []model.Message) model.Request {
|
||||
req := model.Request{
|
||||
Model: l.agent.Model(),
|
||||
Messages: l.assembleMessages(messages),
|
||||
Temperature: l.temperature(),
|
||||
MaxTokens: l.agent.MaxTokens(),
|
||||
Purpose: l.agent.Purpose(),
|
||||
Tools: l.toolSchemas(),
|
||||
Tools: l.toolSchemas(ctx, messages),
|
||||
}
|
||||
if l.agent.Router() != nil {
|
||||
if m, _ := l.agent.Router().RouteRequest(req); m != "" {
|
||||
@@ -50,13 +53,107 @@ func (l *Loop) temperature() *float64 {
|
||||
}
|
||||
|
||||
// toolSchemas advertises the registered tool schemas to the model, or nil when no
|
||||
// dispatcher is configured.
|
||||
func (l *Loop) toolSchemas() []model.ToolSpec {
|
||||
// dispatcher is configured. When a capacity decider is wired and enabled, it
|
||||
// classifies the current round and returns only the allowed set for that state
|
||||
// (a view over the dispatcher, per design/14 §4): the model sees/invokes only
|
||||
// the allowed tools, while Invoke itself stays unblocked. A nil or disabled
|
||||
// decider keeps the pre-existing behavior (every tool advertised).
|
||||
func (l *Loop) toolSchemas(ctx context.Context, messages []model.Message) []model.ToolSpec {
|
||||
d := l.dispatcher()
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return d.ToolSchemas()
|
||||
schemas := d.ToolSchemas()
|
||||
if l.capacity == nil || !l.capacity.Enabled() {
|
||||
return schemas
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(schemas))
|
||||
for _, s := range schemas {
|
||||
names = append(names, s.Name)
|
||||
}
|
||||
acc := capState(ctx)
|
||||
dec := l.capacity.Decide(ctx, capacity.Input{
|
||||
Messages: capacityTexts(messages),
|
||||
CurrentState: acc.state,
|
||||
AllToolNames: names,
|
||||
Recall: l.capacityRecall(ctx, messages),
|
||||
})
|
||||
acc.state = dec.State
|
||||
if l.onCapacity != nil {
|
||||
for _, ev := range dec.Events {
|
||||
l.onCapacity(ev)
|
||||
}
|
||||
}
|
||||
|
||||
allowed := make(map[string]bool, len(dec.AllowedTools))
|
||||
for _, n := range dec.AllowedTools {
|
||||
allowed[n] = true
|
||||
}
|
||||
out := make([]model.ToolSpec, 0, len(dec.AllowedTools))
|
||||
for _, s := range schemas {
|
||||
if allowed[s.Name] {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// capacityTexts extracts the recent conversation text for the capacity decider:
|
||||
// the last few non-system/non-tool turns, in chronological order (oldest first),
|
||||
// so the decider's current-turn window sees the latest user message last.
|
||||
func capacityTexts(messages []model.Message) []string {
|
||||
texts := make([]string, 0, 6)
|
||||
for i := len(messages) - 1; i >= 0 && len(texts) < 6; i-- {
|
||||
m := messages[i]
|
||||
if m.Role == model.RoleSystem || m.Role == model.RoleTool {
|
||||
continue
|
||||
}
|
||||
if t := messageText(m); t != "" {
|
||||
texts = append(texts, t)
|
||||
}
|
||||
}
|
||||
for i, j := 0, len(texts)-1; i < j; i, j = i+1, j-1 {
|
||||
texts[i], texts[j] = texts[j], texts[i]
|
||||
}
|
||||
return texts
|
||||
}
|
||||
|
||||
// capacityRecallTopK bounds how many recalled habit memories the capacity L4 layer
|
||||
// considers per round.
|
||||
const capacityRecallTopK = 5
|
||||
|
||||
// capacityRecall retrieves the owner's relevant long-term memories for the capacity
|
||||
// L4 habit-alignment layer (design §2.2 L4), the memory feed that lets the decider
|
||||
// learn the user's task-expression habits. It returns nil (keeping L4 silent) when
|
||||
// no retriever/persona is configured — backward compatible — or in a restricted
|
||||
// (group chat / stranger) context, per the isolation red line: L4 learns the owner's
|
||||
// habits and must never read owner-sensitive memory into a group or stranger intent
|
||||
// decision (design §2.2 红线: 不读陌生人敏感).
|
||||
func (l *Loop) capacityRecall(ctx context.Context, messages []model.Message) []capacity.RecallItem {
|
||||
if l.retriever == nil || l.personaID == "" {
|
||||
return nil
|
||||
}
|
||||
env := sessionEnvFrom(ctx)
|
||||
if env.Restricted() {
|
||||
return nil
|
||||
}
|
||||
results, err := l.retriever.Retrieve(ctx, l.personaID, queryFromMessages(messages), capacityRecallTopK)
|
||||
if err != nil {
|
||||
l.log.Warn("capacity recall", "error", err, "env", env.ActorEnv)
|
||||
return nil
|
||||
}
|
||||
items := make([]capacity.RecallItem, 0, len(results))
|
||||
for _, r := range results {
|
||||
items = append(items, capacity.RecallItem{
|
||||
Content: r.Item.Content,
|
||||
Scope: string(r.Item.Scope),
|
||||
Kind: string(r.Item.Kind),
|
||||
Tags: r.Item.Tags,
|
||||
Score: r.Score,
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// decodeToolCalls decodes tool calls from a model.Response using the same two
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"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"
|
||||
)
|
||||
@@ -31,6 +32,11 @@ func (l *Loop) Run(ctx context.Context, sessionID string, messages []model.Messa
|
||||
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{}
|
||||
|
||||
@@ -19,7 +19,7 @@ func (l *Loop) streamStep(ctx context.Context, messages []model.Message) (*stepO
|
||||
if adapter == nil {
|
||||
return nil, fmt.Errorf("loop: stream step: %w", ErrNoAdapter)
|
||||
}
|
||||
req := l.buildRequest(messages)
|
||||
req := l.buildRequest(ctx, messages)
|
||||
|
||||
if l.guards != nil {
|
||||
verdict, err := l.guards.CheckInput(ctx, &req)
|
||||
|
||||
Reference in new issue
Block a user