mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-21 09:28:14 +00:00
feat(core): 注入行为的记忆/裁剪标志位落地 + jieba 词库内嵌 + Windows 改走 WSL
配套 SDK 提交:homeagent-sdk ba49dfd(公开 API 纯追加,无签名变更)。
本仓第三方的库镜像同步至该版本,以保证全新 clone 能编译。
## 1. 注入标志位(内核侧)
- 7 条注入路径(排队/中断/同步 × 纯文本/带媒体 + 旧 NoMem 变体)解析并转发
no_memory / context_policy / cleaner_name;策略在入口**校验**,
非法值报错而不是静默降级成 none(降级会让调用方以为自己声明的裁剪在生效)。
- 新增 validateContextPolicy(与 tool.register 同一套规则)与 pubSdkInjectOpts。
- input.register 不再手写字段白名单重建 ChannelDef,改为整体传递 + 补 ContextPolicy。
- io 层:applyInjectOpts 把标志位写进事件 payload,仅非零时写
(零值与旧 payload 逐字节一致,事件订阅方与旧内核都不受影响)。
- ioAdapter / procCore / internal-sdk 别名补齐六个 *Opts 实现。
## 2. 修掉「输入无条件裁剪」这个真缺陷
eventloop 此前对**每条非中断输入**都调 `context.Prune(...)`:破坏性(低相关事件被
归档移出上下文)且无法从调用点看出是谁触发的。改为 pruneOnInput/pruneDeclared:
优先级:注入点声明(payload.context_policy)> 通道声明(ChannelDef.ContextPolicy)
> 默认**不裁剪**
查询向量仍取清洗后的内容;新增 cleanInputFor 解析清洗文本,优先级为
注入点声明的 cleaner(cleaner_name)> 按 source 查到的通道 cleaner > 原文,
名字查不到时**记日志再回退**(注入是 fire-and-forget,插件看不到错误,
至少要在内核日志留下「你声明的清洗没生效」的痕迹)。
## 3. jieba 词库内嵌(修「猜 GOMODCACHE → 静默失效」)
原 jiebaDictDir() 去猜 GOMODCACHE/GOPATH/~/go/pkg/mod,部署机上通常没有 Go 模块
缓存 → GetJieba() 返回 nil → 分词/关键词提取/NLP 依存解析(进而 doc→graph 三元组
抽取)/静态词向量 tokenizer **一律静默返回空列表**,只有一行日志。本机看起来正常
只因开发机与生产机重合、恰好有那份缓存。
现在词库随二进制分发:internal/memory/jiebadict/ 5 文件约 11.6MB + go:embed,
按**内容哈希**命名缓存目录落盘(词库升级不复用旧文件),已齐全则跳过写入。
模块缓存降为兜底。homed 体积 32MB。
顺带确认(并有测试佐证):gojieba 的 Tag() 不需要 pos_dict/ 目录——
cppjieba 的 PosTagger 从主词典每行的词性列取 tag。
## 4. homed 放弃 Windows 原生,改走 WSL2
插件体系依赖「继承的 fd」+「统一共享内存区的段内偏移解引用」,Windows 既无 fd
继承语义,其句柄模型也无法表达后者;强行适配等于再维护一套平台专属 ABI
(C ABI 时代三套 ABI 并存曾导致改写型插件在某平台静默失效)。
- cmd/homed/platform_{windows,other}.go:原生 Windows 启动即拒绝并打印 WSL2 指引。
- internal/plugin/proc/shmalloc_windows.go:allocShm 直接返回「请用 WSL2」,
**不返回半可用的段**(与 shmalloc_other.go 同风格:未支持平台显式报错);
procEnvForShm 返回 nil。顺手修掉两处长期编译错误
(cryptorand→rand、h.evData→h.unified.evtData),使 GOOS=windows 至少能编译。
注:homed 本就编不出 Windows——internal/memory 依赖 cgo-only 的 gojieba。
- deploy/packaging/installer.nsi:不再安装 homed.exe/initconfig.exe,改为携带
**linux payload** 并调用新的 install-via-wsl.ps1;退出码 20/21 表示
「需先装 WSL/发行版」,走指引而非报错。
- deploy/packaging/windows/install-via-wsl.ps1(新):检测 WSL → 引导安装 →
确保 WSL2 → 送包进发行版 → 在 WSL 内按 Linux 方式安装。**复用 Linux 包与
linux/setup.sh**,不另写一套安装逻辑;落点与 deb 布局统一
(/usr/bin/homed + /usr/lib/homeagent/setup.sh)。
- deploy/packaging/linux/setup.sh:API Key 允许 HOMEAGENT_API_KEY 覆盖
(否则安装器界面显示一份、config.db 里另一份 → 登录不上)。
- deploy/packaging/build.sh:windows 目标只构建 waiter + gui,并新增
stage_linux_payload 把 Linux 包暂存给安装器;homed/initconfig 在 windows
目标下明确拒绝。
## 5. 插件调用点统一写明意图
- webui 的 OpenAI 兼容端点(固定提示词模板)→ InjectTextSyncNoMemory。
- agentcli 的 5 处纯状态通知(已启动/超时/执行结束/进程退出/读取结束)→ NoMemory;
**带输出**的 2 处(定时反馈、有新输出)刻意保留记忆并注明理由。
- timer 的定时提醒 → NoMemory(中断本来也隐含 NoMemory,这里是写明意图)。
## 6. 版本
meta.Version 仍为 1.2.0(main 是下一个未发布中版本);
SDKCompatibleVersion 1.1.0 → **1.2.0**(本内核已实现 SDK 1.2.0 全部新增方法)。
## 测试
- core:默认不裁剪(无声明/none/空)、通道 opt-in、注入点双向覆盖通道、
nil context/io 安全、cleaner 优先级与未知名回退。
- io:零值 opts 与历史 payload 逐键相同;text/中断/媒体三类注入标志位都落到
payload;旧方法仍生效。
- proc:validateContextPolicy 只接受 ""/none/prune,报错含位置与实际值;
**跨进程** e2e——testdata 插件经 io.injectText 送出三个标志位,断言它们穿过 RPC
到达内核。
- memory:模块缓存不可见时内嵌词库仍可用(分词与 POS 内容词均非空)、
落盘幂等、内容哈希稳定。
验证:go build ./... / go vet ./... / go vet -tags onnxruntime ./...
go test -short ./internal/memory/... ./internal/nlp/... ./internal/plugin/...
./internal/agent/{core,io}/... ./pkg/...
This commit is contained in:
@ -53,7 +53,7 @@ func GetJieba() *gojieba.Jieba {
|
||||
}()
|
||||
d := jiebaDictDir()
|
||||
if d == "" {
|
||||
log.Printf("[jieba] no dictionary directory found, jieba disabled")
|
||||
log.Printf("[jieba] 未找到词库目录(内嵌落盘失败且模块缓存也不存在),jieba disabled")
|
||||
return
|
||||
}
|
||||
jiebaInst = gojieba.NewJieba(
|
||||
@ -68,9 +68,24 @@ func GetJieba() *gojieba.Jieba {
|
||||
}
|
||||
|
||||
func jiebaDictDir() string {
|
||||
// 首选内嵌词库:它是产物的一部分,与二进制同版本、不依赖宿主环境。
|
||||
//
|
||||
// 以前这里只猜 GOMODCACHE/GOPATH/~/go/pkg/mod,部署机上通常没有 Go 模块缓存,
|
||||
// 于是分词与关键词提取会**静默退回空列表**(详见 jieba_embed.go 的说明)。
|
||||
if dir, err := materializeJiebaDict(); err == nil && dir != "" {
|
||||
return dir
|
||||
}
|
||||
log.Printf("[jieba] 内嵌词库落盘失败,回退到模块缓存查找(内嵌失败通常意味着缓存目录不可写)")
|
||||
|
||||
// 回退:开发机上存在的模块缓存(仅作为兵底,不应依赖它)。
|
||||
//
|
||||
// GOMODCACHE is typically $GOPATH/pkg/mod. When set, Go writes modules
|
||||
// under <GOMODCACHE>/github.com/... . Look first at GOMODCACHE, then
|
||||
// derive from GOPATH, then try common locations.
|
||||
return jiebaDictDirFromModuleCache()
|
||||
}
|
||||
|
||||
func jiebaDictDirFromModuleCache() string {
|
||||
candidates := []string{
|
||||
os.Getenv("GOMODCACHE"),
|
||||
}
|
||||
|
||||
123
internal/memory/jieba_embed.go
Normal file
123
internal/memory/jieba_embed.go
Normal file
@ -0,0 +1,123 @@
|
||||
// Package memory 的 jieba 词库内嵌。
|
||||
//
|
||||
// 为什么要把词库嵌进二进制,而不是像以前那样去猜 Go 模块缓存路径:
|
||||
//
|
||||
// 原实现是 `jiebaDictDir()` 依次试 GOMODCACHE / GOPATH / ~/go/pkg/mod,去找
|
||||
// `github.com/yanyiwu/gojieba@v1.4.7/deps/cppjieba/dict`。部署机上通常**没有**
|
||||
// Go 模块缓存,于是返回 "",`GetJieba()` 返回 nil,四个分词/关键词函数
|
||||
// **一律静默返回空列表**(只在首次打一行「jieba disabled」)。
|
||||
//
|
||||
// 后果不是「少了个优化」而是**能力整体消失**:图记忆的关键词提取、文档
|
||||
// TF-IDF 分词、NLP 依存解析(进而 doc→graph 三元组抽取)全部退化为空。
|
||||
// 而本机之所以看起来正常,只是因为开发机与生产机重合、恰好有那份模块缓存。
|
||||
//
|
||||
// 内嵌后词库成为产物的一部分:与二进制同版本、随二进制分发、不依赖宿主环境。
|
||||
// 代价是包体大 ~11.6MB(jieba.dict.utf8 5.1M + idf.utf8 6.0M + hmm_model 0.5M + …),
|
||||
// 这是可接受的——它换来的是「装到哪都能用」。
|
||||
//
|
||||
// 关于 POS:gojieba 的 Tag() 不读 `pos_dict/` 目录,而是从主词典每行的
|
||||
// 词性列取 tag(cppjieba 的 PosTagger::LookupTag 走 dict->Find(...)->tag),
|
||||
// 取不到时用 SpecialRule 按字符类型兜底。所以这 5 个文件已足够同时支撑
|
||||
// Cut 与 Tag,无需再嵌 pos_dict/。
|
||||
package memory
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
//go:embed jiebadict/*
|
||||
var jiebaDictFS embed.FS
|
||||
|
||||
// jiebaDictFiles 是 gojieba.NewJieba 需要的 5 个文件,顺序与它的参数一致:
|
||||
// dict, hmm, user, idf, stop_words。
|
||||
var jiebaDictFiles = []string{
|
||||
"jieba.dict.utf8",
|
||||
"hmm_model.utf8",
|
||||
"user.dict.utf8",
|
||||
"idf.utf8",
|
||||
"stop_words.utf8",
|
||||
}
|
||||
|
||||
// materializeJiebaDict 把内嵌词库落盘,返回目录路径。
|
||||
//
|
||||
// gojieba 的 C++ API 只接受**文件路径**(NewJieba 会对每个路径 os.Stat,
|
||||
// 缺失就 panic),所以必须先落盘再传路径。
|
||||
//
|
||||
// 落盘位置与幂等性:
|
||||
// - 用内容哈希命名目录:词库升级后不会复用旧文件(否则会出现「新旧词库混用」
|
||||
// 这种最难查的一类问题——分词结果与版本对不上)。
|
||||
// - 已存在且大小一致就跳过写入:正常启动只做几次 stat。
|
||||
func materializeJiebaDict() (string, error) {
|
||||
sum, err := jiebaDictDigest()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
base, err := os.UserCacheDir()
|
||||
if err != nil || base == "" {
|
||||
base = os.TempDir()
|
||||
}
|
||||
dir := filepath.Join(base, "homeagent", "jieba-"+sum)
|
||||
|
||||
if jiebaDictComplete(dir) {
|
||||
return dir, nil
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("创建词库目录: %w", err)
|
||||
}
|
||||
for _, name := range jiebaDictFiles {
|
||||
data, err := jiebaDictFS.ReadFile("jiebadict/" + name)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("读取内嵌词库 %s: %w", name, err)
|
||||
}
|
||||
path := filepath.Join(dir, name)
|
||||
// 先写临时文件再 rename:避免并发启动时读到写了一半的词库。
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o644); err != nil {
|
||||
return "", fmt.Errorf("写出词库 %s: %w", name, err)
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
return "", fmt.Errorf("落位词库 %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
// jiebaDictDigest 对全部内嵌词库内容求哈希,作为落盘目录名的一部分。
|
||||
func jiebaDictDigest() (string, error) {
|
||||
h := sha256.New()
|
||||
// 按固定顺序喂入:embed.FS 的遍历顺序不保证稳定,顺序变了哈希就变,
|
||||
// 会导致每次启动都重建一份词库。
|
||||
names := append([]string(nil), jiebaDictFiles...)
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
data, err := jiebaDictFS.ReadFile("jiebadict/" + name)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("读取内嵌词库 %s: %w", name, err)
|
||||
}
|
||||
fmt.Fprintf(h, "%s:%d:", name, len(data))
|
||||
h.Write(data)
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))[:16], nil
|
||||
}
|
||||
|
||||
// jiebaDictComplete 判断目录下 5 个词库是否齐全且大小与内嵌版本一致。
|
||||
func jiebaDictComplete(dir string) bool {
|
||||
for _, name := range jiebaDictFiles {
|
||||
want, err := fs.Stat(jiebaDictFS, "jiebadict/"+name)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
got, err := os.Stat(filepath.Join(dir, name))
|
||||
if err != nil || got.Size() != want.Size() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
98
internal/memory/jieba_embed_test.go
Normal file
98
internal/memory/jieba_embed_test.go
Normal file
@ -0,0 +1,98 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 内嵌词库必须自足:把 GOMODCACHE/GOPATH/HOME 全部指向不存在的路径,
|
||||
// 分词与关键词提取仍然要工作。
|
||||
//
|
||||
// 这正是修复前的故障场景:原实现只去猜 Go 模块缓存,部署机上没有那份缓存时
|
||||
// GetJieba() 返回 nil,四个函数静默返回空列表——关键词提取、文档 TF-IDF 分词、
|
||||
// NLP 依存解析(进而 doc→graph 三元组抽取)一起失效,且只有一行日志。
|
||||
func TestEmbeddedJiebaDictIsSelfContained(t *testing.T) {
|
||||
t.Setenv("GOMODCACHE", filepath.Join(t.TempDir(), "nonexistent"))
|
||||
t.Setenv("GOPATH", filepath.Join(t.TempDir(), "nonexistent"))
|
||||
t.Setenv("HOME", filepath.Join(t.TempDir(), "nonexistent"))
|
||||
// 清掉可能已被其它测试初始化过的单例。
|
||||
jiebaOnce = sync.Once{}
|
||||
jiebaInst = nil
|
||||
t.Cleanup(func() {
|
||||
jiebaOnce = sync.Once{}
|
||||
jiebaInst = nil
|
||||
})
|
||||
|
||||
if x := GetJieba(); x == nil {
|
||||
t.Fatal("模块缓存不可见时 jieba 必须仍能初始化(词库应来自内嵌副本)")
|
||||
}
|
||||
|
||||
words := TokenizeWords("今天天气很好,我们去公园散步")
|
||||
if len(words) == 0 {
|
||||
t.Fatal("分词结果为空:内嵌词库没有真正生效")
|
||||
}
|
||||
t.Logf("分词结果: %v", words)
|
||||
|
||||
// 内容词(名词/动词/形容词)——依赖词典里的词性列,顺便验证 Tag 路径可用。
|
||||
content := TokenizeContentWords("北京是中国的首都,这里有很多历史建筑")
|
||||
if len(content) == 0 {
|
||||
t.Fatal("内容词为空:Tag(词性标注)路径失效")
|
||||
}
|
||||
t.Logf("内容词: %v", content)
|
||||
|
||||
if kw := ExtractKeywords("机器学习模型训练需要大量数据和算力"); len(kw) == 0 {
|
||||
t.Fatal("关键词为空")
|
||||
}
|
||||
}
|
||||
|
||||
// 落盘目录必须幂等:第二次调用不应重写文件(正常启动只做几次 stat)。
|
||||
func TestMaterializeJiebaDictIsIdempotent(t *testing.T) {
|
||||
dir, err := materializeJiebaDict()
|
||||
if err != nil {
|
||||
t.Fatalf("materializeJiebaDict: %v", err)
|
||||
}
|
||||
for _, name := range jiebaDictFiles {
|
||||
p := filepath.Join(dir, name)
|
||||
fi, err := os.Stat(p)
|
||||
if err != nil {
|
||||
t.Fatalf("缺少词库文件 %s: %v", name, err)
|
||||
}
|
||||
if fi.Size() == 0 {
|
||||
t.Fatalf("词库文件 %s 为空", name)
|
||||
}
|
||||
}
|
||||
|
||||
// 记下 mtime,再调一次,必须完全没动过。
|
||||
before, _ := os.Stat(filepath.Join(dir, "jieba.dict.utf8"))
|
||||
dir2, err := materializeJiebaDict()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir2 != dir {
|
||||
t.Fatalf("目录名不稳定:%s vs %s(会导致每次启动重建词库)", dir, dir2)
|
||||
}
|
||||
after, _ := os.Stat(filepath.Join(dir, "jieba.dict.utf8"))
|
||||
if !before.ModTime().Equal(after.ModTime()) {
|
||||
t.Fatal("已存在完整词库时不应重写文件")
|
||||
}
|
||||
}
|
||||
|
||||
// 词库内容哈希必须稳定:否则目录名每次都变,等于每次启动都重建。
|
||||
func TestJiebaDictDigestStable(t *testing.T) {
|
||||
a, err := jiebaDictDigest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := jiebaDictDigest()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a != b {
|
||||
t.Fatalf("哈希不稳定: %s vs %s", a, b)
|
||||
}
|
||||
if len(a) != 16 {
|
||||
t.Fatalf("哈希长度异常: %q", a)
|
||||
}
|
||||
}
|
||||
34
internal/memory/jiebadict/hmm_model.utf8
Normal file
34
internal/memory/jiebadict/hmm_model.utf8
Normal file
File diff suppressed because one or more lines are too long
258826
internal/memory/jiebadict/idf.utf8
Normal file
258826
internal/memory/jiebadict/idf.utf8
Normal file
File diff suppressed because it is too large
Load Diff
348982
internal/memory/jiebadict/jieba.dict.utf8
Normal file
348982
internal/memory/jiebadict/jieba.dict.utf8
Normal file
File diff suppressed because it is too large
Load Diff
1534
internal/memory/jiebadict/stop_words.utf8
Normal file
1534
internal/memory/jiebadict/stop_words.utf8
Normal file
File diff suppressed because it is too large
Load Diff
4
internal/memory/jiebadict/user.dict.utf8
Normal file
4
internal/memory/jiebadict/user.dict.utf8
Normal file
@ -0,0 +1,4 @@
|
||||
云计算
|
||||
韩玉鉴赏
|
||||
蓝翔 nz
|
||||
区块链 10 nz
|
||||
Reference in New Issue
Block a user