From b792a94b844b406b7e93a9d96799e158d253617d Mon Sep 17 00:00:00 2001 From: JianFeeeee Date: Mon, 14 Sep 2026 23:14:38 +0800 Subject: [PATCH] =?UTF-8?q?feat(memory):=20=E6=96=B0=E5=A2=9E=E5=8F=AF?= =?UTF-8?q?=E5=A3=B0=E6=98=8E=E7=9A=84=E5=8F=AC=E5=9B=9E=E8=BD=B4=20Recall?= =?UTF-8?q?Policy=EF=BC=88=E4=B8=8E=20prune=20=E6=AD=A3=E4=BA=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题:召回(把 L2/L3 相关记忆注入本轮)此前不可声明、也不受任何 SDK 字段 控制——它只在任务开始时对 f.Input 无条件跑一次。于是 qq_get_message 取回 真实正文后只触发 Prune(裁剪),从不触发召回;而中断通知的 meta 文本反而 会去召回(词不对题,命中一堆泛实体)。 改动: - SDK 新增 RecallPolicy(none|auto) 轴,落在 InjectOptions / ChannelDef / ToolDef 三个声明面,与 ContextPolicy 正交(裁剪 vs 召回)。默认值与 prune 刻意相反:输入/注入默认 auto(保持既有「每条输入都召回」), 工具默认 none(工具输出多为噪声,按需声明)。 - 内核:recallDeclared 按 注入点 > 通道 > 默认auto 解析;输入侧用它决定 是否注入记忆索引;工具侧 ContextPolicy/RecallPolicy 共用同一份清洗后 query,一次相关性过程分别 prune / recall;召回以 system 消息挂到消息 末尾(同任务内替换而非累加)。 - 管线:proc RPC(inject/register + 校验)、lua 键、io payload 全量透传。 - QQ 插件:中断与 qq 通道声明 RecallPolicy=none(meta 不是内容); qq_get_message 声明 RecallPolicy=auto(取回正文后据正文召回)。 测试:新增 recallpolicy_test.go(core)与 proc 校验用例; go build ./... 通过,go test ./internal/... 全通过,SDK 模块与 qq 插件测试通过。 --- internal/agent/core/eventloop.go | 23 +++ internal/agent/core/inputch.go | 3 + internal/agent/core/process.go | 23 +++ internal/agent/core/recallpolicy_test.go | 141 ++++++++++++++++++ internal/agent/core/task.go | 37 +++-- internal/agent/core/tooldefs.go | 33 ++++ internal/agent/io/channel.go | 3 + internal/agent/io/injectopts_test.go | 9 +- internal/plugin/lua_plugin.go | 8 +- internal/plugin/proc/corehandler.go | 20 ++- internal/plugin/proc/corehandler_inject.go | 35 ++++- internal/plugin/proc/corehandler_register.go | 3 + internal/plugin/proc/priority_clamp_test.go | 6 +- internal/plugin/proc/recallpolicy_test.go | 31 ++++ internal/sdk/plugin.go | 6 + .../homeagent-sdk/example/qq/plugin.go | 11 +- third_party/homeagent-sdk/sdk/plugin.go | 34 ++++- 17 files changed, 396 insertions(+), 30 deletions(-) create mode 100644 internal/agent/core/recallpolicy_test.go create mode 100644 internal/plugin/proc/recallpolicy_test.go diff --git a/internal/agent/core/eventloop.go b/internal/agent/core/eventloop.go index 48cbbda..9e8575f 100644 --- a/internal/agent/core/eventloop.go +++ b/internal/agent/core/eventloop.go @@ -405,6 +405,29 @@ func (a *Agent) pruneDeclared(evt *agentIO.InputEvent) bool { return false } +// recallDeclared 判定这次输入是否要触发记忆召回(注入)。 +// +// 与 pruneDeclared **正交**:prune 管“踢出去”(归档低相关 L0 事件), +// recall 管“取进来”(把 L2/L3 相关记忆注入本轮)。 +// +// 默认值与 prune 刻意相反:召回是只读增量、日常对话本就需要,所以**默认 auto**; +// 只有显式声明 recall_policy=none(如中断通知的 meta 文本)才关闭。 +// 优先级同 prune:注入点(payload)> 通道(ChannelDef)> 默认 auto。 +func (a *Agent) recallDeclared(evt *agentIO.InputEvent) bool { + if evt == nil { + return true + } + if p, ok := evt.Payload["recall_policy"].(string); ok && p != "" { + return p != pubsdk.RecallPolicyNone + } + if a.io != nil { + if chDef, ok := a.io.GetInputChannelDef(evt.Source); ok && chDef.RecallPolicy != "" { + return chDef.RecallPolicy != pubsdk.RecallPolicyNone + } + } + return true +} + // cleanInputFor 解析这条输入在计算层应当使用的清洗文本。 // // 优先级:注入点声明的 cleaner(payload.cleaner_name,引用某个已注册的通道 diff --git a/internal/agent/core/inputch.go b/internal/agent/core/inputch.go index dcfbccf..04292a8 100644 --- a/internal/agent/core/inputch.go +++ b/internal/agent/core/inputch.go @@ -139,6 +139,9 @@ func policySuffix(ch agentIO.InputChannel) string { if ch.Def.ContextPolicy != "" && ch.Def.ContextPolicy != "none" { m = append(m, "裁剪:"+ch.Def.ContextPolicy) } + if ch.Def.RecallPolicy != "" && ch.Def.RecallPolicy != "auto" { + m = append(m, "召回:"+ch.Def.RecallPolicy) + } if len(m) == 0 { return "" } diff --git a/internal/agent/core/process.go b/internal/agent/core/process.go index b78f929..fe6d22b 100644 --- a/internal/agent/core/process.go +++ b/internal/agent/core/process.go @@ -81,6 +81,29 @@ func (a *Agent) toolOutputForQuery(toolName, raw string) string { return raw } +// recallMsgMarker 是工具触发召回时注入的 system 消息前缀。 +// 用它做去重与替换的识别标(与用户/中断的 system 消息区分开)。 +const recallMsgMarker = "【记忆召回】" + +// appendOrReplaceRecall 把一段召回文本作为 system 消息挂到消息末尾。 +// +// 同一任务内多次触发(如模型多次调用 qq_get_message)时**替换**上一条召回, +// 而不是累加:否则召回会线性叠进 prompt,把上下文与 token 预算越挤越紧。 +// 替换位置固定在末尾,不影响 tool/assistant 消息的配对。 +func appendOrReplaceRecall(msgs []agentAPI.Message, recallText string) []agentAPI.Message { + if recallText == "" { + return msgs + } + full := recallMsgMarker + "\n" + recallText + for i := len(msgs) - 1; i >= 0; i-- { + if msgs[i].Role == "system" && strings.HasPrefix(msgs[i].Content, recallMsgMarker) { + msgs[i].Content = full + return msgs + } + } + return append(msgs, agentAPI.Message{Role: "system", Content: full}) +} + // dropContinuationPlaceholders 移除此前由本机制插入的 user 占位。 // // 为什么必须移除而不仅仅是“不再追加”:`msgs` 在循环外创建、循环内只增不减, diff --git a/internal/agent/core/recallpolicy_test.go b/internal/agent/core/recallpolicy_test.go new file mode 100644 index 0000000..43a52f0 --- /dev/null +++ b/internal/agent/core/recallpolicy_test.go @@ -0,0 +1,141 @@ +package core + +import ( + "path/filepath" + "strings" + "testing" + + agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api" + agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io" + "gitcode.com/JianFeeeee/HomeAgent/internal/memory" + pubsdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk" +) + +// 这一组测试锁死「默认召回、可显式关闭」这条语义。 +// +// 与 prune 刻意相反:裁剪是破坏性的、默认关;召回是只读增量、默认开。 +// 两者正交,一根 ContextPolicy 表达不了 2×2 的组合(只召回不裁剪 / 只裁不召回)。 +func TestRecallDeclared_DefaultsToRecall(t *testing.T) { + m := agentIO.NewIOManager() + a := &Agent{io: m} + + // 没有任何声明 → 默认召回(保持既有"每条输入都召回"的行为)。 + if !a.recallDeclared(&agentIO.InputEvent{Source: "unknown", Payload: map[string]interface{}{}}) { + t.Fatal("未声明的输入默认必须召回") + } + // 通道注册了但没设 RecallPolicy → 仍默认召回。 + m.RegisterInputChannel("plain", pubsdk.ChannelDef{}) + if !a.recallDeclared(&agentIO.InputEvent{Source: "plain", Payload: map[string]interface{}{}}) { + t.Fatal("ChannelDef 未设 RecallPolicy 应默认召回") + } + // nil 事件不能 panic,且按默认召回。 + if !a.recallDeclared(nil) { + t.Fatal("nil 事件应默认召回") + } +} + +func TestRecallDeclared_ChannelOptOut(t *testing.T) { + m := agentIO.NewIOManager() + m.RegisterInputChannel("meta", pubsdk.ChannelDef{RecallPolicy: pubsdk.RecallPolicyNone}) + m.RegisterInputChannel("talk", pubsdk.ChannelDef{RecallPolicy: pubsdk.RecallPolicyAuto}) + a := &Agent{io: m} + + if a.recallDeclared(&agentIO.InputEvent{Source: "meta", Payload: map[string]interface{}{}}) { + t.Fatal("通道声明 none 不应召回") + } + if !a.recallDeclared(&agentIO.InputEvent{Source: "talk", Payload: map[string]interface{}{}}) { + t.Fatal("通道声明 auto 应召回") + } +} + +// 注入点声明优先于通道定义:同一通道下的不同注入可以有不同意图。 +func TestRecallDeclared_InjectionOverridesChannel(t *testing.T) { + m := agentIO.NewIOManager() + a := &Agent{io: m} + m.RegisterInputChannel("qq", pubsdk.ChannelDef{RecallPolicy: pubsdk.RecallPolicyNone}) + + evt := &agentIO.InputEvent{Source: "qq", Payload: map[string]interface{}{ + "recall_policy": pubsdk.RecallPolicyAuto, + }} + if !a.recallDeclared(evt) { + t.Fatal("注入点声明 auto 应覆盖通道的 none") + } + + m.RegisterInputChannel("plain", pubsdk.ChannelDef{RecallPolicy: pubsdk.RecallPolicyAuto}) + evt = &agentIO.InputEvent{Source: "plain", Payload: map[string]interface{}{ + "recall_policy": pubsdk.RecallPolicyNone, + }} + if a.recallDeclared(evt) { + t.Fatal("注入点声明 none 应覆盖通道的 auto") + } +} + +// buildTaskMemoryContext 在声明 none 时必须返回空串(不注入记忆索引)。 +func TestBuildTaskMemoryContext_RespectsPolicy(t *testing.T) { + m := agentIO.NewIOManager() + m.RegisterInputChannel("meta", pubsdk.ChannelDef{RecallPolicy: pubsdk.RecallPolicyNone}) + a := &Agent{io: m, indexer: newTestIndexer(t, "咖啡", "张三")} + + f := &TaskFrame{Evt: &agentIO.InputEvent{Source: "meta", Payload: map[string]interface{}{}}} + if got := a.buildTaskMemoryContext(f, "咖啡", 0); got != "" { + t.Fatalf("声明 none 时不应注入记忆,实际 %q", got) + } + + f2 := &TaskFrame{Evt: &agentIO.InputEvent{Source: "plain", Payload: map[string]interface{}{}}} + if got := a.buildTaskMemoryContext(f2, "咖啡", 0); !strings.Contains(got, "【记忆索引】") { + t.Fatalf("默认应注入记忆索引,实际 %q", got) + } +} + +// 工具触发的召回:以(清洗后的)工具输出为 query,产出可注入的记忆文本。 +func TestRecallTextFor_UsesQuery(t *testing.T) { + a := &Agent{indexer: newTestIndexer(t, "咖啡", "张三")} + got := a.recallTextFor("咖啡", "tool:test") + if !strings.Contains(got, "【记忆索引】") { + t.Fatalf("应产出记忆索引文本,实际 %q", got) + } + // 空 query 或无 indexer 时不产出、不 panic。 + if got := a.recallTextFor("", "tool:test"); got != "" { + t.Fatalf("空 query 应返回空串,实际 %q", got) + } + if got := (&Agent{}).recallTextFor("咖啡", "tool:test"); got != "" { + t.Fatalf("无 indexer 应返回空串,实际 %q", got) + } +} + +// 召回文本以 system 消息挂在末尾;同一任务内多次触发是**替换**而非累加。 +func TestAppendOrReplaceRecall(t *testing.T) { + msgs := []agentAPI.Message{{Role: "user", Content: "hi"}} + msgs = appendOrReplaceRecall(msgs, "第一段") + if len(msgs) != 2 || msgs[1].Role != "system" || !strings.Contains(msgs[1].Content, "第一段") { + t.Fatalf("首次应追加一条 system 召回消息,实际 %+v", msgs) + } + msgs = appendOrReplaceRecall(msgs, "第二段") + if len(msgs) != 2 { + t.Fatalf("再次触发应替换而非累加,实际 %d 条", len(msgs)) + } + if !strings.Contains(msgs[1].Content, "第二段") || strings.Contains(msgs[1].Content, "第一段") { + t.Fatalf("替换后应只含最新召回,实际 %q", msgs[1].Content) + } + if msgs = appendOrReplaceRecall(msgs, ""); len(msgs) != 2 { + t.Fatalf("空召回不应改变消息,实际 %d 条", len(msgs)) + } +} + +// newTestIndexer 造一个只含给定实体的图记忆 + 已同步的索引器。 +func newTestIndexer(t *testing.T, subject, object string) *memory.Indexer { + t.Helper() + db, err := memory.NewGraphDB(filepath.Join(t.TempDir(), "graph.db")) + if err != nil { + t.Fatalf("NewGraphDB: %v", err) + } + t.Cleanup(func() { db.Close() }) + if _, _, err := db.Commit([]memory.Triple{{Subject: subject, Relation: "喜欢", Object: object}}, "s", 0); err != nil { + t.Fatalf("Commit: %v", err) + } + idx := memory.NewIndexer(db) + if err := idx.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + return idx +} diff --git a/internal/agent/core/task.go b/internal/agent/core/task.go index 0faad80..7f1bdd1 100644 --- a/internal/agent/core/task.go +++ b/internal/agent/core/task.go @@ -275,7 +275,7 @@ func (a *Agent) rebaseFramePrefix(f *TaskFrame) { tail := append([]agentAPI.Message(nil), f.Msgs[f.PrefixLen:]...) budget := ComputeTokenBudget(a.provider, a.systemPrompt) - memContext := a.buildMemoryContext(f.Input, budget.MemoryTokens) + memContext := a.buildTaskMemoryContext(f, f.Input, budget.MemoryTokens) sysPrompt := a.buildSystemPrompt(memContext, f.Input) prefix := a.buildMessages(sysPrompt, f.Input, a.contextTokenBudget(budget)) @@ -497,7 +497,7 @@ func (a *Agent) step(f *TaskFrame) stepOutcome { func (a *Agent) stepPrepare(f *TaskFrame) stepOutcome { budget := ComputeTokenBudget(a.provider, a.systemPrompt) - memContext := a.buildMemoryContext(f.Input, budget.MemoryTokens) + memContext := a.buildTaskMemoryContext(f, f.Input, budget.MemoryTokens) sysPrompt := a.buildSystemPrompt(memContext, f.Input) f.Tools = a.buildToolDefs() @@ -743,16 +743,27 @@ func (a *Agent) stepToolAfter(f *TaskFrame) stepOutcome { result = r } } - // ContextPolicy: prune 工具调用后执行上下文裁剪(§13.8) - if def := a.stageHost.ToolDef(tc.Name); def != nil && def.ContextPolicy == "prune" { - if a.context != nil { - topK := a.maxContextSize - 1 - if topK < 1 { - topK = 1 + // 工具后处理:一次相关性过程,两个**正交**声明—— + // ContextPolicy=prune → 裁剪(踢出去,归档低相关 L0 事件) + // RecallPolicy=auto → 召回(取进来,注入 L2/L3 相关记忆) + // 两者共用同一份**清洗后**的 query:查询向量取清洗后的有效内容,否则噪声 + // (ANSI/base64/JSON 包装)会把相关性打分带偏,裁错事件、召回错记忆。 + var recallText string + if def := a.stageHost.ToolDef(tc.Name); def != nil { + needPrune := def.ContextPolicy == sdk.ContextPolicyPrune + needRecall := def.RecallPolicy == sdk.RecallPolicyAuto + if needPrune || needRecall { + query := a.toolOutputForQuery(tc.Name, result) + if needPrune && a.context != nil { + topK := a.maxContextSize - 1 + if topK < 1 { + topK = 1 + } + a.context.Prune(query, topK, a.docStore) + } + if needRecall { + recallText = a.recallTextFor(query, "tool:"+tc.Name) } - // 查询向量取**清洗后**的有效内容,否则噪声(ANSI/base64/JSON 包装) - // 会把相关性打分带偏,裁掉本该保留的事件。 - a.context.Prune(a.toolOutputForQuery(tc.Name, result), topK, a.docStore) } } @@ -822,6 +833,10 @@ func (a *Agent) stepToolAfter(f *TaskFrame) stepOutcome { // 必须紧跟在 toolMsg 之后:中间插入其他消息会让 tool_call_id 配对断开。 f.Msgs = append(f.Msgs, *mediaMsg) } + // 召回作为 system 消息挂在末尾(tool/assistant 配对已完成,插入此处不断链)。 + if recallText != "" { + f.Msgs = appendOrReplaceRecall(f.Msgs, recallText) + } a.publishEvent(events.EventToolCall, map[string]interface{}{ "tool": tc.Name, diff --git a/internal/agent/core/tooldefs.go b/internal/agent/core/tooldefs.go index cc7ab28..4118294 100644 --- a/internal/agent/core/tooldefs.go +++ b/internal/agent/core/tooldefs.go @@ -2,6 +2,7 @@ package core import ( "fmt" + "log" "strings" agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io" @@ -39,6 +40,38 @@ func (a *Agent) buildMemoryContext(input string, maxTokens int) string { return s } +// buildTaskMemoryContext 按本任务声明的召回策略决定是否注入记忆索引。 +// +// 默认 auto(保持“每条输入都召回”的既有行为);输入/注入声明 +// recall_policy=none 时返回空串,从而不注入记忆。策略与裁剪(ContextPolicy)正交。 +func (a *Agent) buildTaskMemoryContext(f *TaskFrame, input string, maxTokens int) string { + if f != nil && !a.recallDeclared(f.Evt) { + return "" + } + return a.buildMemoryContext(input, maxTokens) +} + +// recallTextFor 以 query 触发一次记忆召回,返回可注入的文本(空串表示无)。 +// +// 这是“召回”侧的单一入口:与 Prune 共用同一份**清洗后**的 query, +// 使“取进来”(召回)与“踢出去”(裁剪)落在同一个相关性过程上。 +// trigger 仅用于日志溯源(如 "tool:qq_get_message")。 +func (a *Agent) recallTextFor(query, trigger string) string { + if query == "" || a.indexer == nil { + return "" + } + memTokens := 0 // 0 = 不截断 + if a.provider != nil { + memTokens = ComputeTokenBudget(a.provider, a.systemPrompt).MemoryTokens + } + text := a.buildMemoryContext(query, memTokens) + if text == "" { + return "" + } + log.Printf("[agent] memory recall (%s): injected %d chars", trigger, len(text)) + return text +} + // expandPromptVars 展开自定义提示词(人格卡)里的版本占位符。 // // 为什么需要:人格卡是**配置项**,一旦写死版本号就会随内核发版而说谎 —— diff --git a/internal/agent/io/channel.go b/internal/agent/io/channel.go index d48417b..e132f47 100644 --- a/internal/agent/io/channel.go +++ b/internal/agent/io/channel.go @@ -352,6 +352,9 @@ func applyInjectOpts(payload map[string]interface{}, opts InjectOptions) { if opts.ContextPolicy != "" { payload["context_policy"] = opts.ContextPolicy } + if opts.RecallPolicy != "" { + payload["recall_policy"] = opts.RecallPolicy + } if opts.CleanerName != "" { payload["cleaner_name"] = opts.CleanerName } diff --git a/internal/agent/io/injectopts_test.go b/internal/agent/io/injectopts_test.go index 3c234f8..25c1075 100644 --- a/internal/agent/io/injectopts_test.go +++ b/internal/agent/io/injectopts_test.go @@ -47,6 +47,7 @@ func TestInjectTextOpts_CarriesFlags(t *testing.T) { m.InjectTextOpts("src", "chan", "hello", InjectOptions{ NoMemory: true, ContextPolicy: "prune", + RecallPolicy: "none", CleanerName: "clean_me", }) evt := drainOne(t, m.InputChan()) @@ -57,6 +58,9 @@ func TestInjectTextOpts_CarriesFlags(t *testing.T) { if evt.Payload["context_policy"] != "prune" { t.Errorf("context_policy 未传递: %v", evt.Payload["context_policy"]) } + if evt.Payload["recall_policy"] != "none" { + t.Errorf("recall_policy 未传递: %v", evt.Payload["recall_policy"]) + } if evt.Payload["cleaner_name"] != "clean_me" { t.Errorf("cleaner_name 未传递: %v", evt.Payload["cleaner_name"]) } @@ -71,12 +75,15 @@ func TestInjectTextOpts_CarriesFlags(t *testing.T) { // 中断注入走另一条队列,标志位同样要带上(用户已确认中断允许声明 prune)。 func TestInjectInterruptTextOpts_CarriesFlags(t *testing.T) { m := NewIOManager() - m.InjectInterruptTextOpts("src", "chan", "alert", InjectOptions{ContextPolicy: "prune"}) + m.InjectInterruptTextOpts("src", "chan", "alert", InjectOptions{ContextPolicy: "prune", RecallPolicy: "none"}) evt := drainOne(t, m.InputInterruptChan()) if evt.Payload["context_policy"] != "prune" { t.Errorf("中断注入的 context_policy 未传递: %v", evt.Payload) } + if evt.Payload["recall_policy"] != "none" { + t.Errorf("中断注入的 recall_policy 未传递: %v", evt.Payload) + } if evt.Payload["type"] != "text" || evt.Payload["content"] != "alert" { t.Errorf("中断注入的基本字段不对: %v", evt.Payload) } diff --git a/internal/plugin/lua_plugin.go b/internal/plugin/lua_plugin.go index 7a2100d..ed43708 100644 --- a/internal/plugin/lua_plugin.go +++ b/internal/plugin/lua_plugin.go @@ -1058,6 +1058,7 @@ func parseToolDef(L *lua.LState, defTbl *lua.LTable, plg *luaPlugin, name string goDef.NoMemory = lua.LVAsBool(v) } goDef.ContextPolicy = defTbl.RawGetString("context_policy").String() + goDef.RecallPolicy = defTbl.RawGetString("recall_policy").String() if v := defTbl.RawGetString("cleaner"); v != nil && v.Type() == lua.LTFunction { goDef.Cleaner = makeLuaCleaner(plg, v.(*lua.LFunction)) } @@ -1078,6 +1079,7 @@ func parseChannelDef(L *lua.LState, defTbl *lua.LTable, plg *luaPlugin) sdk.Chan chDef.NoMemory = lua.LVAsBool(v) } chDef.ContextPolicy = defTbl.RawGetString("context_policy").String() + chDef.RecallPolicy = defTbl.RawGetString("recall_policy").String() if v := defTbl.RawGetString("cleaner"); v != nil && v.Type() == lua.LTFunction { chDef.Cleaner = makeLuaCleaner(plg, v.(*lua.LFunction)) } @@ -1085,8 +1087,9 @@ func parseChannelDef(L *lua.LState, defTbl *lua.LTable, plg *luaPlugin) sdk.Chan } // parseInjectOptions 解析 Lua 侧 options table 为 SDK InjectOptions。 -// 支持的键:no_memory(bool)、context_policy(string)、cleaner_name(string)、priority(string)。 -// 缺省/非表等价于零值(记入记忆 + 不裁剪),与旧的三参数注入完全等价。 +// 支持的键:no_memory(bool)、context_policy(string)、recall_policy(string)、 +// cleaner_name(string)、priority(string)。 +// 缺省/非表等价于零值(记入记忆 + 不裁剪 + 召回),与旧的三参数注入完全等价。 func parseInjectOptions(L *lua.LState, idx int) sdk.InjectOptions { opts := sdk.InjectOptions{} tbl, ok := L.Get(idx).(*lua.LTable) @@ -1097,6 +1100,7 @@ func parseInjectOptions(L *lua.LState, idx int) sdk.InjectOptions { opts.NoMemory = lua.LVAsBool(v) } opts.ContextPolicy = tbl.RawGetString("context_policy").String() + opts.RecallPolicy = tbl.RawGetString("recall_policy").String() opts.CleanerName = tbl.RawGetString("cleaner_name").String() opts.Priority = tbl.RawGetString("priority").String() return opts diff --git a/internal/plugin/proc/corehandler.go b/internal/plugin/proc/corehandler.go index 4fb3fd6..53fe433 100644 --- a/internal/plugin/proc/corehandler.go +++ b/internal/plugin/proc/corehandler.go @@ -215,6 +215,7 @@ type injectParams struct { TextRef SharedRef `json:"text_ref,omitempty"` NoMemory bool `json:"no_memory,omitempty"` ContextPolicy string `json:"context_policy,omitempty"` + RecallPolicy string `json:"recall_policy,omitempty"` CleanerName string `json:"cleaner_name,omitempty"` // Priority 声明中断注入的优先级(L1..L3);L4 内核独占,见 InjectOptions。 Priority string `json:"priority,omitempty"` @@ -237,6 +238,7 @@ type injectMediaParams struct { BlocksRef SharedRef `json:"blocks_ref,omitempty"` NoMemory bool `json:"no_memory,omitempty"` ContextPolicy string `json:"context_policy,omitempty"` + RecallPolicy string `json:"recall_policy,omitempty"` CleanerName string `json:"cleaner_name,omitempty"` Priority string `json:"priority,omitempty"` } @@ -245,10 +247,11 @@ type injectMediaParams struct { // // 单独提一个转换函数是为了让「默认值」只有一个出处:零值即记入记忆 + 不裁剪, // 与旧三参数注入等价。 -func pubSdkInjectOpts(noMemory bool, policy, cleanerName, priority string) pubsdk.InjectOptions { +func pubSdkInjectOpts(noMemory bool, policy, recallPolicy, cleanerName, priority string) pubsdk.InjectOptions { return pubsdk.InjectOptions{ - NoMemory: noMemory, ContextPolicy: policy, CleanerName: cleanerName, - Priority: clampExternalPriority(priority), + NoMemory: noMemory, ContextPolicy: policy, RecallPolicy: recallPolicy, + CleanerName: cleanerName, + Priority: clampExternalPriority(priority), } } @@ -280,6 +283,14 @@ func validateContextPolicy(where, policy string) error { return nil } +// validateRecallPolicy 校验召回策略取值,与 context_policy 同一套规则。 +func validateRecallPolicy(where, policy string) error { + if !pubsdk.ValidRecallPolicy(policy) { + return fmt.Errorf("%s: recall_policy 只允许 none/auto,实际 %q", where, policy) + } + return nil +} + // resolveJSONRef 若 ref 非零则从共享内存读取并 JSON 反序列化到 out; // ref 为零时不动 out(调用方已填的内联值生效)。 // @@ -424,6 +435,9 @@ func (h *coreHandler) toolRegister(params json.RawMessage) (interface{}, error) if err := validateContextPolicy("tool.register", p.Def.ContextPolicy); err != nil { return nil, err } + if err := validateRecallPolicy("tool.register", p.Def.RecallPolicy); err != nil { + return nil, err + } p.Def.Plugin = h.name // 函数本身不进 JSON;has_cleaner 只声明其存在,实际执行回到插件进程。 cleaner, err := h.cleanerProxy(CleanerScopeTool, p.Name, p.HasCleaner) diff --git a/internal/plugin/proc/corehandler_inject.go b/internal/plugin/proc/corehandler_inject.go index 8440bc6..95d8f53 100644 --- a/internal/plugin/proc/corehandler_inject.go +++ b/internal/plugin/proc/corehandler_inject.go @@ -24,7 +24,10 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectText", p.ContextPolicy); err != nil { return nil, err } - h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.CleanerName, p.Priority)) + if err := validateRecallPolicy("io.injectText", p.RecallPolicy); err != nil { + return nil, err + } + h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return nil, nil case MethodIOInjectInterrupt: var p injectParams @@ -34,7 +37,10 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectInterrupt", p.ContextPolicy); err != nil { return nil, err } - h.sdk.InjectInterruptTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.CleanerName, p.Priority)) + if err := validateRecallPolicy("io.injectInterrupt", p.RecallPolicy); err != nil { + return nil, err + } + h.sdk.InjectInterruptTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return nil, nil case MethodIOInjectTextNoMem: var p injectParams @@ -44,8 +50,11 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectTextNoMem", p.ContextPolicy); err != nil { return nil, err } + if err := validateRecallPolicy("io.injectTextNoMem", p.RecallPolicy); err != nil { + return nil, err + } // 旧 RPC 语义就是「不进记忆」,显式标志位只可能再叠上 context_policy。 - h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(true, p.ContextPolicy, p.CleanerName, p.Priority)) + h.sdk.InjectTextOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(true, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return nil, nil case MethodIOInjectSync: var p injectParams @@ -55,7 +64,10 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectInputSync", p.ContextPolicy); err != nil { return nil, err } - reply := h.sdk.InjectInputSyncOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.CleanerName, p.Priority)) + if err := validateRecallPolicy("io.injectInputSync", p.RecallPolicy); err != nil { + return nil, err + } + reply := h.sdk.InjectInputSyncOpts(p.Source, p.Channel, h.resolveText(p), pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return map[string]interface{}{"reply": reply}, nil case MethodIOInjectMedia: @@ -66,11 +78,14 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectMedia", p.ContextPolicy); err != nil { return nil, err } + if err := validateRecallPolicy("io.injectMedia", p.RecallPolicy); err != nil { + return nil, err + } blocks, err := h.resolveBlocks(p) if err != nil { return nil, err } - h.sdk.InjectInputMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.CleanerName, p.Priority)) + h.sdk.InjectInputMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return nil, nil case MethodIOInjectMediaSync: @@ -81,11 +96,14 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectMediaSync", p.ContextPolicy); err != nil { return nil, err } + if err := validateRecallPolicy("io.injectMediaSync", p.RecallPolicy); err != nil { + return nil, err + } blocks, err := h.resolveBlocks(p) if err != nil { return nil, err } - reply := h.sdk.InjectInputMediaSyncOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.CleanerName, p.Priority)) + reply := h.sdk.InjectInputMediaSyncOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return map[string]interface{}{"reply": reply}, nil case MethodIOInjectInterruptMedia: @@ -96,11 +114,14 @@ func (h *coreHandler) handleInject(method string, params json.RawMessage) (inter if err := validateContextPolicy("io.injectInterruptMedia", p.ContextPolicy); err != nil { return nil, err } + if err := validateRecallPolicy("io.injectInterruptMedia", p.RecallPolicy); err != nil { + return nil, err + } blocks, err := h.resolveBlocks(p) if err != nil { return nil, err } - h.sdk.InjectInterruptMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.CleanerName, p.Priority)) + h.sdk.InjectInterruptMediaOpts(p.Source, p.Channel, p.Text, blocks, pubSdkInjectOpts(p.NoMemory, p.ContextPolicy, p.RecallPolicy, p.CleanerName, p.Priority)) return nil, nil // ---- 多模态注入 ---- diff --git a/internal/plugin/proc/corehandler_register.go b/internal/plugin/proc/corehandler_register.go index 9121a29..45641c7 100644 --- a/internal/plugin/proc/corehandler_register.go +++ b/internal/plugin/proc/corehandler_register.go @@ -47,6 +47,9 @@ func (h *coreHandler) handleRegister(method string, params json.RawMessage) (int if err := validateContextPolicy("input.register", p.Def.ContextPolicy); err != nil { return nil, err } + if err := validateRecallPolicy("input.register", p.Def.RecallPolicy); err != nil { + return nil, err + } // 整体传 p.Def(只是把函数型的 Cleaner 换成代理),不要手写字段白名单: // 白名单会让新增字段静默丢失。 def := p.Def diff --git a/internal/plugin/proc/priority_clamp_test.go b/internal/plugin/proc/priority_clamp_test.go index fa49b1b..1197692 100644 --- a/internal/plugin/proc/priority_clamp_test.go +++ b/internal/plugin/proc/priority_clamp_test.go @@ -35,14 +35,14 @@ func TestClampExternalPriority_RejectsL4(t *testing.T) { // 贯穿 pubSdkInjectOpts:RPC 报文里的 priority 必须经过夹取才落到 InjectOptions。 func TestPubSdkInjectOpts_ClampsPriority(t *testing.T) { - got := pubSdkInjectOpts(true, "prune", "cleaner", "L4") + got := pubSdkInjectOpts(true, "prune", "none", "cleaner", "L4") if got.Priority != pubsdk.PriorityL3 { t.Fatalf("经桥后的优先级=%q,期望 L3", got.Priority) } - if !got.NoMemory || got.ContextPolicy != "prune" || got.CleanerName != "cleaner" { + if !got.NoMemory || got.ContextPolicy != "prune" || got.RecallPolicy != "none" || got.CleanerName != "cleaner" { t.Fatalf("其它字段被改动:%+v", got) } - if l2 := pubSdkInjectOpts(false, "", "", "L2"); l2.Priority != pubsdk.PriorityL2 { + if l2 := pubSdkInjectOpts(false, "", "", "", "L2"); l2.Priority != pubsdk.PriorityL2 { t.Fatalf("L2 应原样通过,实际 %q", l2.Priority) } } diff --git a/internal/plugin/proc/recallpolicy_test.go b/internal/plugin/proc/recallpolicy_test.go new file mode 100644 index 0000000..5fe00c1 --- /dev/null +++ b/internal/plugin/proc/recallpolicy_test.go @@ -0,0 +1,31 @@ +package proc + +import ( + "strings" + "testing" +) + +// 非法 recall_policy 必须报错,而不是静默当成默认(auto)。 +// +// 与 context_policy 同理:静默降级会让调用方以为自己声明的“不召回”在生效, +// 而 meta 文本(如中断通知)仍在照常召回,且没有任何报错可循。 +func TestValidateRecallPolicy(t *testing.T) { + ok := []string{"", "none", "auto"} + for _, policy := range ok { + if err := validateRecallPolicy("tool.register", policy); err != nil { + t.Errorf("合法取值 %q 被拒绝: %v", policy, err) + } + } + + bad := []string{"auto ", "AUTO", "None", "true", "always", "召回"} + for _, policy := range bad { + err := validateRecallPolicy("io.injectText", policy) + if err == nil { + t.Errorf("非法取值 %q 应被拒绝", policy) + continue + } + if !strings.Contains(err.Error(), "io.injectText") || !strings.Contains(err.Error(), policy) { + t.Errorf("错误信息应包含位置与实际值,实际: %v", err) + } + } +} diff --git a/internal/sdk/plugin.go b/internal/sdk/plugin.go index 468b3d4..4cb5b3a 100644 --- a/internal/sdk/plugin.go +++ b/internal/sdk/plugin.go @@ -72,6 +72,12 @@ const ( ContextPolicyPrune = pubsdk.ContextPolicyPrune ) +// 召回策略取值:与 ContextPolicy 正交(裁剪 vs 召回)。 +const ( + RecallPolicyNone = pubsdk.RecallPolicyNone + RecallPolicyAuto = pubsdk.RecallPolicyAuto +) + type DisabledPluginInfo struct { Name string `json:"name"` DisabledAt string `json:"disabled_at"` diff --git a/third_party/homeagent-sdk/example/qq/plugin.go b/third_party/homeagent-sdk/example/qq/plugin.go index 9b375c9..df12820 100644 --- a/third_party/homeagent-sdk/example/qq/plugin.go +++ b/third_party/homeagent-sdk/example/qq/plugin.go @@ -439,7 +439,9 @@ type 枚举: text(文字)/ voice(语音转文字后发送)/ image(图 } return cleaned } - s.RegisterInputChannel("qq", sdk.ChannelDef{NoMemory: true, Cleaner: inputCleaner}) + // qq 通道到达的是**中断通知(meta)**,不是用户正文,不据它召回; + // 真实正文由 qq_get_message 取回后由该工具声明 RecallPolicy=auto 触发召回。 + s.RegisterInputChannel("qq", sdk.ChannelDef{NoMemory: true, Cleaner: inputCleaner, RecallPolicy: sdk.RecallPolicyNone}) // 查询类工具输出清洗器:提取 JSON 中的 content/文本字段参与向量化 cleaner := func(output string) string { @@ -459,6 +461,9 @@ type 枚举: text(文字)/ voice(语音转文字后发送)/ image(图 // 不裁的后果是每条 QQ 消息的完整正文都留在 L0 上下文里, // 长会话下持续挤占 token 预算(§13.8)。 ContextPolicy: "prune", + // 正文才是真实内容:取回后用**正文**触发一次召回, + // 而不是用中断通知的 meta 文本去召回(那是无关词)。 + RecallPolicy: "auto", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "message_id": map[string]interface{}{"type": "integer", "description": "NapCat消息ID(从中断消息的 message_id=N 或 reply_to.message_id 获取)"}, @@ -1482,6 +1487,8 @@ func (p *Plugin) injectInterrupt(text, level string) { p.sdk.InjectInterruptTextOpts(p.name, p.name, text, sdk.InjectOptions{ NoMemory: true, Priority: level, + // 中断文本是路由/取正文的指令,不是对话内容,不据它召回。 + RecallPolicy: sdk.RecallPolicyNone, }) } @@ -2802,7 +2809,7 @@ func (p *Plugin) handleDownloadFile(args map[string]interface{}) (interface{}, e // Priority:同上,QQ 侧一律低级别中断(L1)。 p.sdk.InjectInterruptTextOpts(p.name, p.name, fmt.Sprintf("文件下载完成: %s,保存在 %s", filepath.Base(savePath), savePath), - sdk.InjectOptions{NoMemory: true, Priority: sdk.PriorityL1}) + sdk.InjectOptions{NoMemory: true, Priority: sdk.PriorityL1, RecallPolicy: sdk.RecallPolicyNone}) } } else { errMsg = "下载失败,文件可能已过期" diff --git a/third_party/homeagent-sdk/sdk/plugin.go b/third_party/homeagent-sdk/sdk/plugin.go index 72451a7..a1fab03 100644 --- a/third_party/homeagent-sdk/sdk/plugin.go +++ b/third_party/homeagent-sdk/sdk/plugin.go @@ -54,6 +54,26 @@ func ValidContextPolicy(policy string) bool { return false } +// 召回策略:决定一次工具调用/输入/注入是否据其内容**召回**(注入)相关记忆。 +// +// 与 ContextPolicy **正交**:ContextPolicy 管「裁剪」(把低相关 L0 事件归档), +// RecallPolicy 管「召回」(把 L2/L3 的相关记忆注入本轮)。两者默认值刻意相反—— +// 裁剪是破坏性的,默认关(必须显式声明);召回是只读增量、日常对话本就需要, +// 默认 auto(输入/注入),仅**工具**默认 none(工具输出多为噪声,按需声明)。 +const ( + RecallPolicyNone = "none" + RecallPolicyAuto = "auto" +) + +// ValidRecallPolicy 校验召回策略取值;空串按调用面取默认值。 +func ValidRecallPolicy(policy string) bool { + switch policy { + case "", RecallPolicyNone, RecallPolicyAuto: + return true + } + return false +} + // InjectOptions 声明一次注入行为在记忆层与上下文层的表现。 // // 零值 = 记入记忆 + 不裁剪上下文,与历史行为(三参数注入方法)完全一致, @@ -65,6 +85,7 @@ func ValidContextPolicy(policy string) bool { // // NoMemory: 此次注入不参与记忆计算(向量化/关键词提取/蒸馏),原文仍留在上下文 // ContextPolicy: 此次注入后是否依据(清洗后的)内容裁剪上下文;默认不裁剪。 +// RecallPolicy: 此次注入是否依据(清洗后的)内容召回相关记忆;默认 auto(召回)。 // // 中断注入也允许声明 prune——它同样会携带内容进入上下文。 // @@ -77,7 +98,11 @@ func ValidContextPolicy(policy string) bool { type InjectOptions struct { NoMemory bool ContextPolicy string - CleanerName string + // RecallPolicy 声明此次注入是否据其内容召回相关记忆。 + // 空串 = 默认(输入/注入 auto,即保持既有「每条输入都召回」的行为); + // RecallPolicyNone 显式关闭(如中断通知的 meta 文本不该据它召回)。 + RecallPolicy string + CleanerName string // Priority 声明**中断注入**的优先级(仅 InjectInterrupt* 有意义)。 // @@ -106,6 +131,7 @@ const ( // NoMemory: 此通道输入/输出不参与记忆计算(向量化/关键词提取/蒸馏),但原文保留在上下文中 // Cleaner: 计算层过滤函数,不改原文;仅在向量化/jieba/蒸馏/存档提取关键词时调用 // ContextPolicy: 此通道的输入到达后是否据此裁剪上下文,默认 none(不裁剪) +// RecallPolicy: 此通道的输入到达后是否据此召回相关记忆,默认 auto(召回) // // JSON tag 是必需的:通道定义要跨进程传给内核,而 Cleaner 是函数(必须忽略)。 // 没有 tag 时既无法整体 marshal(func 不支持),又会诱使调用方手写字段白名单—— @@ -114,6 +140,8 @@ type ChannelDef struct { NoMemory bool `json:"no_memory,omitempty"` Cleaner func(string) string `json:"-"` ContextPolicy string `json:"context_policy,omitempty"` + // RecallPolicy 见 InjectOptions.RecallPolicy;空串等价 auto(保持既有行为)。 + RecallPolicy string `json:"recall_policy,omitempty"` } // StageContext provides context for stage handlers. @@ -180,6 +208,10 @@ type ToolDef struct { NoMemory bool `json:"no_memory,omitempty"` // 此工具输出不参与记忆计算,但原文保留 Cleaner func(string) string `json:"-"` // 计算层过滤函数,不改原文;仅在向量化/jieba/蒸馏时调用 ContextPolicy string `json:"context_policy,omitempty"` // 上下文策略:""(默认,不裁剪) / ContextPolicyNone / ContextPolicyPrune + // RecallPolicy 声明此工具输出是否触发一次记忆召回(注入)。 + // ""(默认 none) / RecallPolicyNone / RecallPolicyAuto。 + // 默认 none:多数工具输出是噪声;需要「取回真实内容后据它召回」的工具(如 qq_get_message)应显式声明 auto。 + RecallPolicy string `json:"recall_policy,omitempty"` } // IOInjector provides methods for injecting input and interrupts into the agent pipeline.